@nice2dev/ui-platform 1.1.7 → 1.1.10
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 +9 -9
- package/dist/index.d.ts +526 -205
- package/dist/index.mjs +4221 -3781
- package/dist/ui-platform.css +1 -1
- package/package.json +2 -1
- package/dist/style.css +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var Ve=Object.defineProperty;var We=(m,A,x)=>A in m?Ve(m,A,{enumerable:!0,configurable:!0,writable:!0,value:x}):m[A]=x;var ae=(m,A,x)=>We(m,typeof A!="symbol"?A+"":A,x);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),ie=e.createContext(null),Ge={showSplash:!0,splashDuration:2e3,autoHideSplash:!0,showProgress:!0,showTaskNames:!0,globalTimeout:6e4,autoRecovery:!0,recoveryAttempts:3,recoveryDelay:2e3,checkUpdates:!1,sendAnalytics:!1},ue=e.forwardRef((m,A)=>{const{tasks:x=[],config:k,splash:p,errorScreen:N,onComplete:O,onTaskComplete:q,onError:o,onRecovery:u,children:S}=m,D={...Ge,...k},b=e.useRef(0),f=e.useRef(x),g=e.useRef(null),[j,B]=e.useState(D.showSplash),[L,M]=e.useState({phase:"initializing",isLoading:!0,isReady:!1,hasError:!1,progress:0,completedTasks:0,totalTasks:x.length,results:[],recoveryAttempt:0,totalDuration:0}),W=e.useCallback(async a=>{const n=Date.now();let s=0;const r=async()=>{try{const c=a.timeout||D.globalTimeout,l=new Promise((_,y)=>{setTimeout(()=>y(new Error("Task timeout")),c)});return await Promise.race([a.execute(),l]),{taskId:a.id,success:!0,duration:Date.now()-n,retriesUsed:s}}catch(c){const l=a.retries??0;return s<l?(s++,await new Promise(_=>setTimeout(_,500)),r()):{taskId:a.id,success:!1,error:c instanceof Error?c:new Error(String(c)),duration:Date.now()-n,retriesUsed:s}}};return r()},[D.globalTimeout]),X=e.useCallback(a=>{const n=[],s=[...a],r=new Set;for(;s.length>0;){const c=s.filter(_=>_.dependencies?_.dependencies.every(y=>r.has(y)):!0);if(c.length===0){n.push(...s);break}c.sort((_,y)=>(y.priority??0)-(_.priority??0));const l=c[0];n.push(l),r.add(l.id),s.splice(s.indexOf(l),1)}return n},[]),F=e.useCallback(async()=>{var r;b.current=Date.now(),g.current=new AbortController;const a=X(f.current),n=[];M(c=>({...c,phase:"loading",isLoading:!0,isReady:!1,hasError:!1,errorMessage:void 0,progress:0,completedTasks:0,totalTasks:a.length,results:[]}));for(let c=0;c<a.length&&!((r=g.current)!=null&&r.signal.aborted);c++){const l=a[c];M(y=>({...y,currentTask:l.name,progress:Math.round(c/a.length*100)}));const _=await W(l);if(n.push(_),M(y=>({...y,completedTasks:c+1,results:[...y.results,_]})),q==null||q(_),!_.success&&l.critical){const y=_.error||new Error("Critical task failed");o==null||o(y,l.id),M(h=>({...h,phase:"error",isLoading:!1,hasError:!0,errorMessage:y.message}));return}}const s=Date.now()-b.current;if(M(c=>({...c,phase:"ready",isLoading:!1,isReady:!0,currentTask:void 0,progress:100,totalDuration:s})),O==null||O(n),D.autoHideSplash){const c=Date.now()-b.current,l=Math.max(0,D.splashDuration-c);setTimeout(()=>{B(!1)},l)}},[X,W,D.autoHideSplash,D.splashDuration,q,o,O]),z=e.useCallback(async()=>{g.current&&g.current.abort(),M(a=>({...a,recoveryAttempt:0})),B(D.showSplash),await F()},[D.showSplash,F]),P=e.useCallback(()=>{g.current&&g.current.abort(),M(a=>({...a,phase:"ready",isLoading:!1,isReady:!0,progress:100})),B(!1)},[]),H=e.useCallback(()=>{B(!1)},[]),d=e.useCallback(async()=>{const a=L.recoveryAttempt+1;a>D.recoveryAttempts||(M(n=>({...n,phase:"recovery",recoveryAttempt:a})),u==null||u(a),await new Promise(n=>setTimeout(n,D.recoveryDelay)),await F())},[L.recoveryAttempt,D.recoveryAttempts,D.recoveryDelay,u,F]),I=e.useCallback(a=>{f.current=[...f.current,a]},[]),E=e.useCallback(a=>{f.current=f.current.filter(n=>n.id!==a)},[]),R=e.useCallback(a=>L.results.find(n=>n.taskId===a),[L.results]);e.useEffect(()=>{L.hasError&&D.autoRecovery&&L.recoveryAttempt<D.recoveryAttempts&&d()},[L.hasError,D.autoRecovery,D.recoveryAttempts,L.recoveryAttempt,d]),e.useEffect(()=>(F(),()=>{g.current&&g.current.abort()}),[]),e.useImperativeHandle(A,()=>({getState:()=>L,restart:z,skip:P,addTask:I,removeTask:E,getTaskResult:R,hideSplash:H,recover:d}),[L,z,P,I,E,R,H,d]);const i={...L,restart:z,skip:P,hideSplash:H};return L.hasError&&L.recoveryAttempt>=D.recoveryAttempts?t.jsx(ie.Provider,{value:i,children:N||t.jsxs("div",{className:"nice-auto-start__error",children:[t.jsx("div",{className:"nice-auto-start__error-icon",children:"⚠"}),t.jsx("h2",{className:"nice-auto-start__error-title",children:"Startup Failed"}),t.jsx("p",{className:"nice-auto-start__error-message",children:L.errorMessage}),t.jsx("button",{className:"nice-auto-start__error-retry",onClick:z,children:"Retry"})]})}):j&&!L.isReady?t.jsx(ie.Provider,{value:i,children:p||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",children:"◈"}),t.jsx("h1",{className:"nice-auto-start__splash-title",children:"Loading..."}),D.showProgress&&t.jsx("div",{className:"nice-auto-start__splash-progress",children:t.jsx("div",{className:"nice-auto-start__splash-progress-bar",style:{width:`${L.progress}%`}})}),D.showTaskNames&&L.currentTask&&t.jsx("div",{className:"nice-auto-start__splash-task",children:L.currentTask}),L.phase==="recovery"&&t.jsxs("div",{className:"nice-auto-start__splash-recovery",children:["Recovery attempt ",L.recoveryAttempt," of ",D.recoveryAttempts]})]})})}):t.jsx(ie.Provider,{value:i,children:S})});ue.displayName="NiceAutoStart";const Ye=ue;Ye.displayName="NiceAutoStartProvider";const Xe=e.createContext(null),Ke={autoDetect:!0,pollInterval:2e3,defaultFeatures:{resizable:!0,scrollbars:!0},allowMultiWindow:!0,syncContent:!1},Qe=()=>typeof window>"u"?!1:"getScreenDetails"in window,Je=()=>`window-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Ze=m=>{const A=[];return m.width!==void 0&&A.push(`width=${m.width}`),m.height!==void 0&&A.push(`height=${m.height}`),m.left!==void 0&&A.push(`left=${m.left}`),m.top!==void 0&&A.push(`top=${m.top}`),m.menubar!==void 0&&A.push(`menubar=${m.menubar?"yes":"no"}`),m.toolbar!==void 0&&A.push(`toolbar=${m.toolbar?"yes":"no"}`),m.location!==void 0&&A.push(`location=${m.location?"yes":"no"}`),m.status!==void 0&&A.push(`status=${m.status?"yes":"no"}`),m.resizable!==void 0&&A.push(`resizable=${m.resizable?"yes":"no"}`),m.scrollbars!==void 0&&A.push(`scrollbars=${m.scrollbars?"yes":"no"}`),A.join(",")},oe=()=>{var A;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 m=window.screen;return{id:"primary",label:"Primary Display",width:m.width,height:m.height,availWidth:m.availWidth,availHeight:m.availHeight,left:m.availLeft||0,top:m.availTop||0,devicePixelRatio:window.devicePixelRatio,isPrimary:!0,orientation:((A=m.orientation)==null?void 0:A.type)||"landscape-primary",colorDepth:m.colorDepth}},fe=e.forwardRef((m,A)=>{const{config:x,onScreensChange:k,onWindowOpen:p,onWindowClose:N,onPermissionChange:O,children:q}=m,o={...Ke,...x},u=e.useRef(new Map),S=e.useRef(null),[D,b]=e.useState([oe()]),[f,g]=e.useState([]),[j,B]=e.useState("unknown"),[L]=e.useState(Qe),M=e.useCallback(async()=>{if(!L){const n=oe();return b([n]),[n]}try{const s=(await window.getScreenDetails()).screens.map((r,c)=>{var l;return{id:`screen-${c}`,label:r.label||`Display ${c+1}`,width:r.width,height:r.height,availWidth:r.availWidth,availHeight:r.availHeight,left:r.left,top:r.top,devicePixelRatio:r.devicePixelRatio,isPrimary:r.isPrimary,isInternal:r.isInternal,orientation:((l=r.orientation)==null?void 0:l.type)||"landscape-primary",colorDepth:r.colorDepth}});return b(s),k==null||k(s),s}catch{const n=oe();return b([n]),[n]}},[L,k]),W=e.useCallback(async()=>{if(!L)return B("denied"),O==null||O("denied"),!1;try{return await M(),B("granted"),O==null||O("granted"),!0}catch(n){return n instanceof DOMException&&n.name==="NotAllowedError"?(B("denied"),O==null||O("denied")):(B("unknown"),O==null||O("unknown")),!1}},[L,M,O]),X=e.useCallback(async(n,s="about:blank",r={})=>{if(!o.allowMultiWindow&&f.length>0)return console.warn("Multi-window mode is disabled"),null;const c=Je(),l={...o.defaultFeatures,...r,width:r.width??n.availWidth,height:r.height??n.availHeight,left:r.left??n.left,top:r.top??n.top},_=Ze(l),y={window:null,screen:n,id:c,state:"opening",isFullscreen:!1,features:l};g(h=>[...h,y]);try{const h=window.open(s,c,_);if(!h)return g(w=>w.map(U=>U.id===c?{...U,state:"error"}:U)),null;u.current.set(c,h);const v={...y,window:h,state:"open"};g(w=>w.map(U=>U.id===c?v:U));const T=setInterval(()=>{h.closed&&(clearInterval(T),u.current.delete(c),g(w=>w.filter(U=>U.id!==c)),N==null||N(v))},500);return l.fullscreen&&h.addEventListener("load",()=>{var w,U;(U=(w=h.document.documentElement).requestFullscreen)==null||U.call(w)}),p==null||p(v),v}catch(h){return console.error("Failed to open window:",h),g(v=>v.map(T=>T.id===c?{...T,state:"error"}:T)),null}},[o.allowMultiWindow,o.defaultFeatures,f.length,p,N]),F=e.useCallback(n=>{const s=u.current.get(n);s&&!s.closed&&s.close(),u.current.delete(n),g(r=>r.filter(c=>c.id!==n))},[]),z=e.useCallback(()=>{for(const[n,s]of u.current)s.closed||s.close(),u.current.delete(n);g([])},[]),P=e.useCallback((n,s)=>{const r=u.current.get(n);r&&!r.closed&&(r.moveTo(s.left,s.top),r.resizeTo(s.availWidth,s.availHeight),g(c=>c.map(l=>l.id===n?{...l,screen:s}:l)))},[]),H=e.useCallback(async n=>{const s=u.current.get(n);if(!s||s.closed)return!1;try{const r=!!s.document.fullscreenElement;return r?await s.document.exitFullscreen():await s.document.documentElement.requestFullscreen(),g(c=>c.map(l=>l.id===n?{...l,isFullscreen:!r}:l)),!0}catch{return!1}},[]),d=e.useCallback((n,s)=>{const r=u.current.get(n);r&&!r.closed&&r.postMessage(s,"*")},[]),I=e.useCallback(n=>{for(const s of u.current.values())s.closed||s.postMessage(n,"*")},[]);e.useEffect(()=>{o.autoDetect&&M()},[o.autoDetect,M]),e.useEffect(()=>(o.autoDetect&&o.pollInterval>0&&(S.current=setInterval(M,o.pollInterval)),()=>{S.current&&clearInterval(S.current)}),[o.autoDetect,o.pollInterval,M]),e.useEffect(()=>{if(!L)return;const n=()=>{M()};return window.addEventListener("screenschange",n),()=>{window.removeEventListener("screenschange",n)}},[L,M]),e.useEffect(()=>()=>{z()},[z]);const E=D.find(n=>n.isPrimary)||null,R=D.filter(n=>!n.isPrimary),i={screens:D,primaryScreen:E,externalScreens:R,windows:f,isApiAvailable:L,permissionState:j};e.useImperativeHandle(A,()=>({getState:()=>i,requestPermission:W,getScreens:M,openWindow:X,closeWindow:F,closeAllWindows:z,moveWindowToScreen:P,toggleFullscreen:H,sendMessage:d,broadcast:I}),[i,W,M,X,F,z,P,H,d,I]);const a={...i,requestPermission:W,openWindow:X,closeWindow:F,moveWindowToScreen:P};return t.jsx(Xe.Provider,{value:a,children:t.jsx("div",{className:"nice-external-display",children:q})})});fe.displayName="NiceExternalDisplay";const et=fe;et.displayName="NiceExternalDisplayProvider";const tt=e.createContext(null),nt={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=e.forwardRef((m,A)=>{const{config:x,children:k,screensaver:p,adminPanel:N,onModeChange:O,onFullscreenChange:q,onAdminAccess:o,onInactivity:u,onActivity:S,onExitRequest:D}=m,b={...nt,...x},f=e.useRef(null),g=e.useRef(null),j=e.useRef({count:0,timer:null}),[B,L]=e.useState({mode:"windowed",isFullscreen:!1,isLocked:!1,isAdminMode:!1,isScreensaverActive:!1,idleTime:0,isPinDialogOpen:!1}),[M,W]=e.useState(""),[X,F]=e.useState(!1),z=e.useCallback(async()=>{const v=f.current;if(v)try{v.requestFullscreen?await v.requestFullscreen():v.webkitRequestFullscreen?await v.webkitRequestFullscreen():v.msRequestFullscreen&&await v.msRequestFullscreen()}catch(T){console.warn("Failed to enter fullscreen:",T)}},[]),P=e.useCallback(async()=>{try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen?await document.webkitExitFullscreen():document.msExitFullscreen&&await document.msExitFullscreen()}catch(v){console.warn("Failed to exit fullscreen:",v)}},[]),H=e.useCallback(async()=>{B.isFullscreen?await P():await z()},[B.isFullscreen,z,P]),d=e.useCallback(()=>{L(v=>({...v,mode:"locked",isLocked:!0,isAdminMode:!1})),O==null||O("locked")},[O]),I=e.useCallback(v=>b.exitPin&&v!==b.exitPin?(F(!0),setTimeout(()=>F(!1),1e3),!1):(L(T=>({...T,mode:T.isFullscreen?"fullscreen":"windowed",isLocked:!1,isPinDialogOpen:!1})),W(""),!0),[b.exitPin]),E=e.useCallback(()=>{L(v=>({...v,isAdminMode:!0})),o==null||o()},[o]),R=e.useCallback(()=>{L(v=>({...v,isAdminMode:!1}))},[]),i=e.useCallback(()=>{j.current.timer&&clearTimeout(j.current.timer),j.current.count++,j.current.count>=b.adminTapCount?(j.current.count=0,E()):j.current.timer=setTimeout(()=>{j.current.count=0},b.adminTapTimeout)},[b.adminTapCount,b.adminTapTimeout,E]),a=e.useCallback(()=>{g.current&&clearTimeout(g.current),B.isScreensaverActive&&(L(v=>({...v,isScreensaverActive:!1})),S==null||S()),b.inactivityTimeout>0&&(g.current=setTimeout(()=>{L(v=>({...v,isScreensaverActive:!0})),u==null||u()},b.inactivityTimeout))},[b.inactivityTimeout,B.isScreensaverActive,S,u]),n=e.useCallback(()=>{L(v=>({...v,isScreensaverActive:!0}))},[]),s=e.useCallback(()=>{L(v=>({...v,isScreensaverActive:!1})),a()},[a]),r=e.useCallback(()=>{L(v=>({...v,isPinDialogOpen:!0})),W(""),F(!1)},[]),c=e.useCallback(()=>{L(v=>({...v,isPinDialogOpen:!1})),W(""),F(!1)},[]),l=e.useCallback(()=>{I(M)},[M,I]),_=e.useCallback(v=>{v.key==="Enter"&&l()},[l]);e.useEffect(()=>{const v=()=>{const T=!!document.fullscreenElement;L(w=>({...w,mode:w.isLocked?"locked":T?"fullscreen":"windowed",isFullscreen:T})),q==null||q(T)};return document.addEventListener("fullscreenchange",v),document.addEventListener("webkitfullscreenchange",v),()=>{document.removeEventListener("fullscreenchange",v),document.removeEventListener("webkitfullscreenchange",v)}},[q]),e.useEffect(()=>{if(!b.disableContextMenu)return;const v=T=>{B.isAdminMode||T.preventDefault()};return document.addEventListener("contextmenu",v),()=>document.removeEventListener("contextmenu",v)},[b.disableContextMenu,B.isAdminMode]),e.useEffect(()=>{const v=async T=>{const U=b.exitShortcut.toLowerCase().split("+"),$=U.includes("ctrl")===T.ctrlKey,G=U.includes("shift")===T.shiftKey,V=U.includes("alt")===T.altKey,Y=U.some(C=>C===T.key.toLowerCase());if($&&G&&V&&Y){T.preventDefault(),(D?await D("keyboard"):!0)&&(B.isLocked?r():P());return}if(b.disableShortcuts&&!B.isAdminMode){const C=["F5","F11","F12"],Q=[{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(C.includes(T.key)){T.preventDefault();return}for(const K of Q)if(K.ctrl===T.ctrlKey&&(K.shift??!1)===T.shiftKey&&(K.alt??!1)===T.altKey&&K.key.toLowerCase()===T.key.toLowerCase()){T.preventDefault();return}}};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[b.disableShortcuts,b.exitShortcut,B.isAdminMode,B.isLocked,P,r,D]),e.useEffect(()=>{if(!b.disableCopyPaste)return;const v=w=>{B.isAdminMode||w.preventDefault()},T=w=>{B.isAdminMode||w.preventDefault()};return document.addEventListener("copy",v),document.addEventListener("paste",T),()=>{document.removeEventListener("copy",v),document.removeEventListener("paste",T)}},[b.disableCopyPaste,B.isAdminMode]),e.useEffect(()=>{const v=["mousedown","mousemove","keydown","touchstart","scroll"],T=()=>{a()};for(const w of v)document.addEventListener(w,T);return a(),()=>{for(const w of v)document.removeEventListener(w,T);g.current&&clearTimeout(g.current)}},[a]),e.useEffect(()=>{if(b.autoFullscreen){const v=setTimeout(()=>{z()},100);return()=>clearTimeout(v)}},[b.autoFullscreen,z]),e.useImperativeHandle(A,()=>({getState:()=>B,enterFullscreen:z,exitFullscreen:P,toggleFullscreen:H,lock:d,unlock:I,enterAdminMode:E,exitAdminMode:R,resetIdleTimer:a,showScreensaver:n,hideScreensaver:s,openPinDialog:r,closePinDialog:c}),[B,z,P,H,d,I,E,R,a,n,s,r,c]);const y={...B,enterFullscreen:z,exitFullscreen:P,toggleFullscreen:H,lock:d,unlock:I,enterAdminMode:E,exitAdminMode:R,resetIdleTimer:a},h=["nice-kiosk-mode",`nice-kiosk-mode--${B.mode}`,B.isFullscreen&&"nice-kiosk-mode--fullscreen",!b.showCursor&&"nice-kiosk-mode--no-cursor",b.disableSelection&&"nice-kiosk-mode--no-select",!b.allowScrolling&&"nice-kiosk-mode--no-scroll",b.className].filter(Boolean).join(" ");return t.jsx(tt.Provider,{value:y,children:t.jsxs("div",{ref:f,className:h,onClick:i,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:R,"aria-label":"Close admin panel",children:"✕"})]}),t.jsx("div",{className:"nice-kiosk-mode__admin-content",children:N})]}),B.isScreensaverActive&&t.jsx("div",{className:"nice-kiosk-mode__screensaver",onClick:s,onTouchStart:s,children:p||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 ${X?"nice-kiosk-mode__pin-input--error":""}`,value:M,onChange:v=>W(v.target.value),onKeyPress:_,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:c,children:"Cancel"}),t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--submit",onClick:l,children:"Unlock"})]}),X&&t.jsx("div",{className:"nice-kiosk-mode__pin-error",children:"Incorrect PIN"})]})}),B.isLocked&&!B.isPinDialogOpen&&t.jsxs("div",{className:"nice-kiosk-mode__lock-indicator",children:[t.jsx("span",{className:"nice-kiosk-mode__lock-icon",children:"🔒"}),t.jsx("span",{className:"nice-kiosk-mode__lock-text",children:"Kiosk Locked"})]})]})})});me.displayName="NiceKioskMode";const st=me;st.displayName="NiceKioskModeProvider";const rt=e.createContext(null),at={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}},ct={initialMode:"normal",autoDimTimeout:120*1e3,autoSleepTimeout:600*1e3,lowBatteryThreshold:20,criticalBatteryThreshold:5,wakeOnTouch:!0,wakeOnMotion:!1,transitionDuration:500},he=e.forwardRef((m,A)=>{const{config:x,onModeChange:k,onBrightnessChange:p,onSleep:N,onWake:O,onLowBattery:q,children:o}=m,u={...ct,...x},S={...at,...x==null?void 0:x.modes},D=e.useRef(null),b=e.useRef(null),f=e.useRef(Date.now()),g=e.useRef(null),[j,B]=e.useState({currentMode:u.initialMode,brightness:S[u.initialMode].brightness??1,isPowerSaving:u.initialMode!=="normal",isSleeping:u.initialMode==="sleep",idleTime:0,isDisplayOn:!0}),L=e.useCallback(R=>{const i=S[R];document.documentElement.style.setProperty("--lpm-brightness",String(i.brightness)),document.documentElement.style.setProperty("--lpm-transition",`${u.transitionDuration}ms`),i.disableAnimations?document.documentElement.classList.add("lpm-no-animations"):document.documentElement.classList.remove("lpm-no-animations"),i.reduceImageQuality?document.documentElement.classList.add("lpm-reduced-quality"):document.documentElement.classList.remove("lpm-reduced-quality")},[S,u.transitionDuration]),M=e.useCallback(R=>{B(i=>{if(i.currentMode===R)return i;const a=i.currentMode,n=S[R];return L(R),k==null||k(R,a),p==null||p(n.brightness??1),R==="sleep"&&a!=="sleep"?N==null||N():a==="sleep"&&R!=="sleep"&&(O==null||O()),{...i,currentMode:R,brightness:n.brightness??1,isPowerSaving:R!=="normal",isSleeping:R==="sleep",isDisplayOn:R!=="sleep"}})},[S,L,k,p,N,O]),W=e.useCallback(R=>{const i=Math.max(0,Math.min(1,R));document.documentElement.style.setProperty("--lpm-brightness",String(i)),B(a=>({...a,brightness:i})),p==null||p(i)},[p]),X=e.useCallback(()=>{M("sleep")},[M]),F=e.useCallback(()=>{M("normal"),P()},[M]),z=e.useCallback(()=>{j.currentMode==="normal"?M("low"):M("normal")},[j.currentMode,M]),P=e.useCallback(()=>{if(f.current=Date.now(),D.current&&clearTimeout(D.current),b.current&&clearTimeout(b.current),j.isSleeping){F();return}j.currentMode!=="normal"&&j.currentMode!=="sleep"&&M("normal"),u.autoDimTimeout>0&&(D.current=setTimeout(()=>{j.currentMode==="normal"&&M("dim")},u.autoDimTimeout)),u.autoSleepTimeout>0&&(b.current=setTimeout(()=>{M("sleep")},u.autoSleepTimeout)),B(R=>({...R,idleTime:0}))},[j.isSleeping,j.currentMode,u.autoDimTimeout,u.autoSleepTimeout,M,F]),H=e.useCallback(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const R=await navigator.getBattery();return{level:Math.round(R.level*100),charging:R.charging}}catch{return{}}return{}},[]),d=e.useCallback(async()=>{const R=await H();R.level!==void 0&&(B(i=>({...i,batteryLevel:R.level,isCharging:R.charging})),R.charging||(R.level<=u.criticalBatteryThreshold?(M("sleep"),q==null||q(R.level)):R.level<=u.lowBatteryThreshold&&(j.currentMode==="normal"&&M("low"),q==null||q(R.level))))},[H,u.lowBatteryThreshold,u.criticalBatteryThreshold,j.currentMode,M,q]),I=e.useCallback(()=>{if(!(x!=null&&x.schedule)||x.schedule.length===0)return;const i=new Date().getHours();for(const a of x.schedule){const{startHour:n,endHour:s,mode:r}=a;let c;if(n<=s?c=i>=n&&i<s:c=i>=n||i<s,c){B(l=>({...l,scheduledModeActive:r})),j.currentMode!==r&&M(r);return}}B(a=>({...a,scheduledModeActive:void 0}))},[x==null?void 0:x.schedule,j.currentMode,M]);e.useEffect(()=>{const R=["mousedown","mousemove","keydown","touchstart","scroll"],i=()=>{u.wakeOnTouch&&P()};for(const a of R)document.addEventListener(a,i);return P(),()=>{for(const a of R)document.removeEventListener(a,i);D.current&&clearTimeout(D.current),b.current&&clearTimeout(b.current)}},[u.wakeOnTouch,P]),e.useEffect(()=>{d(),(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const i=await navigator.getBattery();g.current=i,i.addEventListener("levelchange",d),i.addEventListener("chargingchange",d)}catch{}})()},[d]),e.useEffect(()=>{I();const R=setInterval(I,6e4);return()=>clearInterval(R)},[I]),e.useEffect(()=>{L(u.initialMode)},[u.initialMode,L]),e.useImperativeHandle(A,()=>({getState:()=>j,setMode:M,setBrightness:W,sleep:X,wake:F,togglePowerSaving:z,resetIdleTimer:P,getBatteryInfo:H}),[j,M,W,X,F,z,P,H]);const E={...j,setMode:M,setBrightness:W,sleep:X,wake:F,resetIdleTimer:P};return t.jsx(rt.Provider,{value:E,children:t.jsxs("div",{className:`nice-lpm nice-lpm--${j.currentMode}`,children:[t.jsx("div",{className:"nice-lpm__overlay",style:{opacity:1-j.brightness}}),t.jsx("div",{className:"nice-lpm__content",children:o}),j.isSleeping&&t.jsx("div",{className:"nice-lpm__sleep-screen",onClick:u.wakeOnTouch?F:void 0,onTouchStart:u.wakeOnTouch?F:void 0,children:t.jsx("div",{className:"nice-lpm__sleep-message",children:"Touch to wake"})})]})})});he.displayName="NiceLowPowerMode";const it=he;it.displayName="NiceLowPowerModeProvider";const ot=e.createContext(null),lt={preferredOrientation:"any",allowUserChange:!0,showRotationPrompt:!0,lockOnMount:!1,autoRotateContent:!1,supportedOrientations:["any","portrait","portrait-primary","portrait-secondary","landscape","landscape-primary","landscape-secondary","natural"]},Le=()=>{if(typeof window>"u")return"portrait";const m=window.screen;return m.orientation?m.orientation.type:window.innerHeight>window.innerWidth?"portrait":"landscape"},dt=()=>{if(typeof window>"u")return 0;const m=window.screen;return m.orientation?m.orientation.angle:window.orientation||0},le=()=>{if(typeof window>"u")return{type:"portrait",angle:0,isPortrait:!0,isLandscape:!1,width:0,height:0,aspectRatio:0};const m=Le(),A=dt(),x=window.screen.width,k=window.screen.height,p=m.includes("portrait")||window.innerHeight>window.innerWidth,N=m.includes("landscape")||window.innerWidth>window.innerHeight;return{type:m,angle:A,isPortrait:p,isLandscape:N,width:x,height:k,aspectRatio:x/k}},ut=()=>{if(typeof window>"u")return!1;const m=window.screen;return!!(m.orientation&&typeof m.orientation.lock=="function")},ge=e.forwardRef((m,A)=>{const{config:x,onOrientationChange:k,onLockChange:p,onUnsupportedOrientation:N,rotationPrompt:O,children:q,className:o}=m,u={...lt,...x},S=e.useRef(!1),[D,b]=e.useState(Le),[f,g]=e.useState(null),[j,B]=e.useState(le),[L]=e.useState(ut),M=e.useCallback(i=>!!(u.supportedOrientations.includes("any")||u.supportedOrientations.includes(i)||i.includes("portrait")&&u.supportedOrientations.includes("portrait")||i.includes("landscape")&&u.supportedOrientations.includes("landscape")),[u.supportedOrientations]),W=e.useCallback(async i=>{if(!L)return console.warn("Screen Orientation API is not available"),g(i),p==null||p(!0,i),!1;try{return await window.screen.orientation.lock(i),g(i),p==null||p(!0,i),!0}catch(a){return console.warn("Failed to lock orientation:",a),g(i),p==null||p(!0,i),!1}},[L,p]),X=e.useCallback(async()=>{if(g(null),p==null||p(!1,null),!L)return!1;try{return window.screen.orientation.unlock(),!0}catch(i){return console.warn("Failed to unlock orientation:",i),!1}},[L,p]),F=e.useCallback(async()=>f?X():W(D),[f,D,W,X]),z=e.useCallback(()=>le(),[]),P=e.useCallback(()=>{const i=le(),a=i.type;b(a),B(i),k==null||k(i),M(a)||N==null||N(a,u.supportedOrientations)},[u.supportedOrientations,M,k,N]);e.useEffect(()=>{S.current||(S.current=!0,P(),u.lockOnMount&&u.preferredOrientation!=="any"&&W(u.preferredOrientation))},[u.lockOnMount,u.preferredOrientation,P,W]),e.useEffect(()=>{const i=window.screen.orientation;return i&&i.addEventListener("change",P),window.addEventListener("resize",P),window.addEventListener("orientationchange",P),()=>{i&&i.removeEventListener("change",P),window.removeEventListener("resize",P),window.removeEventListener("orientationchange",P)}},[P]);const H={current:D,locked:f,isLocked:f!==null,isSupported:M(D),info:j,isApiAvailable:L};e.useImperativeHandle(A,()=>({getState:()=>H,lock:W,unlock:X,toggleLock:F,getOrientationInfo:z,isOrientationSupported:M}),[H,W,X,F,z,M]);const d={...H,lock:W,unlock:X,getOrientationInfo:z},I=e.useCallback(()=>{if(!u.autoRotateContent||!f||f==="any")return;const i=f.includes("portrait"),a=j.isPortrait;return i===a?void 0:{transform:`rotate(${i?90:-90}deg)`,transformOrigin:"center center",width:i?j.height:j.width,height:i?j.width:j.height}},[u.autoRotateContent,f,j]),E=u.showRotationPrompt&&f!==null&&f!=="any"&&!H.isSupported,R=["nice-orientation",`nice-orientation--${D}`,f&&`nice-orientation--locked-${f}`,!H.isSupported&&"nice-orientation--unsupported",o].filter(Boolean).join(" ");return t.jsx(ot.Provider,{value:d,children:t.jsxs("div",{className:R,style:I(),"data-orientation":D,"data-locked":f||void 0,children:[q,E&&t.jsx("div",{className:"nice-orientation__prompt",children:O||t.jsxs("div",{className:"nice-orientation__prompt-content",children:[t.jsx("div",{className:"nice-orientation__prompt-icon",children:t.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",ry:"2"}),t.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"18"}),t.jsx("path",{d:"M21 12h-3m3 0l-2-2m2 2l-2 2"})]})}),t.jsxs("p",{className:"nice-orientation__prompt-text",children:["Please rotate your device to"," ",f!=null&&f.includes("portrait")?"portrait":"landscape"," mode"]})]})})]})})});ge.displayName="NiceOrientationLock";const ft=ge;ft.displayName="NiceOrientationLockProvider";const mt=e.createContext(null),ht={heartbeatInterval:3e4,reconnectDelay:5e3,maxReconnectAttempts:10,enableHealthMonitoring:!0,healthReportInterval:6e4,enableScreenshot:!0,enableLogs:!0,logBufferSize:100},pe=e.forwardRef((m,A)=>{const{config:x,onConnectionChange:k,onCommandReceived:p,onCustomCommand:N,children:O}=m,q={...ht,...x},o=e.useRef(null),u=e.useRef(null),S=e.useRef(null),D=e.useRef([]),b=e.useRef(Date.now()),[f,g]=e.useState({status:"disconnected",isConnected:!1,reconnectAttempts:0,pendingCommands:[],commandHistory:[]}),j=e.useCallback(()=>{const d=typeof navigator<"u"?navigator:null,I=typeof window<"u"?window:null;return{deviceId:q.deviceId,name:q.deviceName||q.deviceId,type:"embedded-display",os:d==null?void 0:d.platform,browser:d==null?void 0:d.userAgent,resolution:I?`${I.screen.width}x${I.screen.height}`:void 0,uptime:Math.floor((Date.now()-b.current)/1e3),metadata:{}}},[q.deviceId,q.deviceName]),B=e.useCallback(async()=>{const d={isOnline:typeof navigator<"u"?navigator.onLine:!0,lastUpdated:new Date};if(typeof performance<"u"&&"memory"in performance){const I=performance.memory;I&&(d.memory=Math.round(I.usedJSHeapSize/I.jsHeapSizeLimit*100))}if(typeof navigator<"u"&&"getBattery"in navigator)try{const I=await navigator.getBattery();d.battery=Math.round(I.level*100)}catch{}if(typeof navigator<"u"&&"storage"in navigator&&"estimate"in navigator.storage)try{const I=await navigator.storage.estimate();I.quota&&I.usage&&(d.storageFree=I.quota-I.usage)}catch{}return d},[]),L=e.useCallback(async()=>{var d;if(((d=o.current)==null?void 0:d.readyState)!==WebSocket.OPEN){g(I=>({...I,status:"connecting"})),k==null||k("connecting");try{const I=new URL(q.serverUrl);I.searchParams.set("deviceId",q.deviceId),q.apiKey&&I.searchParams.set("apiKey",q.apiKey);const E=new WebSocket(I.toString());o.current=E,E.onopen=()=>{g(R=>({...R,status:"connected",isConnected:!0,reconnectAttempts:0,error:void 0})),k==null||k("connected"),E.send(JSON.stringify({type:"register",payload:j()}))},E.onmessage=async R=>{try{const i=JSON.parse(R.data);if(i.type==="command"){const a={id:i.id,type:i.commandType,payload:i.payload,timestamp:new Date,acknowledged:!0,executed:!1};g(r=>({...r,pendingCommands:[...r.pendingCommands,a]})),p==null||p(a);let n,s;try{switch(a.type){case"restart":typeof window<"u"&&window.location.reload();break;case"screenshot":n=await P();break;case"logs":n=D.current;break;case"custom":N&&(n=await N(a));break}a.executed=!0,a.result=n}catch(r){s=r instanceof Error?r.message:String(r),a.error=s}E.send(JSON.stringify({type:"commandResult",commandId:a.id,result:n,error:s})),g(r=>({...r,pendingCommands:r.pendingCommands.filter(c=>c.id!==a.id),commandHistory:[...r.commandHistory.slice(-49),a]}))}}catch{}},E.onerror=()=>{g(R=>({...R,status:"error",error:"WebSocket error"}))},E.onclose=()=>{o.current=null,g(R=>{const i={...R,status:"disconnected",isConnected:!1};return R.reconnectAttempts<q.maxReconnectAttempts&&setTimeout(()=>{g(a=>({...a,reconnectAttempts:a.reconnectAttempts+1})),L()},q.reconnectDelay),i}),k==null||k("disconnected")}}catch(I){g(E=>({...E,status:"error",error:I instanceof Error?I.message:"Connection failed"})),k==null||k("error")}}},[q.serverUrl,q.deviceId,q.apiKey,q.maxReconnectAttempts,q.reconnectDelay,j,k,p,N]),M=e.useCallback(()=>{o.current&&(o.current.close(),o.current=null),g(d=>({...d,status:"disconnected",isConnected:!1,reconnectAttempts:q.maxReconnectAttempts}))},[q.maxReconnectAttempts]),W=e.useCallback(async()=>{var d;((d=o.current)==null?void 0:d.readyState)===WebSocket.OPEN&&(o.current.send(JSON.stringify({type:"heartbeat",timestamp:new Date().toISOString(),deviceId:q.deviceId})),g(I=>({...I,lastHeartbeat:new Date})))},[q.deviceId]),X=e.useCallback(async d=>{var E;if(((E=o.current)==null?void 0:E.readyState)!==WebSocket.OPEN)return;const I=d||await B();o.current.send(JSON.stringify({type:"health",metrics:I,deviceId:q.deviceId})),g(R=>({...R,healthMetrics:I}))},[q.deviceId,B]),F=e.useCallback(async(d,I,E)=>{var R;((R=o.current)==null?void 0:R.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"commandResult",commandId:d,result:I,error:E}))},[]),z=e.useCallback((d,I,E)=>{var i;const R={level:d,message:I,data:E,timestamp:new Date};D.current=[...D.current.slice(-(q.logBufferSize-1)),R],q.enableLogs&&((i=o.current)==null?void 0:i.readyState)===WebSocket.OPEN&&o.current.send(JSON.stringify({type:"log",...R,deviceId:q.deviceId}))},[q.deviceId,q.enableLogs,q.logBufferSize]),P=e.useCallback(async()=>{if(q.enableScreenshot)try{return"screenshot-not-implemented"}catch{return}},[q.enableScreenshot]);e.useEffect(()=>(L(),()=>{M(),u.current&&clearInterval(u.current),S.current&&clearInterval(S.current)}),[]),e.useEffect(()=>{if(f.isConnected)return u.current=setInterval(W,q.heartbeatInterval),()=>{u.current&&clearInterval(u.current)}},[f.isConnected,q.heartbeatInterval,W]),e.useEffect(()=>{if(!(!f.isConnected||!q.enableHealthMonitoring))return S.current=setInterval(()=>{X()},q.healthReportInterval),X(),()=>{S.current&&clearInterval(S.current)}},[f.isConnected,q.enableHealthMonitoring,q.healthReportInterval,X]),e.useImperativeHandle(A,()=>({getState:()=>f,connect:L,disconnect:M,sendHeartbeat:W,sendHealthMetrics:X,reportCommandResult:F,sendLog:z,captureScreenshot:P,getDeviceInfo:j}),[f,L,M,W,X,F,z,P,j]);const H={...f,deviceInfo:j(),connect:L,disconnect:M,sendLog:z};return t.jsx(mt.Provider,{value:H,children:O})});pe.displayName="NiceRemoteManagement";const gt=pe;gt.displayName="NiceRemoteManagementProvider";const pt={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},Re=e.forwardRef((m,A)=>{var l,_,y,h,v,T;const{config:x,enabled:k=!0,onActivate:p,onDeactivate:N,onModeChange:O,children:q}=m,o={...pt,...x},u=e.useRef(null),S=e.useRef(null),D=e.useRef(null),b=e.useRef(null),[f,g]=e.useState({isActive:!1,activeModes:[],shiftX:0,shiftY:0,isDimmed:!1,isScreensaverActive:!1,idleTime:0}),[j,B]=e.useState(0),[L,M]=e.useState({x:50,y:50,dx:1,dy:1}),W=e.useCallback(()=>{if(!o.pixelShift)return;const{maxShift:w}=o.pixelShift,U=Math.floor(Math.random()*(w*2+1))-w,$=Math.floor(Math.random()*(w*2+1))-w;g(G=>({...G,shiftX:U,shiftY:$}))},[o.pixelShift]),X=e.useCallback(()=>{!o.pixelShift||D.current||(W(),D.current=setInterval(W,o.pixelShift.interval))},[o.pixelShift,W]),F=e.useCallback(()=>{D.current&&(clearInterval(D.current),D.current=null),g(w=>({...w,shiftX:0,shiftY:0}))},[]),z=e.useCallback(()=>{!o.colorCycle||b.current||(b.current=setInterval(()=>{B(w=>{var U;return(w+1)%(((U=o.colorCycle)==null?void 0:U.colors.length)||1)})},o.colorCycle.interval))},[o.colorCycle]),P=e.useCallback(()=>{b.current&&(clearInterval(b.current),b.current=null),B(0)},[]),H=e.useCallback(()=>{if(!k||f.isActive)return;const w=o.modes;g(U=>({...U,isActive:!0,activeModes:w})),w.includes("pixel-shift")&&X(),w.includes("color-cycling")&&z(),w.includes("dimming")&&g(U=>({...U,isDimmed:!0})),w.includes("screensaver")&&g(U=>({...U,isScreensaverActive:!0})),p==null||p(),O==null||O(w)},[k,f.isActive,o.modes,X,z,p,O]),d=e.useCallback(()=>{f.isActive&&(F(),P(),g(w=>({...w,isActive:!1,activeModes:[],isDimmed:!1,isScreensaverActive:!1})),N==null||N(),O==null||O([]))},[f.isActive,F,P,N,O]),I=e.useCallback(()=>{f.isActive?d():H()},[f.isActive,H,d]),E=e.useCallback(()=>{S.current&&clearTimeout(S.current),f.isActive&&d(),k&&o.inactivityTimeout>0&&(S.current=setTimeout(()=>{H()},o.inactivityTimeout))},[k,f.isActive,o.inactivityTimeout,H,d]),R=e.useCallback(()=>{g(w=>({...w,isScreensaverActive:!0}))},[]),i=e.useCallback(()=>{g(w=>({...w,isScreensaverActive:!1})),E()},[E]),a=e.useCallback(w=>{g(U=>({...U,isDimmed:w>0}))},[]);e.useEffect(()=>{var U;if(!f.isScreensaverActive||((U=o.screensaver)==null?void 0:U.type)!=="bounce")return;const w=setInterval(()=>{M($=>{let{x:G,y:V,dx:Y,dy:C}=$;return G+=Y*.5,V+=C*.5,(G<=0||G>=90)&&(Y=-Y),(V<=0||V>=90)&&(C=-C),{x:G,y:V,dx:Y,dy:C}})},50);return()=>clearInterval(w)},[f.isScreensaverActive,(l=o.screensaver)==null?void 0:l.type]),e.useEffect(()=>{if(!k)return;const w=["mousedown","mousemove","keydown","touchstart","scroll","wheel"],U=()=>{E()};for(const $ of w)document.addEventListener($,U);return E(),()=>{for(const $ of w)document.removeEventListener($,U);S.current&&clearTimeout(S.current),F(),P()}},[k,E,F,P]),e.useImperativeHandle(A,()=>({getState:()=>f,activate:H,deactivate:d,toggle:I,resetIdleTimer:E,forceShift:W,showScreensaver:R,hideScreensaver:i,setDimLevel:a}),[f,H,d,I,E,W,R,i,a]);const n=()=>{if(!f.isScreensaverActive)return null;const w=o.screensaver||{type:"blank"};switch(w.type){case"blank":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--blank",onClick:i,onTouchStart:i});case"bounce":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--bounce",onClick:i,onTouchStart:i,children:t.jsx("div",{className:"nice-sbp__bounce-logo",style:{left:`${L.x}%`,top:`${L.y}%`},children:"⬡"})});case"matrix":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--matrix",onClick:i,onTouchStart:i,children:Array.from({length:20}).map((U,$)=>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((G,V)=>t.jsx("span",{children:String.fromCharCode(12448+Math.random()*96)},V))},$))});case"noise":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--noise",onClick:i,onTouchStart:i});case"custom":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--custom",onClick:i,onTouchStart:i,children:w.component});default:return null}},s={transform:f.isActive&&o.modes.includes("pixel-shift")?`translate(${f.shiftX}px, ${f.shiftY}px)`:void 0,transition:(_=o.pixelShift)!=null&&_.smooth?"transform 0.5s ease":void 0},r={"--dim-level":f.isDimmed?((y=o.dimming)==null?void 0:y.level)||.3:0,"--dim-duration":`${((h=o.dimming)==null?void 0:h.fadeDuration)||2e3}ms`},c=f.isActive&&o.modes.includes("color-cycling")?{backgroundColor:(v=o.colorCycle)==null?void 0:v.colors[j],transition:`background-color ${((T=o.colorCycle)==null?void 0:T.transitionDuration)||1e3}ms ease`}:{};return t.jsxs("div",{ref:u,className:`nice-sbp ${f.isActive?"nice-sbp--active":""}`,style:{...c},children:[t.jsx("div",{className:"nice-sbp__content",style:s,children:q}),f.isDimmed&&t.jsx("div",{className:"nice-sbp__dim-overlay",style:r,onClick:E,onTouchStart:E}),n(),f.isActive&&o.modes.includes("invert")&&t.jsx("div",{className:"nice-sbp__invert-overlay"})]})});Re.displayName="NiceScreenBurnPrevention";const yt={pointCount:5,targetSize:40,accuracyThreshold:20,pointTimeout:1e4,showAccuracy:!0,allowRetry:!0,persistCalibration:!0,storageKey:"nice-touch-calibration"},bt=m=>({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}]})[m],Pe=e.forwardRef((m,A)=>{const{config:x,autoStart:k=!1,onStart:p,onPointCalibrated:N,onComplete:O,onCancel:q,children:o}=m,u={...yt,...x},S=e.useRef(null),D=e.useRef(null),[b,f]=e.useState({isActive:!1,currentPointIndex:0,totalPoints:u.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),g=e.useCallback(d=>{const I=d.filter(G=>G.calibrated&&G.actualX!==void 0&&G.actualY!==void 0);if(I.length<3)return{scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};let E=0,R=0,i=0,a=0;const n=I.length;for(const G of I)E+=G.targetX,R+=G.targetY,i+=G.actualX,a+=G.actualY;const s=E/n,r=R/n,c=i/n,l=a/n;let _=0,y=0,h=0,v=0;for(const G of I){const V=G.targetX-s,Y=G.targetY-r,C=G.actualX-c,Q=G.actualY-l;_+=V*V,y+=V*C,h+=Y*Y,v+=Y*Q}const T=y!==0?_/y:1,w=v!==0?h/v:1,U=s-T*c,$=r-w*l;return{scaleX:T,scaleY:w,offsetX:U,offsetY:$,rotation:0}},[]),j=e.useCallback((d,I)=>{const E=d.filter(i=>i.calibrated);if(E.length===0)return 0;let R=0;for(const i of E){if(i.actualX===void 0||i.actualY===void 0)continue;const a=I.scaleX*i.actualX+I.offsetX,n=I.scaleY*i.actualY+I.offsetY,s=i.targetX-a,r=i.targetY-n;R+=Math.sqrt(s*s+r*r)}return R/E.length},[]),B=e.useCallback(()=>{const I=bt(u.pointCount).map(E=>({...E,calibrated:!1}));f({isActive:!0,currentPointIndex:0,totalPoints:u.pointCount,points:I,isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),p==null||p()},[u.pointCount,p]),L=e.useCallback(()=>{D.current&&clearTimeout(D.current),f(d=>({...d,isActive:!1,isCompleted:!1})),q==null||q()},[q]),M=e.useCallback(()=>{if(u.persistCalibration)try{localStorage.removeItem(u.storageKey)}catch{}f({isActive:!1,currentPointIndex:0,totalPoints:u.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0})},[u.persistCalibration,u.storageKey,u.pointCount]),W=e.useCallback(d=>{const I=g(d),E=j(d,I),R=E<=u.accuracyThreshold;if(u.persistCalibration&&R)try{localStorage.setItem(u.storageKey,JSON.stringify({matrix:I,points:d}))}catch{}f(i=>({...i,isActive:!1,isCompleted:!0,isSuccessful:R,matrix:I,averageError:E})),O==null||O(I,R)},[u.accuracyThreshold,u.persistCalibration,u.storageKey,g,j,O]),X=e.useCallback(d=>{if(!b.isActive||!S.current)return;d.preventDefault();const I=S.current.getBoundingClientRect();let E,R;"touches"in d?(E=d.touches[0].clientX,R=d.touches[0].clientY):(E=d.clientX,R=d.clientY);const i=(E-I.left)/I.width*100,a=(R-I.top)/I.height*100,n=b.currentPointIndex,s=[...b.points];s[n]={...s[n],actualX:i,actualY:a,calibrated:!0};const r=n+1;r>=b.totalPoints?W(s):f(c=>({...c,currentPointIndex:r,points:s})),N==null||N(s[n],n)},[b.isActive,b.currentPointIndex,b.points,b.totalPoints,W,N]),F=e.useCallback((d,I)=>{const E=b.matrix;return E?{x:E.scaleX*d+E.offsetX,y:E.scaleY*I+E.offsetY}:{x:d,y:I}},[b.matrix]),z=e.useCallback(()=>{if(b.matrix)return!0;if(u.persistCalibration)try{return!!localStorage.getItem(u.storageKey)}catch{return!1}return!1},[b.matrix,u.persistCalibration,u.storageKey]),P=e.useCallback(()=>{if(u.persistCalibration)try{localStorage.removeItem(u.storageKey)}catch{}f(d=>({...d,matrix:null}))},[u.persistCalibration,u.storageKey]);if(e.useEffect(()=>{if(u.persistCalibration)try{const d=localStorage.getItem(u.storageKey);if(d){const I=JSON.parse(d);f(E=>({...E,matrix:I.matrix,points:I.points||[],isCompleted:!0,isSuccessful:!0}))}}catch{}},[u.persistCalibration,u.storageKey]),e.useEffect(()=>{if(!b.isActive)return;const d=S.current;if(d)return d.addEventListener("touchstart",X,{passive:!1}),d.addEventListener("mousedown",X),()=>{d.removeEventListener("touchstart",X),d.removeEventListener("mousedown",X)}},[b.isActive,X]),e.useEffect(()=>{if(!(!b.isActive||u.pointTimeout<=0))return D.current=setTimeout(()=>{b.currentPointIndex<b.totalPoints-1?f(d=>({...d,currentPointIndex:d.currentPointIndex+1})):W(b.points)},u.pointTimeout),()=>{D.current&&clearTimeout(D.current)}},[b.isActive,b.currentPointIndex,b.points,b.totalPoints,u.pointTimeout,W]),e.useEffect(()=>{k&&!z()&&B()},[k,z,B]),e.useImperativeHandle(A,()=>({getState:()=>b,start:B,cancel:L,reset:M,getMatrix:()=>b.matrix,transformPoint:F,hasCalibration:z,clearCalibration:P}),[b,B,L,M,F,z,P]),!b.isActive)return t.jsx(t.Fragment,{children:o});const H=b.points[b.currentPointIndex];return t.jsxs("div",{ref:S,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 ",b.currentPointIndex+1," of ",b.totalPoints]})]}),H&&t.jsx("div",{className:"nice-touch-calibration__target",style:{left:`${H.targetX}%`,top:`${H.targetY}%`,width:u.targetSize,height:u.targetSize},children:(x==null?void 0:x.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"})]})}),b.points.map((d,I)=>d.calibrated&&t.jsx("div",{className:"nice-touch-calibration__calibrated",style:{left:`${d.actualX}%`,top:`${d.actualY}%`}},I)),t.jsx("button",{className:"nice-touch-calibration__cancel",onClick:L,children:"Cancel"})]}),b.isCompleted&&t.jsxs("div",{className:"nice-touch-calibration__result",children:[t.jsx("div",{className:`nice-touch-calibration__result-icon ${b.isSuccessful?"nice-touch-calibration__result-icon--success":"nice-touch-calibration__result-icon--error"}`,children:b.isSuccessful?"✓":"✗"}),t.jsx("h3",{className:"nice-touch-calibration__result-title",children:b.isSuccessful?"Calibration Complete":"Calibration Failed"}),u.showAccuracy&&t.jsxs("p",{className:"nice-touch-calibration__result-accuracy",children:["Average error: ",b.averageError.toFixed(1),"px"]}),!b.isSuccessful&&u.allowRetry&&t.jsx("button",{className:"nice-touch-calibration__retry",onClick:B,children:"Retry Calibration"})]})]})});Pe.displayName="NiceTouchCalibration";const wt={format:"code128",width:2,height:100,displayValue:!0,font:"monospace",fontSize:14,textAlign:"center",textPosition:"bottom",textMargin:2,background:"var(--nice-bg, #fff)",lineColor:"var(--nice-text, #000000)",margin:10,flat:!1},_e=104,vt=106,xt=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",ce=["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=m=>{let A=ce[_e],x=_e;for(let k=0;k<m.length;k++){const p=m[k],N=xt.indexOf(p);N!==-1&&(A+=ce[N],x+=N*(k+1))}return x=x%103,A+=ce[x],A+=ce[vt],A},Te=["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],Ct=["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"],Oe=["1110010","1100110","1101100","1000010","1011100","1001110","1010000","1000100","1001000","1110100"],kt=["LLLLLL","LLGLGG","LLGGLG","LLGGGL","LGLLGG","LGGLLG","LGGGLL","LGLGLG","LGLGGL","LGGLGL"],St=m=>{let A=0;for(let x=0;x<12;x++)A+=parseInt(m[x])*(x%2===0?1:3);return(10-A%10)%10},_t=m=>{let A=m.replace(/\D/g,"").slice(0,12).padStart(12,"0");const x=St(A);A+=x;const k=parseInt(A[0]),p=kt[k];let N="101";for(let O=1;O<=6;O++){const q=parseInt(A[O]);N+=p[O-1]==="L"?Te[q]:Ct[q]}N+="01010";for(let O=7;O<=12;O++){const q=parseInt(A[O]);N+=Oe[q]}return N+="101",N},Nt=m=>{let A=m.replace(/\D/g,"").slice(0,7).padStart(7,"0"),x=0;for(let N=0;N<7;N++)x+=parseInt(A[N])*(N%2===0?3:1);const k=(10-x%10)%10;A+=k;let p="101";for(let N=0;N<4;N++)p+=Te[parseInt(A[N])];p+="01010";for(let N=4;N<8;N++)p+=Oe[parseInt(A[N])];return p+="101",p},jt={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"},It=m=>{const A=("*"+m.toUpperCase()+"*").split("");let x="";for(const k of A){const p=jt[k];p&&(x+=p+"0")}return x.slice(0,-1)},je=m=>{switch(m){case"code128":return Ne;case"code39":case"code93":return It;case"ean13":return _t;case"ean8":return Nt;default:return Ne}},Me=e.forwardRef((m,A)=>{const{value:x,options:k,onGenerate:p,onError:N,showBorder:O=!1,className:q}=m,o={...wt,...k},u=e.useRef(null),S=e.useRef(null),[D,b]=e.useState(null),[f,g]=e.useState(null),j=e.useCallback(()=>{if(!u.current||!x)return;const z=u.current,P=z.getContext("2d");if(P)try{const d=je(o.format)(x),I=o.width,E=d.length*I,R=o.marginTop??o.margin,i=o.marginBottom??o.margin,a=o.marginLeft??o.margin,n=o.marginRight??o.margin,s=o.displayValue&&!o.flat?o.fontSize+o.textMargin*2:0,r=E+a+n,c=o.height+R+i+s;z.width=r,z.height=c,P.fillStyle=o.background,P.fillRect(0,0,r,c),P.fillStyle=o.lineColor;let l=a;const _=o.textPosition==="top"&&o.displayValue?R+s:R;for(let h=0;h<d.length;h++)d[h]==="1"&&P.fillRect(l,_,I,o.height),l+=I;if(o.displayValue&&!o.flat){P.fillStyle=o.lineColor,P.font=`${o.fontSize}px ${o.font}`,P.textBaseline=o.textPosition==="top"?"top":"bottom";let h=a;o.textAlign==="center"?(h=a+E/2,P.textAlign="center"):o.textAlign==="right"?(h=a+E,P.textAlign="right"):P.textAlign="left";const v=o.textPosition==="top"?R+o.textMargin:c-i-o.textMargin;P.fillText(x,h,v)}const y=z.toDataURL("image/png");g(y),b(null),p==null||p(y)}catch(H){const d=H instanceof Error?H.message:"Failed to generate barcode";b(d),N==null||N(new Error(d))}},[x,o,p,N]);e.useEffect(()=>{j()},[j]);const B=e.useCallback((z="image/png",P=1)=>{var H;return((H=u.current)==null?void 0:H.toDataURL(z,P))||null},[]),L=e.useCallback(()=>{if(!u.current||!x)return null;try{const P=je(o.format)(x),H=o.width,d=o.marginTop??o.margin,I=o.marginBottom??o.margin,E=o.marginLeft??o.margin,R=o.marginRight??o.margin,i=o.displayValue&&!o.flat?o.fontSize+o.textMargin*2:0,a=P.length*H,n=a+E+R,s=o.height+d+I+i,r=[];let c=E;const l=o.textPosition==="top"&&o.displayValue?d+i:d;for(let y=0;y<P.length;y++)P[y]==="1"&&r.push(`<rect x="${c}" y="${l}" width="${H}" height="${o.height}" fill="${o.lineColor}"/>`),c+=H;let _="";if(o.displayValue&&!o.flat){const y=o.textAlign==="center"?"middle":o.textAlign==="right"?"end":"start";let h=E;o.textAlign==="center"?h=E+a/2:o.textAlign==="right"&&(h=E+a);const v=o.textPosition==="top"?d+o.fontSize:s-I-o.textMargin;_=`<text x="${h}" y="${v}" font-family="${o.font}" font-size="${o.fontSize}" text-anchor="${y}" fill="${o.lineColor}">${x}</text>`}return`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${s}" viewBox="0 0 ${n} ${s}">
|
|
2
|
-
<rect width="100%" height="100%" fill="${
|
|
3
|
-
${
|
|
1
|
+
"use strict";var Nt=Object.defineProperty;var It=(n,f,p)=>f in n?Nt(n,f,{enumerable:!0,configurable:!0,writable:!0,value:p}):n[f]=p;var ce=(n,f,p)=>It(n,typeof f!="symbol"?f+"":f,p);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),le=e.createContext(null),jt=()=>{const n=e.useContext(le);if(!n)throw new Error("useAutoStart must be used within NiceAutoStartProvider");return n},At={showSplash:!0,splashDuration:2e3,autoHideSplash:!0,showProgress:!0,showTaskNames:!0,globalTimeout:6e4,autoRecovery:!0,recoveryAttempts:3,recoveryDelay:2e3,checkUpdates:!1,sendAnalytics:!1},he=e.forwardRef((n,f)=>{const{tasks:p=[],config:C,splash:h,errorScreen:N,onComplete:T,onTaskComplete:P,onError:i,onRecovery:d,children:b}=n,L={...At,...C},x=e.useRef(0),u=e.useRef(p),y=e.useRef(null),[A,q]=e.useState(L.showSplash),[U,V]=e.useState({phase:"initializing",isLoading:!0,isReady:!1,hasError:!1,progress:0,completedTasks:0,totalTasks:p.length,results:[],recoveryAttempt:0,totalDuration:0}),z=e.useCallback(async s=>{const a=Date.now();let r=0;const o=async()=>{try{const l=s.timeout||L.globalTimeout,j=new Promise((F,g)=>{setTimeout(()=>g(new Error("Task timeout")),l)});return await Promise.race([s.execute(),j]),{taskId:s.id,success:!0,duration:Date.now()-a,retriesUsed:r}}catch(l){const j=s.retries??0;return r<j?(r++,await new Promise(F=>setTimeout(F,500)),o()):{taskId:s.id,success:!1,error:l instanceof Error?l:new Error(String(l)),duration:Date.now()-a,retriesUsed:r}}};return o()},[L.globalTimeout]),Y=e.useCallback(s=>{const a=[],r=[...s],o=new Set;for(;r.length>0;){const l=r.filter(F=>F.dependencies?F.dependencies.every(g=>o.has(g)):!0);if(l.length===0){a.push(...r);break}l.sort((F,g)=>(g.priority??0)-(F.priority??0));const j=l[0];a.push(j),o.add(j.id),r.splice(r.indexOf(j),1)}return a},[]),B=e.useCallback(async()=>{x.current=Date.now();const s=new AbortController;y.current=s;const a=Y(u.current),r=[];V(l=>({...l,phase:"loading",isLoading:!0,isReady:!1,hasError:!1,errorMessage:void 0,progress:0,completedTasks:0,totalTasks:a.length,results:[]}));for(let l=0;l<a.length;l++){if(s.signal.aborted)return;const j=a[l];V(g=>({...g,currentTask:j.name,progress:Math.round(l/a.length*100)}));const F=await z(j);if(s.signal.aborted)return;if(r.push(F),V(g=>({...g,completedTasks:l+1,results:[...g.results,F]})),P==null||P(F),!F.success&&j.critical){const g=F.error||new Error("Critical task failed");i==null||i(g,j.id),V(m=>({...m,phase:"error",isLoading:!1,hasError:!0,errorMessage:g.message}));return}}const o=Date.now()-x.current;if(V(l=>({...l,phase:"ready",isLoading:!1,isReady:!0,currentTask:void 0,progress:100,totalDuration:o})),T==null||T(r),L.autoHideSplash){const l=Date.now()-x.current,j=Math.max(0,L.splashDuration-l);setTimeout(()=>{q(!1)},j)}},[Y,z,L.autoHideSplash,L.splashDuration,P,i,T]),G=e.useCallback(async()=>{y.current&&y.current.abort(),V(s=>({...s,recoveryAttempt:0})),q(L.showSplash),await B()},[L.showSplash,B]),E=e.useCallback(()=>{y.current&&y.current.abort(),V(s=>({...s,phase:"ready",isLoading:!1,isReady:!0,progress:100})),q(!1)},[]),$=e.useCallback(()=>{q(!1)},[]),R=e.useCallback(async()=>{const s=U.recoveryAttempt+1;s>L.recoveryAttempts||(V(a=>({...a,phase:"recovery",recoveryAttempt:s})),d==null||d(s),await new Promise(a=>setTimeout(a,L.recoveryDelay)),await B())},[U.recoveryAttempt,L.recoveryAttempts,L.recoveryDelay,d,B]),k=e.useCallback(s=>{u.current=[...u.current,s]},[]),S=e.useCallback(s=>{u.current=u.current.filter(a=>a.id!==s)},[]),D=e.useCallback(s=>U.results.find(a=>a.taskId===s),[U.results]);e.useEffect(()=>{U.hasError&&L.autoRecovery&&U.recoveryAttempt<L.recoveryAttempts&&R()},[U.hasError,L.autoRecovery,L.recoveryAttempts,U.recoveryAttempt,R]),e.useEffect(()=>(B(),()=>{y.current&&y.current.abort()}),[]),e.useImperativeHandle(f,()=>({getState:()=>U,restart:G,skip:E,addTask:k,removeTask:S,getTaskResult:D,hideSplash:$,recover:R}),[U,G,E,k,S,D,$,R]);const c={...U,restart:G,skip:E,hideSplash:$};return U.hasError&&U.recoveryAttempt>=L.recoveryAttempts?t.jsx(le.Provider,{value:c,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:U.errorMessage}),t.jsx("button",{className:"nice-auto-start__error-retry",onClick:G,children:"Retry"})]})}):A&&!U.isReady?t.jsx(le.Provider,{value:c,children:h||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..."}),L.showProgress&&t.jsx("div",{className:"nice-auto-start__splash-progress",children:t.jsx("div",{className:"nice-auto-start__splash-progress-bar",style:{width:`${U.progress}%`}})}),L.showTaskNames&&U.currentTask&&t.jsx("div",{className:"nice-auto-start__splash-task",children:U.currentTask}),U.phase==="recovery"&&t.jsxs("div",{className:"nice-auto-start__splash-recovery",children:["Recovery attempt ",U.recoveryAttempt," of ",L.recoveryAttempts]})]})})}):t.jsx(le.Provider,{value:c,children:b})});he.displayName="NiceAutoStart";const Te=he;Te.displayName="NiceAutoStartProvider";const Me=e.createContext(null),Fe=()=>{const n=e.useContext(Me);if(!n)throw new Error("useExternalDisplay must be used within NiceExternalDisplayProvider");return n},Dt={autoDetect:!0,pollInterval:2e3,defaultFeatures:{resizable:!0,scrollbars:!0},allowMultiWindow:!0,syncContent:!1},Et=()=>typeof window>"u"?!1:"getScreenDetails"in window,Lt=()=>`window-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Pt=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(",")},je=()=>{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}},Rt=async()=>{try{return(await navigator.permissions.query({name:"window-management"})).state}catch{return"unknown"}},Ae=async()=>(await window.getScreenDetails()).screens.map((f,p)=>{var C;return{id:`screen-${p}`,label:f.label||`Display ${p+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:((C=f.orientation)==null?void 0:C.type)||"landscape-primary",colorDepth:f.colorDepth}}),De=(n,f)=>JSON.stringify(n)===JSON.stringify(f),ge=e.forwardRef((n,f)=>{const{config:p,onScreensChange:C,onWindowOpen:h,onWindowClose:N,onPermissionChange:T,children:P}=n,i={...Dt,...p},d=e.useRef(new Map),b=e.useRef(null),[L,x]=e.useState([je()]),[u,y]=e.useState([]),[A,q]=e.useState("unknown"),[U]=e.useState(Et),V=e.useRef(C),z=e.useRef(T);e.useEffect(()=>{V.current=C,z.current=T});const Y=e.useRef([]),B=e.useCallback(g=>{var m;x(w=>De(w,g)?w:g),De(Y.current,g)||(Y.current=g,(m=V.current)==null||m.call(V,g))},[]),G=e.useRef("unknown"),E=e.useCallback(g=>{var m;G.current!==g&&(G.current=g,q(g),(m=z.current)==null||m.call(z,g))},[]),$=e.useCallback(async()=>{if(U){const m=await Rt();if(E(m),m==="granted")try{const w=await Ae();return B(w),w}catch{}}const g=[je()];return B(g),g},[U,E,B]),R=e.useCallback(async()=>{if(!U)return E("denied"),!1;try{return B(await Ae()),E("granted"),!0}catch(g){return E(g instanceof DOMException&&g.name==="NotAllowedError"?"denied":"unknown"),!1}},[U,E,B]),k=e.useCallback(async(g,m="about:blank",w={})=>{if(!i.allowMultiWindow&&u.length>0)return console.warn("Multi-window mode is disabled"),null;const O=Lt(),_={...i.defaultFeatures,...w,width:w.width??g.availWidth,height:w.height??g.availHeight,left:w.left??g.left,top:w.top??g.top},W=Pt(_),I={window:null,screen:g,id:O,state:"opening",isFullscreen:!1,features:_};y(H=>[...H,I]);try{const H=window.open(m,O,W);if(!H)return y(v=>v.map(J=>J.id===O?{...J,state:"error"}:J)),null;d.current.set(O,H);const M={...I,window:H,state:"open"};y(v=>v.map(J=>J.id===O?M:J));const X=setInterval(()=>{H.closed&&(clearInterval(X),d.current.delete(O),y(v=>v.filter(J=>J.id!==O)),N==null||N(M))},500);return _.fullscreen&&H.addEventListener("load",()=>{var v,J;(J=(v=H.document.documentElement).requestFullscreen)==null||J.call(v)}),h==null||h(M),M}catch(H){return console.error("Failed to open window:",H),y(M=>M.map(X=>X.id===O?{...X,state:"error"}:X)),null}},[i.allowMultiWindow,i.defaultFeatures,u.length,h,N]),S=e.useCallback(g=>{const m=d.current.get(g);m&&!m.closed&&m.close(),d.current.delete(g),y(w=>w.filter(O=>O.id!==g))},[]),D=e.useCallback(()=>{for(const[g,m]of d.current)m.closed||m.close(),d.current.delete(g);y([])},[]),c=e.useCallback((g,m)=>{const w=d.current.get(g);w&&!w.closed&&(w.moveTo(m.left,m.top),w.resizeTo(m.availWidth,m.availHeight),y(O=>O.map(_=>_.id===g?{..._,screen:m}:_)))},[]),s=e.useCallback(async g=>{const m=d.current.get(g);if(!m||m.closed)return!1;try{const w=!!m.document.fullscreenElement;return w?await m.document.exitFullscreen():await m.document.documentElement.requestFullscreen(),y(O=>O.map(_=>_.id===g?{..._,isFullscreen:!w}:_)),!0}catch{return!1}},[]),a=e.useCallback((g,m)=>{const w=d.current.get(g);w&&!w.closed&&w.postMessage(m,"*")},[]),r=e.useCallback(g=>{for(const m of d.current.values())m.closed||m.postMessage(g,"*")},[]);e.useEffect(()=>{i.autoDetect&&$()},[i.autoDetect,$]),e.useEffect(()=>(i.autoDetect&&i.pollInterval>0&&(b.current=setInterval($,i.pollInterval)),()=>{b.current&&clearInterval(b.current)}),[i.autoDetect,i.pollInterval,$]),e.useEffect(()=>{if(!U)return;const g=()=>{$()};return window.addEventListener("screenschange",g),()=>{window.removeEventListener("screenschange",g)}},[U,$]),e.useEffect(()=>()=>{D()},[D]);const o=L.find(g=>g.isPrimary)||null,l=L.filter(g=>!g.isPrimary),j={screens:L,primaryScreen:o,externalScreens:l,windows:u,isApiAvailable:U,permissionState:A};e.useImperativeHandle(f,()=>({getState:()=>j,requestPermission:R,getScreens:$,openWindow:k,closeWindow:S,closeAllWindows:D,moveWindowToScreen:c,toggleFullscreen:s,sendMessage:a,broadcast:r}),[j,R,$,k,S,D,c,s,a,r]);const F={...j,requestPermission:R,openWindow:k,closeWindow:S,moveWindowToScreen:c};return t.jsx(Me.Provider,{value:F,children:t.jsx("div",{className:"nice-external-display",children:P})})});ge.displayName="NiceExternalDisplay";const Be=ge;Be.displayName="NiceExternalDisplayProvider";const $e=({onSelect:n,selectedId:f,showPreview:p=!0,className:C})=>{const{screens:h,primaryScreen:N}=Fe(),T=b=>{n==null||n(b)},i=(()=>{let b=0,L=0,x=0,u=0;for(const y of h)b=Math.min(b,y.left),L=Math.min(L,y.top),x=Math.max(x,y.left+y.width),u=Math.max(u,y.top+y.height);return{minX:b,minY:L,maxX:x,maxY:u,width:x-b,height:u-L}})(),d=Math.min(280/i.width,160/i.height,1);return t.jsxs("div",{className:`nice-screen-selector ${C||""}`,children:[p&&t.jsx("div",{className:"nice-screen-selector__preview",style:{width:i.width*d,height:i.height*d},children:h.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)*d,top:(b.top-i.minY)*d,width:b.width*d,height:b.height*d},onClick:()=>T(b),title:b.label,children:t.jsx("span",{className:"nice-screen-selector__screen-label",children:b.isPrimary?"P":h.indexOf(b)+1})},b.id))}),t.jsx("div",{className:"nice-screen-selector__list",children:h.map(b=>t.jsxs("button",{className:`nice-screen-selector__item ${f===b.id?"nice-screen-selector__item--selected":""}`,onClick:()=>T(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))})]})};$e.displayName="NiceScreenSelector";const qe=e.createContext(null),Ot=()=>{const n=e.useContext(qe);if(!n)throw new Error("useKioskMode must be used within NiceKioskModeProvider");return n},Tt={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:""},pe=e.forwardRef((n,f)=>{const{config:p,children:C,screensaver:h,adminPanel:N,onModeChange:T,onFullscreenChange:P,onAdminAccess:i,onInactivity:d,onActivity:b,onExitRequest:L}=n,x={...Tt,...p},u=e.useRef(null),y=e.useRef(null),A=e.useRef({count:0,timer:null}),[q,U]=e.useState({mode:"windowed",isFullscreen:!1,isLocked:!1,isAdminMode:!1,isScreensaverActive:!1,idleTime:0,isPinDialogOpen:!1}),[V,z]=e.useState(""),[Y,B]=e.useState(!1),G=e.useCallback(async()=>{const w=u.current;if(w)try{w.requestFullscreen?await w.requestFullscreen():w.webkitRequestFullscreen?await w.webkitRequestFullscreen():w.msRequestFullscreen&&await w.msRequestFullscreen()}catch(O){console.warn("Failed to enter fullscreen:",O)}},[]),E=e.useCallback(async()=>{try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen?await document.webkitExitFullscreen():document.msExitFullscreen&&await document.msExitFullscreen()}catch(w){console.warn("Failed to exit fullscreen:",w)}},[]),$=e.useCallback(async()=>{q.isFullscreen?await E():await G()},[q.isFullscreen,G,E]),R=e.useCallback(()=>{U(w=>({...w,mode:"locked",isLocked:!0,isAdminMode:!1})),T==null||T("locked")},[T]),k=e.useCallback(w=>x.exitPin&&w!==x.exitPin?(B(!0),setTimeout(()=>B(!1),1e3),!1):(U(O=>({...O,mode:O.isFullscreen?"fullscreen":"windowed",isLocked:!1,isPinDialogOpen:!1})),z(""),!0),[x.exitPin]),S=e.useCallback(()=>{U(w=>({...w,isAdminMode:!0})),i==null||i()},[i]),D=e.useCallback(()=>{U(w=>({...w,isAdminMode:!1}))},[]),c=e.useCallback(()=>{A.current.timer&&clearTimeout(A.current.timer),A.current.count++,A.current.count>=x.adminTapCount?(A.current.count=0,S()):A.current.timer=setTimeout(()=>{A.current.count=0},x.adminTapTimeout)},[x.adminTapCount,x.adminTapTimeout,S]),s=e.useCallback(()=>{y.current&&clearTimeout(y.current),q.isScreensaverActive&&(U(w=>({...w,isScreensaverActive:!1})),b==null||b()),x.inactivityTimeout>0&&(y.current=setTimeout(()=>{U(w=>({...w,isScreensaverActive:!0})),d==null||d()},x.inactivityTimeout))},[x.inactivityTimeout,q.isScreensaverActive,b,d]),a=e.useCallback(()=>{U(w=>({...w,isScreensaverActive:!0}))},[]),r=e.useCallback(()=>{U(w=>({...w,isScreensaverActive:!1})),s()},[s]),o=e.useCallback(()=>{U(w=>({...w,isPinDialogOpen:!0})),z(""),B(!1)},[]),l=e.useCallback(()=>{U(w=>({...w,isPinDialogOpen:!1})),z(""),B(!1)},[]),j=e.useCallback(()=>{k(V)},[V,k]),F=e.useCallback(w=>{w.key==="Enter"&&j()},[j]);e.useEffect(()=>{const w=()=>{const O=!!document.fullscreenElement;U(_=>({..._,mode:_.isLocked?"locked":O?"fullscreen":"windowed",isFullscreen:O})),P==null||P(O)};return document.addEventListener("fullscreenchange",w),document.addEventListener("webkitfullscreenchange",w),()=>{document.removeEventListener("fullscreenchange",w),document.removeEventListener("webkitfullscreenchange",w)}},[P]),e.useEffect(()=>{if(!x.disableContextMenu)return;const w=O=>{q.isAdminMode||O.preventDefault()};return document.addEventListener("contextmenu",w),()=>document.removeEventListener("contextmenu",w)},[x.disableContextMenu,q.isAdminMode]),e.useEffect(()=>{const w=async O=>{const W=x.exitShortcut.toLowerCase().split("+"),I=W.includes("ctrl")===O.ctrlKey,H=W.includes("shift")===O.shiftKey,M=W.includes("alt")===O.altKey,X=W.some(v=>v===O.key.toLowerCase());if(I&&H&&M&&X){O.preventDefault(),(L?await L("keyboard"):!0)&&(q.isLocked?o():E());return}if(x.disableShortcuts&&!q.isAdminMode){const v=["F5","F11","F12"],J=[{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(v.includes(O.key)){O.preventDefault();return}for(const Q of J)if(Q.ctrl===O.ctrlKey&&(Q.shift??!1)===O.shiftKey&&(Q.alt??!1)===O.altKey&&Q.key.toLowerCase()===O.key.toLowerCase()){O.preventDefault();return}}};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[x.disableShortcuts,x.exitShortcut,q.isAdminMode,q.isLocked,E,o,L]),e.useEffect(()=>{if(!x.disableCopyPaste)return;const w=_=>{q.isAdminMode||_.preventDefault()},O=_=>{q.isAdminMode||_.preventDefault()};return document.addEventListener("copy",w),document.addEventListener("paste",O),()=>{document.removeEventListener("copy",w),document.removeEventListener("paste",O)}},[x.disableCopyPaste,q.isAdminMode]),e.useEffect(()=>{const w=["mousedown","mousemove","keydown","touchstart","scroll"],O=()=>{s()};for(const _ of w)document.addEventListener(_,O);return s(),()=>{for(const _ of w)document.removeEventListener(_,O);y.current&&clearTimeout(y.current)}},[s]),e.useEffect(()=>{if(x.autoFullscreen){const w=setTimeout(()=>{G()},100);return()=>clearTimeout(w)}},[x.autoFullscreen,G]),e.useImperativeHandle(f,()=>({getState:()=>q,enterFullscreen:G,exitFullscreen:E,toggleFullscreen:$,lock:R,unlock:k,enterAdminMode:S,exitAdminMode:D,resetIdleTimer:s,showScreensaver:a,hideScreensaver:r,openPinDialog:o,closePinDialog:l}),[q,G,E,$,R,k,S,D,s,a,r,o,l]);const g={...q,enterFullscreen:G,exitFullscreen:E,toggleFullscreen:$,lock:R,unlock:k,enterAdminMode:S,exitAdminMode:D,resetIdleTimer:s},m=["nice-kiosk-mode",`nice-kiosk-mode--${q.mode}`,q.isFullscreen&&"nice-kiosk-mode--fullscreen",!x.showCursor&&"nice-kiosk-mode--no-cursor",x.disableSelection&&"nice-kiosk-mode--no-select",!x.allowScrolling&&"nice-kiosk-mode--no-scroll",x.className].filter(Boolean).join(" ");return t.jsx(qe.Provider,{value:g,children:t.jsxs("div",{ref:u,className:m,onClick:c,children:[t.jsx("div",{className:"nice-kiosk-mode__content",children:C}),q.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:D,"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})]}),q.isScreensaverActive&&t.jsx("div",{className:"nice-kiosk-mode__screensaver",onClick:r,onTouchStart:r,children:h||t.jsx("div",{className:"nice-kiosk-mode__screensaver-default",children:t.jsx("div",{className:"nice-kiosk-mode__screensaver-text",children:"Touch to continue"})})}),q.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 ${Y?"nice-kiosk-mode__pin-input--error":""}`,value:V,onChange:w=>z(w.target.value),onKeyPress:F,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:l,children:"Cancel"}),t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--submit",onClick:j,children:"Unlock"})]}),Y&&t.jsx("div",{className:"nice-kiosk-mode__pin-error",children:"Incorrect PIN"})]})}),q.isLocked&&!q.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__lock-indicator",children:t.jsx("span",{className:"nice-kiosk-mode__lock-text",children:"Kiosk Locked"})})]})})});pe.displayName="NiceKioskMode";const Ue=pe;Ue.displayName="NiceKioskModeProvider";const He=e.createContext(null),Mt=()=>{const n=e.useContext(He);if(!n)throw new Error("useLowPowerMode must be used within NiceLowPowerModeProvider");return n},Ft={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}},Bt={initialMode:"normal",autoDimTimeout:120*1e3,autoSleepTimeout:600*1e3,lowBatteryThreshold:20,criticalBatteryThreshold:5,wakeOnTouch:!0,wakeOnMotion:!1,transitionDuration:500},ye=e.forwardRef((n,f)=>{const{config:p,onModeChange:C,onBrightnessChange:h,onSleep:N,onWake:T,onLowBattery:P,children:i}=n,d={...Bt,...p},b={...Ft,...p==null?void 0:p.modes},L=e.useRef(null),x=e.useRef(null),u=e.useRef(Date.now()),y=e.useRef(null),[A,q]=e.useState({currentMode:d.initialMode,brightness:b[d.initialMode].brightness??1,isPowerSaving:d.initialMode!=="normal",isSleeping:d.initialMode==="sleep",idleTime:0,isDisplayOn:!0}),U=e.useCallback(D=>{const c=b[D];document.documentElement.style.setProperty("--lpm-brightness",String(c.brightness)),document.documentElement.style.setProperty("--lpm-transition",`${d.transitionDuration}ms`),c.disableAnimations?document.documentElement.classList.add("lpm-no-animations"):document.documentElement.classList.remove("lpm-no-animations"),c.reduceImageQuality?document.documentElement.classList.add("lpm-reduced-quality"):document.documentElement.classList.remove("lpm-reduced-quality")},[b,d.transitionDuration]),V=e.useCallback(D=>{q(c=>{if(c.currentMode===D)return c;const s=c.currentMode,a=b[D];return U(D),C==null||C(D,s),h==null||h(a.brightness??1),D==="sleep"&&s!=="sleep"?N==null||N():s==="sleep"&&D!=="sleep"&&(T==null||T()),{...c,currentMode:D,brightness:a.brightness??1,isPowerSaving:D!=="normal",isSleeping:D==="sleep",isDisplayOn:D!=="sleep"}})},[b,U,C,h,N,T]),z=e.useCallback(D=>{const c=Math.max(0,Math.min(1,D));document.documentElement.style.setProperty("--lpm-brightness",String(c)),q(s=>({...s,brightness:c})),h==null||h(c)},[h]),Y=e.useCallback(()=>{V("sleep")},[V]),B=e.useCallback(()=>{V("normal"),E()},[V]),G=e.useCallback(()=>{A.currentMode==="normal"?V("low"):V("normal")},[A.currentMode,V]),E=e.useCallback(()=>{if(u.current=Date.now(),L.current&&clearTimeout(L.current),x.current&&clearTimeout(x.current),A.isSleeping){B();return}A.currentMode!=="normal"&&A.currentMode!=="sleep"&&V("normal"),d.autoDimTimeout>0&&(L.current=setTimeout(()=>{A.currentMode==="normal"&&V("dim")},d.autoDimTimeout)),d.autoSleepTimeout>0&&(x.current=setTimeout(()=>{V("sleep")},d.autoSleepTimeout)),q(D=>({...D,idleTime:0}))},[A.isSleeping,A.currentMode,d.autoDimTimeout,d.autoSleepTimeout,V,B]),$=e.useCallback(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const D=await navigator.getBattery();return{level:Math.round(D.level*100),charging:D.charging}}catch{return{}}return{}},[]),R=e.useCallback(async()=>{const D=await $();D.level!==void 0&&(q(c=>({...c,batteryLevel:D.level,isCharging:D.charging})),D.charging||(D.level<=d.criticalBatteryThreshold?(V("sleep"),P==null||P(D.level)):D.level<=d.lowBatteryThreshold&&(A.currentMode==="normal"&&V("low"),P==null||P(D.level))))},[$,d.lowBatteryThreshold,d.criticalBatteryThreshold,A.currentMode,V,P]),k=e.useCallback(()=>{if(!(p!=null&&p.schedule)||p.schedule.length===0)return;const c=new Date().getHours();for(const s of p.schedule){const{startHour:a,endHour:r,mode:o}=s;let l;if(a<=r?l=c>=a&&c<r:l=c>=a||c<r,l){q(j=>({...j,scheduledModeActive:o})),A.currentMode!==o&&V(o);return}}q(s=>({...s,scheduledModeActive:void 0}))},[p==null?void 0:p.schedule,A.currentMode,V]);e.useEffect(()=>{const D=["mousedown","mousemove","keydown","touchstart","scroll"],c=()=>{d.wakeOnTouch&&E()};for(const s of D)document.addEventListener(s,c);return E(),()=>{for(const s of D)document.removeEventListener(s,c);L.current&&clearTimeout(L.current),x.current&&clearTimeout(x.current)}},[d.wakeOnTouch,E]),e.useEffect(()=>{R(),(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const c=await navigator.getBattery();y.current=c,c.addEventListener("levelchange",R),c.addEventListener("chargingchange",R)}catch{}})()},[R]),e.useEffect(()=>{k();const D=setInterval(k,6e4);return()=>clearInterval(D)},[k]),e.useEffect(()=>{U(d.initialMode)},[d.initialMode,U]),e.useImperativeHandle(f,()=>({getState:()=>A,setMode:V,setBrightness:z,sleep:Y,wake:B,togglePowerSaving:G,resetIdleTimer:E,getBatteryInfo:$}),[A,V,z,Y,B,G,E,$]);const S={...A,setMode:V,setBrightness:z,sleep:Y,wake:B,resetIdleTimer:E};return t.jsx(He.Provider,{value:S,children:t.jsxs("div",{className:`nice-lpm nice-lpm--${A.currentMode}`,children:[t.jsx("div",{className:"nice-lpm__overlay",style:{opacity:1-A.brightness}}),t.jsx("div",{className:"nice-lpm__content",children:i}),A.isSleeping&&t.jsx("div",{className:"nice-lpm__sleep-screen",onClick:d.wakeOnTouch?B:void 0,onTouchStart:d.wakeOnTouch?B:void 0,children:t.jsx("div",{className:"nice-lpm__sleep-message",children:"Touch to wake"})})]})})});ye.displayName="NiceLowPowerMode";const We=ye;We.displayName="NiceLowPowerModeProvider";const Ve=e.createContext(null),$t=()=>{const n=e.useContext(Ve);if(!n)throw new Error("useOrientationLock must be used within NiceOrientationLockProvider");return n},qt={preferredOrientation:"any",allowUserChange:!0,showRotationPrompt:!0,lockOnMount:!1,autoRotateContent:!1,supportedOrientations:["any","portrait","portrait-primary","portrait-secondary","landscape","landscape-primary","landscape-secondary","natural"]},ze=()=>{if(typeof window>"u")return"portrait";const n=window.screen;return n.orientation?n.orientation.type:window.innerHeight>window.innerWidth?"portrait":"landscape"},Ut=()=>{if(typeof window>"u")return 0;const n=window.screen;return n.orientation?n.orientation.angle:window.orientation||0},me=()=>{if(typeof window>"u")return{type:"portrait",angle:0,isPortrait:!0,isLandscape:!1,width:0,height:0,aspectRatio:0};const n=ze(),f=Ut(),p=window.screen.width,C=window.screen.height,h=n.includes("portrait")||window.innerHeight>window.innerWidth,N=n.includes("landscape")||window.innerWidth>window.innerHeight;return{type:n,angle:f,isPortrait:h,isLandscape:N,width:p,height:C,aspectRatio:p/C}},Ht=()=>{if(typeof window>"u")return!1;const n=window.screen;return!!(n.orientation&&typeof n.orientation.lock=="function")},be=e.forwardRef((n,f)=>{const{config:p,onOrientationChange:C,onLockChange:h,onUnsupportedOrientation:N,rotationPrompt:T,children:P,className:i}=n,d={...qt,...p},b=e.useRef(!1),[L,x]=e.useState(ze),[u,y]=e.useState(null),[A,q]=e.useState(me),[U]=e.useState(Ht),V=e.useCallback(c=>!!(d.supportedOrientations.includes("any")||d.supportedOrientations.includes(c)||c.includes("portrait")&&d.supportedOrientations.includes("portrait")||c.includes("landscape")&&d.supportedOrientations.includes("landscape")),[d.supportedOrientations]),z=e.useCallback(async c=>{if(!U)return console.warn("Screen Orientation API is not available"),y(c),h==null||h(!0,c),!1;try{return await window.screen.orientation.lock(c),y(c),h==null||h(!0,c),!0}catch(s){return console.warn("Failed to lock orientation:",s),y(c),h==null||h(!0,c),!1}},[U,h]),Y=e.useCallback(async()=>{if(y(null),h==null||h(!1,null),!U)return!1;try{return window.screen.orientation.unlock(),!0}catch(c){return console.warn("Failed to unlock orientation:",c),!1}},[U,h]),B=e.useCallback(async()=>u?Y():z(L),[u,L,z,Y]),G=e.useCallback(()=>me(),[]),E=e.useCallback(()=>{const c=me(),s=c.type;x(s),q(c),C==null||C(c),V(s)||N==null||N(s,d.supportedOrientations)},[d.supportedOrientations,V,C,N]);e.useEffect(()=>{b.current||(b.current=!0,E(),d.lockOnMount&&d.preferredOrientation!=="any"&&z(d.preferredOrientation))},[d.lockOnMount,d.preferredOrientation,E,z]),e.useEffect(()=>{const c=window.screen.orientation;return c&&c.addEventListener("change",E),window.addEventListener("resize",E),window.addEventListener("orientationchange",E),()=>{c&&c.removeEventListener("change",E),window.removeEventListener("resize",E),window.removeEventListener("orientationchange",E)}},[E]);const $={current:L,locked:u,isLocked:u!==null,isSupported:V(L),info:A,isApiAvailable:U};e.useImperativeHandle(f,()=>({getState:()=>$,lock:z,unlock:Y,toggleLock:B,getOrientationInfo:G,isOrientationSupported:V}),[$,z,Y,B,G,V]);const R={...$,lock:z,unlock:Y,getOrientationInfo:G},k=e.useCallback(()=>{if(!d.autoRotateContent||!u||u==="any")return;const c=u.includes("portrait"),s=A.isPortrait;return c===s?void 0:{transform:`rotate(${c?90:-90}deg)`,transformOrigin:"center center",width:c?A.height:A.width,height:c?A.width:A.height}},[d.autoRotateContent,u,A]),S=d.showRotationPrompt&&u!==null&&u!=="any"&&!$.isSupported,D=["nice-orientation",`nice-orientation--${L}`,u&&`nice-orientation--locked-${u}`,!$.isSupported&&"nice-orientation--unsupported",i].filter(Boolean).join(" ");return t.jsx(Ve.Provider,{value:R,children:t.jsxs("div",{className:D,style:k(),"data-orientation":L,"data-locked":u||void 0,children:[P,S&&t.jsx("div",{className:"nice-orientation__prompt",children:T||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"," ",u!=null&&u.includes("portrait")?"portrait":"landscape"," mode"]})]})})]})})});be.displayName="NiceOrientationLock";const Ge=be;Ge.displayName="NiceOrientationLockProvider";const Ye=e.createContext(null),Wt=()=>{const n=e.useContext(Ye);if(!n)throw new Error("useRemoteManagement must be used within NiceRemoteManagementProvider");return n},Vt={heartbeatInterval:3e4,reconnectDelay:5e3,maxReconnectAttempts:10,enableHealthMonitoring:!0,healthReportInterval:6e4,enableScreenshot:!0,enableLogs:!0,logBufferSize:100},we=e.forwardRef((n,f)=>{const{config:p,onConnectionChange:C,onCommandReceived:h,onCustomCommand:N,children:T}=n,P={...Vt,...p},i=e.useRef(null),d=e.useRef(null),b=e.useRef(null),L=e.useRef([]),x=e.useRef(Date.now()),u=e.useRef(0),[y,A]=e.useState({status:"disconnected",isConnected:!1,reconnectAttempts:0,pendingCommands:[],commandHistory:[]}),q=e.useCallback(()=>{const k=typeof navigator<"u"?navigator:null,S=typeof window<"u"?window:null;return{deviceId:P.deviceId,name:P.deviceName||P.deviceId,type:"embedded-display",os:k==null?void 0:k.platform,browser:k==null?void 0:k.userAgent,resolution:S?`${S.screen.width}x${S.screen.height}`:void 0,uptime:Math.floor((Date.now()-x.current)/1e3),metadata:{}}},[P.deviceId,P.deviceName]),U=e.useCallback(async()=>{const k={isOnline:typeof navigator<"u"?navigator.onLine:!0,lastUpdated:new Date};if(typeof performance<"u"&&"memory"in performance){const S=performance.memory;S&&(k.memory=Math.round(S.usedJSHeapSize/S.jsHeapSizeLimit*100))}if(typeof navigator<"u"&&"getBattery"in navigator)try{const S=await navigator.getBattery();k.battery=Math.round(S.level*100)}catch{}if(typeof navigator<"u"&&"storage"in navigator&&"estimate"in navigator.storage)try{const S=await navigator.storage.estimate();S.quota&&S.usage&&(k.storageFree=S.quota-S.usage)}catch{}return k},[]),V=e.useCallback(async()=>{var k;if(((k=i.current)==null?void 0:k.readyState)!==WebSocket.OPEN){A(S=>({...S,status:"connecting"})),C==null||C("connecting");try{const S=new URL(P.serverUrl);S.searchParams.set("deviceId",P.deviceId),P.apiKey&&S.searchParams.set("apiKey",P.apiKey);const D=new WebSocket(S.toString());i.current=D,D.onopen=()=>{u.current=0,A(c=>({...c,status:"connected",isConnected:!0,reconnectAttempts:0,error:void 0})),C==null||C("connected"),D.send(JSON.stringify({type:"register",payload:q()}))},D.onmessage=async c=>{try{const s=JSON.parse(c.data);if(s.type==="command"){const a={id:s.id,type:s.commandType,payload:s.payload,timestamp:new Date,acknowledged:!0,executed:!1};A(l=>({...l,pendingCommands:[...l.pendingCommands,a]})),h==null||h(a);let r,o;try{switch(a.type){case"restart":typeof window<"u"&&window.location.reload();break;case"screenshot":r=await $();break;case"logs":r=L.current;break;case"custom":N&&(r=await N(a));break}a.executed=!0,a.result=r}catch(l){o=l instanceof Error?l.message:String(l),a.error=o}D.send(JSON.stringify({type:"commandResult",commandId:a.id,result:r,error:o})),A(l=>({...l,pendingCommands:l.pendingCommands.filter(j=>j.id!==a.id),commandHistory:[...l.commandHistory.slice(-49),a]}))}}catch{}},D.onerror=()=>{i.current===D&&A(c=>({...c,status:"error",error:"WebSocket error"}))},D.onclose=()=>{i.current===D&&(i.current=null,A(c=>({...c,status:"disconnected",isConnected:!1})),u.current<P.maxReconnectAttempts&&setTimeout(()=>{u.current>=P.maxReconnectAttempts||(u.current+=1,A(c=>({...c,reconnectAttempts:u.current})),V())},P.reconnectDelay),C==null||C("disconnected"))}}catch(S){A(D=>({...D,status:"error",error:S instanceof Error?S.message:"Connection failed"})),C==null||C("error")}}},[P.serverUrl,P.deviceId,P.apiKey,P.maxReconnectAttempts,P.reconnectDelay,q,C,h,N]),z=e.useCallback(()=>{u.current=P.maxReconnectAttempts,i.current&&(i.current.close(),i.current=null),A(k=>({...k,status:"disconnected",isConnected:!1,reconnectAttempts:P.maxReconnectAttempts}))},[P.maxReconnectAttempts]),Y=e.useCallback(async()=>{var k;((k=i.current)==null?void 0:k.readyState)===WebSocket.OPEN&&(i.current.send(JSON.stringify({type:"heartbeat",timestamp:new Date().toISOString(),deviceId:P.deviceId})),A(S=>({...S,lastHeartbeat:new Date})))},[P.deviceId]),B=e.useCallback(async k=>{var D;if(((D=i.current)==null?void 0:D.readyState)!==WebSocket.OPEN)return;const S=k||await U();i.current.send(JSON.stringify({type:"health",metrics:S,deviceId:P.deviceId})),A(c=>({...c,healthMetrics:S}))},[P.deviceId,U]),G=e.useCallback(async(k,S,D)=>{var c;((c=i.current)==null?void 0:c.readyState)===WebSocket.OPEN&&i.current.send(JSON.stringify({type:"commandResult",commandId:k,result:S,error:D}))},[]),E=e.useCallback((k,S,D)=>{var s;const c={level:k,message:S,data:D,timestamp:new Date};L.current=[...L.current.slice(-(P.logBufferSize-1)),c],P.enableLogs&&((s=i.current)==null?void 0:s.readyState)===WebSocket.OPEN&&i.current.send(JSON.stringify({type:"log",...c,deviceId:P.deviceId}))},[P.deviceId,P.enableLogs,P.logBufferSize]),$=e.useCallback(async()=>{if(P.enableScreenshot)try{return"screenshot-not-implemented"}catch{return}},[P.enableScreenshot]);e.useEffect(()=>(u.current=0,V(),()=>{z(),d.current&&clearInterval(d.current),b.current&&clearInterval(b.current)}),[]),e.useEffect(()=>{if(y.isConnected)return d.current=setInterval(Y,P.heartbeatInterval),()=>{d.current&&clearInterval(d.current)}},[y.isConnected,P.heartbeatInterval,Y]),e.useEffect(()=>{if(!(!y.isConnected||!P.enableHealthMonitoring))return b.current=setInterval(()=>{B()},P.healthReportInterval),B(),()=>{b.current&&clearInterval(b.current)}},[y.isConnected,P.enableHealthMonitoring,P.healthReportInterval,B]),e.useImperativeHandle(f,()=>({getState:()=>y,connect:V,disconnect:z,sendHeartbeat:Y,sendHealthMetrics:B,reportCommandResult:G,sendLog:E,captureScreenshot:$,getDeviceInfo:q}),[y,V,z,Y,B,G,E,$,q]);const R={...y,deviceInfo:q(),connect:V,disconnect:z,sendLog:E};return t.jsx(Ye.Provider,{value:R,children:T})});we.displayName="NiceRemoteManagement";const Xe=we;Xe.displayName="NiceRemoteManagementProvider";const zt={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},Ke=e.forwardRef((n,f)=>{var j,F,g,m,w,O;const{config:p,enabled:C=!0,onActivate:h,onDeactivate:N,onModeChange:T,children:P}=n,i={...zt,...p},d=e.useRef(null),b=e.useRef(null),L=e.useRef(null),x=e.useRef(null),[u,y]=e.useState({isActive:!1,activeModes:[],shiftX:0,shiftY:0,isDimmed:!1,isScreensaverActive:!1,idleTime:0}),[A,q]=e.useState(0),[U,V]=e.useState({x:50,y:50,dx:1,dy:1}),z=e.useCallback(()=>{if(!i.pixelShift)return;const{maxShift:_}=i.pixelShift,W=Math.floor(Math.random()*(_*2+1))-_,I=Math.floor(Math.random()*(_*2+1))-_;y(H=>({...H,shiftX:W,shiftY:I}))},[i.pixelShift]),Y=e.useCallback(()=>{!i.pixelShift||L.current||(z(),L.current=setInterval(z,i.pixelShift.interval))},[i.pixelShift,z]),B=e.useCallback(()=>{L.current&&(clearInterval(L.current),L.current=null),y(_=>({..._,shiftX:0,shiftY:0}))},[]),G=e.useCallback(()=>{!i.colorCycle||x.current||(x.current=setInterval(()=>{q(_=>{var W;return(_+1)%(((W=i.colorCycle)==null?void 0:W.colors.length)||1)})},i.colorCycle.interval))},[i.colorCycle]),E=e.useCallback(()=>{x.current&&(clearInterval(x.current),x.current=null),q(0)},[]),$=e.useCallback(()=>{if(!C||u.isActive)return;const _=i.modes;y(W=>({...W,isActive:!0,activeModes:_})),_.includes("pixel-shift")&&Y(),_.includes("color-cycling")&&G(),_.includes("dimming")&&y(W=>({...W,isDimmed:!0})),_.includes("screensaver")&&y(W=>({...W,isScreensaverActive:!0})),h==null||h(),T==null||T(_)},[C,u.isActive,i.modes,Y,G,h,T]),R=e.useCallback(()=>{u.isActive&&(B(),E(),y(_=>({..._,isActive:!1,activeModes:[],isDimmed:!1,isScreensaverActive:!1})),N==null||N(),T==null||T([]))},[u.isActive,B,E,N,T]),k=e.useCallback(()=>{u.isActive?R():$()},[u.isActive,$,R]),S=e.useCallback(()=>{b.current&&clearTimeout(b.current),u.isActive&&R(),C&&i.inactivityTimeout>0&&(b.current=setTimeout(()=>{$()},i.inactivityTimeout))},[C,u.isActive,i.inactivityTimeout,$,R]),D=e.useCallback(()=>{y(_=>({..._,isScreensaverActive:!0}))},[]),c=e.useCallback(()=>{y(_=>({..._,isScreensaverActive:!1})),S()},[S]),s=e.useCallback(_=>{y(W=>({...W,isDimmed:_>0}))},[]);e.useEffect(()=>{var W;if(!u.isScreensaverActive||((W=i.screensaver)==null?void 0:W.type)!=="bounce")return;const _=setInterval(()=>{V(I=>{let{x:H,y:M,dx:X,dy:v}=I;return H+=X*.5,M+=v*.5,(H<=0||H>=90)&&(X=-X),(M<=0||M>=90)&&(v=-v),{x:H,y:M,dx:X,dy:v}})},50);return()=>clearInterval(_)},[u.isScreensaverActive,(j=i.screensaver)==null?void 0:j.type]),e.useEffect(()=>{if(!C)return;const _=["mousedown","mousemove","keydown","touchstart","scroll","wheel"],W=()=>{S()};for(const I of _)document.addEventListener(I,W);return S(),()=>{for(const I of _)document.removeEventListener(I,W);b.current&&clearTimeout(b.current),B(),E()}},[C,S,B,E]),e.useImperativeHandle(f,()=>({getState:()=>u,activate:$,deactivate:R,toggle:k,resetIdleTimer:S,forceShift:z,showScreensaver:D,hideScreensaver:c,setDimLevel:s}),[u,$,R,k,S,z,D,c,s]);const a=()=>{if(!u.isScreensaverActive)return null;const _=i.screensaver||{type:"blank"};switch(_.type){case"blank":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--blank",onClick:c,onTouchStart:c});case"bounce":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--bounce",onClick:c,onTouchStart:c,children:t.jsx("div",{className:"nice-sbp__bounce-logo",style:{left:`${U.x}%`,top:`${U.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:c,onTouchStart:c,children:Array.from({length:20}).map((W,I)=>t.jsx("div",{className:"nice-sbp__matrix-column",style:{left:`${I*5}%`,animationDelay:`${Math.random()*5}s`,animationDuration:`${5+Math.random()*5}s`},children:Array.from({length:20}).map((H,M)=>t.jsx("span",{children:String.fromCharCode(12448+Math.random()*96)},M))},I))});case"noise":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--noise",onClick:c,onTouchStart:c});case"custom":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--custom",onClick:c,onTouchStart:c,children:_.component});default:return null}},r={transform:u.isActive&&i.modes.includes("pixel-shift")?`translate(${u.shiftX}px, ${u.shiftY}px)`:void 0,transition:(F=i.pixelShift)!=null&&F.smooth?"transform 0.5s ease":void 0},o={"--dim-level":u.isDimmed?((g=i.dimming)==null?void 0:g.level)||.3:0,"--dim-duration":`${((m=i.dimming)==null?void 0:m.fadeDuration)||2e3}ms`},l=u.isActive&&i.modes.includes("color-cycling")?{backgroundColor:(w=i.colorCycle)==null?void 0:w.colors[A],transition:`background-color ${((O=i.colorCycle)==null?void 0:O.transitionDuration)||1e3}ms ease`}:{};return t.jsxs("div",{ref:d,className:`nice-sbp ${u.isActive?"nice-sbp--active":""}`,style:{...l},children:[t.jsx("div",{className:"nice-sbp__content",style:r,children:P}),u.isDimmed&&t.jsx("div",{className:"nice-sbp__dim-overlay",style:o,onClick:S,onTouchStart:S}),a(),u.isActive&&i.modes.includes("invert")&&t.jsx("div",{className:"nice-sbp__invert-overlay"})]})});Ke.displayName="NiceScreenBurnPrevention";const Gt={pointCount:5,targetSize:40,accuracyThreshold:20,pointTimeout:1e4,showAccuracy:!0,allowRetry:!0,persistCalibration:!0,storageKey:"nice-touch-calibration"},Yt=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],Qe=e.forwardRef((n,f)=>{const{config:p,autoStart:C=!1,onStart:h,onPointCalibrated:N,onComplete:T,onCancel:P,children:i}=n,d={...Gt,...p},b=e.useRef(null),L=e.useRef(null),[x,u]=e.useState({isActive:!1,currentPointIndex:0,totalPoints:d.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),y=e.useCallback(k=>{const S=k.filter(M=>M.calibrated&&M.actualX!==void 0&&M.actualY!==void 0);if(S.length<3)return{scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};let D=0,c=0,s=0,a=0;const r=S.length;for(const M of S)D+=M.targetX,c+=M.targetY,s+=M.actualX,a+=M.actualY;const o=D/r,l=c/r,j=s/r,F=a/r;let g=0,m=0,w=0,O=0;for(const M of S){const X=M.targetX-o,v=M.targetY-l,J=M.actualX-j,Q=M.actualY-F;g+=X*X,m+=X*J,w+=v*v,O+=v*Q}const _=m!==0?g/m:1,W=O!==0?w/O:1,I=o-_*j,H=l-W*F;return{scaleX:_,scaleY:W,offsetX:I,offsetY:H,rotation:0}},[]),A=e.useCallback((k,S)=>{const D=k.filter(s=>s.calibrated);if(D.length===0)return 0;let c=0;for(const s of D){if(s.actualX===void 0||s.actualY===void 0)continue;const a=S.scaleX*s.actualX+S.offsetX,r=S.scaleY*s.actualY+S.offsetY,o=s.targetX-a,l=s.targetY-r;c+=Math.sqrt(o*o+l*l)}return c/D.length},[]),q=e.useCallback(()=>{const S=Yt(d.pointCount).map(D=>({...D,calibrated:!1}));u({isActive:!0,currentPointIndex:0,totalPoints:d.pointCount,points:S,isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),h==null||h()},[d.pointCount,h]),U=e.useCallback(()=>{L.current&&clearTimeout(L.current),u(k=>({...k,isActive:!1,isCompleted:!1})),P==null||P()},[P]),V=e.useCallback(()=>{u(k=>({...k,isCompleted:!1}))},[]),z=e.useCallback(()=>{if(d.persistCalibration)try{localStorage.removeItem(d.storageKey)}catch{}u({isActive:!1,currentPointIndex:0,totalPoints:d.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0})},[d.persistCalibration,d.storageKey,d.pointCount]),Y=e.useCallback(k=>{const S=y(k),D=A(k,S),c=D<=d.accuracyThreshold;if(d.persistCalibration&&c)try{localStorage.setItem(d.storageKey,JSON.stringify({matrix:S,points:k}))}catch{}u(s=>({...s,points:k,isActive:!1,isCompleted:!0,isSuccessful:c,matrix:S,averageError:D})),T==null||T(S,c)},[d.accuracyThreshold,d.persistCalibration,d.storageKey,y,A,T]),B=e.useCallback(k=>{if(!x.isActive||!b.current)return;k.preventDefault();const S=b.current.getBoundingClientRect();let D,c;"touches"in k?(D=k.touches[0].clientX,c=k.touches[0].clientY):(D=k.clientX,c=k.clientY);const s=(D-S.left)/S.width*100,a=(c-S.top)/S.height*100,r=x.currentPointIndex,o=[...x.points];o[r]={...o[r],actualX:s,actualY:a,calibrated:!0};const l=r+1;N==null||N(o[r],r),l>=x.totalPoints?Y(o):u(j=>({...j,currentPointIndex:l,points:o}))},[x.isActive,x.currentPointIndex,x.points,x.totalPoints,Y,N]),G=e.useCallback((k,S)=>{const D=x.matrix;return D?{x:D.scaleX*k+D.offsetX,y:D.scaleY*S+D.offsetY}:{x:k,y:S}},[x.matrix]),E=e.useCallback(()=>{if(x.matrix)return!0;if(d.persistCalibration)try{return!!localStorage.getItem(d.storageKey)}catch{return!1}return!1},[x.matrix,d.persistCalibration,d.storageKey]),$=e.useCallback(()=>{if(d.persistCalibration)try{localStorage.removeItem(d.storageKey)}catch{}u(k=>({...k,matrix:null}))},[d.persistCalibration,d.storageKey]);if(e.useEffect(()=>{if(d.persistCalibration)try{const k=localStorage.getItem(d.storageKey);if(k){const S=JSON.parse(k);u(D=>({...D,matrix:S.matrix,points:S.points||[],isCompleted:!0,isSuccessful:!0}))}}catch{}},[d.persistCalibration,d.storageKey]),e.useEffect(()=>{if(!x.isActive)return;const k=b.current;if(k)return k.addEventListener("touchstart",B,{passive:!1}),k.addEventListener("mousedown",B),()=>{k.removeEventListener("touchstart",B),k.removeEventListener("mousedown",B)}},[x.isActive,B]),e.useEffect(()=>{if(!(!x.isActive||d.pointTimeout<=0))return L.current=setTimeout(()=>{x.currentPointIndex<x.totalPoints-1?u(k=>({...k,currentPointIndex:k.currentPointIndex+1})):Y(x.points)},d.pointTimeout),()=>{L.current&&clearTimeout(L.current)}},[x.isActive,x.currentPointIndex,x.points,x.totalPoints,d.pointTimeout,Y]),e.useEffect(()=>{C&&!E()&&q()},[C,E,q]),e.useImperativeHandle(f,()=>({getState:()=>x,start:q,cancel:U,reset:z,getMatrix:()=>x.matrix,transformPoint:G,hasCalibration:E,clearCalibration:$}),[x,q,U,z,G,E,$]),!x.isActive&&!x.isCompleted)return t.jsx(t.Fragment,{children:i});const R=x.isActive?x.points[x.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 ",x.currentPointIndex+1," of ",x.totalPoints]})]}),R&&t.jsx("div",{className:"nice-touch-calibration__target",style:{left:`${R.targetX}%`,top:`${R.targetY}%`,width:d.targetSize,height:d.targetSize},children:(p==null?void 0:p.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"})]})}),x.points.map((k,S)=>k.calibrated&&t.jsx("div",{className:"nice-touch-calibration__calibrated",style:{left:`${k.actualX}%`,top:`${k.actualY}%`}},S)),x.isActive&&t.jsx("button",{className:"nice-touch-calibration__cancel",onClick:U,children:"Cancel"})]}),x.isCompleted&&t.jsxs("div",{className:"nice-touch-calibration__result",children:[t.jsx("div",{className:`nice-touch-calibration__result-icon ${x.isSuccessful?"nice-touch-calibration__result-icon--success":"nice-touch-calibration__result-icon--error"}`,children:t.jsx("span",{className:`nice-platform-mark nice-platform-mark--${x.isSuccessful?"check":"alert"}`,"aria-hidden":"true"})}),t.jsx("h3",{className:"nice-touch-calibration__result-title",children:x.isSuccessful?"Calibration Complete":"Calibration Failed"}),d.showAccuracy&&t.jsxs("p",{className:"nice-touch-calibration__result-accuracy",children:["Average error: ",x.averageError.toFixed(1),"px"]}),!x.isSuccessful&&d.allowRetry&&t.jsx("button",{className:"nice-touch-calibration__retry",onClick:q,children:"Retry Calibration"}),t.jsx("button",{className:"nice-touch-calibration__retry nice-touch-calibration__done",onClick:V,children:"Done"})]})]})});Qe.displayName="NiceTouchCalibration";const Xt={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},Ee=104,Kt=106,Qt=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",oe=["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"],Le=n=>{let f=oe[Ee],p=Ee;for(let C=0;C<n.length;C++){const h=n[C],N=Qt.indexOf(h);N!==-1&&(f+=oe[N],p+=N*(C+1))}return p=p%103,f+=oe[p],f+=oe[Kt],f},Je=["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],Jt=["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"],Ze=["1110010","1100110","1101100","1000010","1011100","1001110","1010000","1000100","1001000","1110100"],Zt=["LLLLLL","LLGLGG","LLGGLG","LLGGGL","LGLLGG","LGGLLG","LGGGLL","LGLGLG","LGLGGL","LGGLGL"],en=n=>{let f=0;for(let p=0;p<12;p++)f+=parseInt(n[p])*(p%2===0?1:3);return(10-f%10)%10},tn=n=>{let f=n.replace(/\D/g,"").slice(0,12).padStart(12,"0");const p=en(f);f+=p;const C=parseInt(f[0]),h=Zt[C];let N="101";for(let T=1;T<=6;T++){const P=parseInt(f[T]);N+=h[T-1]==="L"?Je[P]:Jt[P]}N+="01010";for(let T=7;T<=12;T++){const P=parseInt(f[T]);N+=Ze[P]}return N+="101",N},nn=n=>{let f=n.replace(/\D/g,"").slice(0,7).padStart(7,"0"),p=0;for(let N=0;N<7;N++)p+=parseInt(f[N])*(N%2===0?3:1);const C=(10-p%10)%10;f+=C;let h="101";for(let N=0;N<4;N++)h+=Je[parseInt(f[N])];h+="01010";for(let N=4;N<8;N++)h+=Ze[parseInt(f[N])];return h+="101",h},sn={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"},rn=n=>{const f=("*"+n.toUpperCase()+"*").split("");let p="";for(const C of f){const h=sn[C];h&&(p+=h+"0")}return p.slice(0,-1)},Pe=n=>{switch(n){case"code128":return Le;case"code39":case"code93":return rn;case"ean13":return tn;case"ean8":return nn;default:return Le}},et=e.forwardRef((n,f)=>{const{value:p,options:C,onGenerate:h,onError:N,showBorder:T=!1,className:P}=n,i={...Xt,...C},d=e.useRef(null),b=e.useRef(null),[L,x]=e.useState(null),[u,y]=e.useState(null),A=e.useCallback(()=>{if(!d.current||!p)return;const G=d.current,E=G.getContext("2d");if(E)try{const R=Pe(i.format)(p),k=i.width,S=R.length*k,D=i.marginTop??i.margin,c=i.marginBottom??i.margin,s=i.marginLeft??i.margin,a=i.marginRight??i.margin,r=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,o=S+s+a,l=i.height+D+c+r;G.width=o,G.height=l,E.fillStyle=i.background,E.fillRect(0,0,o,l),E.fillStyle=i.lineColor;let j=s;const F=i.textPosition==="top"&&i.displayValue?D+r:D;for(let m=0;m<R.length;m++)R[m]==="1"&&E.fillRect(j,F,k,i.height),j+=k;if(i.displayValue&&!i.flat){E.fillStyle=i.lineColor,E.font=`${i.fontSize}px ${i.font}`,E.textBaseline=i.textPosition==="top"?"top":"bottom";let m=s;i.textAlign==="center"?(m=s+S/2,E.textAlign="center"):i.textAlign==="right"?(m=s+S,E.textAlign="right"):E.textAlign="left";const w=i.textPosition==="top"?D+i.textMargin:l-c-i.textMargin;E.fillText(p,m,w)}const g=G.toDataURL("image/png");y(g),x(null),h==null||h(g)}catch($){const R=$ instanceof Error?$.message:"Failed to generate barcode";x(R),N==null||N(new Error(R))}},[p,i,h,N]);e.useEffect(()=>{A()},[A]);const q=e.useCallback((G="image/png",E=1)=>{var $;return(($=d.current)==null?void 0:$.toDataURL(G,E))||null},[]),U=e.useCallback(()=>{if(!d.current||!p)return null;try{const E=Pe(i.format)(p),$=i.width,R=i.marginTop??i.margin,k=i.marginBottom??i.margin,S=i.marginLeft??i.margin,D=i.marginRight??i.margin,c=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,s=E.length*$,a=s+S+D,r=i.height+R+k+c,o=[];let l=S;const j=i.textPosition==="top"&&i.displayValue?R+c:R;for(let g=0;g<E.length;g++)E[g]==="1"&&o.push(`<rect x="${l}" y="${j}" width="${$}" height="${i.height}" fill="${i.lineColor}"/>`),l+=$;let F="";if(i.displayValue&&!i.flat){const g=i.textAlign==="center"?"middle":i.textAlign==="right"?"end":"start";let m=S;i.textAlign==="center"?m=S+s/2:i.textAlign==="right"&&(m=S+s);const w=i.textPosition==="top"?R+i.fontSize:r-k-i.textMargin;F=`<text x="${m}" y="${w}" font-family="${i.font}" font-size="${i.fontSize}" text-anchor="${g}" fill="${i.lineColor}">${p}</text>`}return`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${r}" viewBox="0 0 ${a} ${r}">
|
|
2
|
+
<rect width="100%" height="100%" fill="${i.background}"/>
|
|
3
|
+
${o.join(`
|
|
4
4
|
`)}
|
|
5
|
-
${
|
|
6
|
-
</svg>`}catch{return null}},[x,o]),M=e.useCallback(()=>u.current,[]),W=e.useCallback((z="barcode",P="png")=>{const H=document.createElement("a");if(P==="svg"){const d=L();if(!d)return;const I=new Blob([d],{type:"image/svg+xml"});H.href=URL.createObjectURL(I),H.download=`${z}.svg`}else{const d=B();if(!d)return;H.href=d,H.download=`${z}.png`}H.click()},[B,L]),X=e.useCallback(()=>{j()},[j]);e.useImperativeHandle(A,()=>({toDataURL:B,toSVG:L,getCanvas:M,download:W,regenerate:X}),[B,L,M,W,X]);const F=["nice-barcode-generator",O&&"nice-barcode-generator--bordered",D&&"nice-barcode-generator--error",q].filter(Boolean).join(" ");return t.jsxs("div",{className:F,children:[t.jsx("canvas",{ref:u,className:"nice-barcode-generator__canvas"}),t.jsx("svg",{ref:S,style:{display:"none"}}),D&&t.jsx("div",{className:"nice-barcode-generator__error",children:t.jsx("span",{children:D})})]})});Me.displayName="NiceBarcodeGenerator";const At={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"},Dt=m=>({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"})[m.toLowerCase().replace("-","_")]||"unknown",Et=()=>typeof window<"u"&&"BarcodeDetector"in window,Lt=m=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[m],Rt=()=>{try{const m=new(window.AudioContext||window.webkitAudioContext),A=m.createOscillator(),x=m.createGain();A.connect(x),x.connect(m.destination),A.type="sine",A.frequency.value=1e3,x.gain.value=.1,A.start(),setTimeout(()=>{A.stop(),m.close()},100)}catch{}},Pt=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate(50)},Fe=e.forwardRef((m,A)=>{const{config:x,onScan:k,onBatchScan:p,onError:N,onCameraReady:O,customScanFrame:q,showScanFrame:o=!0,autoStart:u=!1,children:S,className:D}=m,b={...At,...x},f=e.useRef(null),g=e.useRef(null),j=e.useRef(null),B=e.useRef(null),L=e.useRef(null),M=e.useRef(null),[W,X]=e.useState(!1),[F,z]=e.useState(!1),[P,H]=e.useState(null),[d,I]=e.useState(null),[E,R]=e.useState(null),[i,a]=e.useState(b.facingMode),[n,s]=e.useState(null),r=Et(),c=e.useCallback(async()=>{try{return(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach(Y=>Y.stop()),R(!0),!0}catch{return R(!1),!1}},[]),l=e.useCallback(async()=>{if(!f.current)return;const V=Lt(b.resolution),Y={video:{facingMode:i,width:{ideal:V.width},height:{ideal:V.height}},audio:!1};try{const C=await navigator.mediaDevices.getUserMedia(Y);j.current=C,f.current.srcObject=C,await f.current.play(),z(!0),R(!0),I(null),O==null||O()}catch(C){const Q=C instanceof Error?C.message:"Failed to access camera";I(Q),R(!1),N==null||N(new Error(Q))}},[b.resolution,i,O,N]),_=e.useCallback(()=>{j.current&&(j.current.getTracks().forEach(V=>V.stop()),j.current=null),f.current&&(f.current.srcObject=null),z(!1)},[]),y=e.useCallback(async()=>{a(i==="user"?"environment":"user"),W&&_()},[i,W,_]),h=e.useCallback(async()=>{if(r)try{const V=window.BarcodeDetector,Y=b.formats.map(C=>C.replace("_","-"));B.current=new V({formats:Y})}catch(V){const Y=V instanceof Error?V.message:"Failed to initialize barcode detector";I(Y),N==null||N(new Error(Y))}},[r,b.formats,N]),v=e.useCallback(async()=>{if(!(!f.current||!B.current||!F))try{const Y=await B.current.detect(f.current);if(Y.length>0){const C=Y.map(K=>({rawValue:K.rawValue,format:Dt(K.format),boundingBox:K.boundingBox?{x:K.boundingBox.x,y:K.boundingBox.y,width:K.boundingBox.width,height:K.boundingBox.height}:void 0,cornerPoints:K.cornerPoints,timestamp:new Date})),Q=C[0];if(b.continuous&&Q.rawValue===M.current)return;M.current=Q.rawValue,b.showBoundingBox&&Q.boundingBox&&(s(Q.boundingBox),setTimeout(()=>s(null),500)),b.beepOnScan&&Rt(),b.vibrateOnScan&&Pt(),H(Q),k==null||k(Q),C.length>1&&(p==null||p(C)),setTimeout(()=>{M.current=null},1e3)}}catch{}},[F,b.continuous,b.showBoundingBox,b.beepOnScan,b.vibrateOnScan,k,p]),T=e.useCallback(async()=>{X(!0),I(null),await h(),await l()},[h,l]),w=e.useCallback(()=>{X(!1),L.current&&(clearInterval(L.current),L.current=null),_()},[_]),U=e.useCallback(async()=>{W?w():await T()},[W,T,w]),$=e.useCallback(()=>{if(!f.current||!g.current)return null;const V=g.current,Y=f.current;V.width=Y.videoWidth,V.height=Y.videoHeight;const C=V.getContext("2d");return C?(C.drawImage(Y,0,0),V.toDataURL("image/png")):null},[]);e.useEffect(()=>(W&&F&&b.continuous&&(L.current=setInterval(v,b.scanInterval)),()=>{L.current&&(clearInterval(L.current),L.current=null)}),[W,F,b.continuous,b.scanInterval,v]),e.useEffect(()=>(u&&T(),()=>{w()}),[]),e.useEffect(()=>{W&&!F&&l()},[i,W,F,l]),e.useImperativeHandle(A,()=>({getState:()=>({isScanning:W,isCameraReady:F,lastResult:P,error:d,isSupported:r,hasPermission:E}),start:T,stop:w,toggle:U,takeSnapshot:$,switchCamera:y,requestPermission:c}),[W,F,P,d,r,E,T,w,U,$,y,c]);const G=["nice-barcode-scanner",W&&"nice-barcode-scanner--scanning",F&&"nice-barcode-scanner--ready",d&&"nice-barcode-scanner--error",D].filter(Boolean).join(" ");return t.jsxs("div",{className:G,children:[t.jsx("video",{ref:f,className:"nice-barcode-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:g,className:"nice-barcode-scanner__canvas"}),o&&W&&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"})]}),n&&f.current&&t.jsx("div",{className:"nice-barcode-scanner__bounding-box",style:{left:`${n.x/f.current.videoWidth*100}%`,top:`${n.y/f.current.videoHeight*100}%`,width:`${n.width/f.current.videoWidth*100}%`,height:`${n.height/f.current.videoHeight*100}%`}}),d&&t.jsxs("div",{className:"nice-barcode-scanner__error",children:[t.jsx("div",{className:"nice-barcode-scanner__error-icon",children:t.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),t.jsx("p",{className:"nice-barcode-scanner__error-text",children:d}),t.jsx("button",{className:"nice-barcode-scanner__error-btn",onClick:()=>T(),children:"Try Again"})]}),!r&&t.jsx("div",{className:"nice-barcode-scanner__unsupported",children:t.jsx("p",{children:"Barcode scanning is not supported in this browser."})}),S&&t.jsx("div",{className:"nice-barcode-scanner__overlay",children:S})]})});Fe.displayName="NiceBarcodeScanner";const Tt=e.createContext(null),Ot={autoIncrementDuplicates:!0,maxItems:1e3,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,showBoundingBox:!0,allowManualEntry:!0,minConfidence:0},Mt=()=>{try{const m=new(window.AudioContext||window.webkitAudioContext),A=m.createOscillator(),x=m.createGain();A.connect(x),x.connect(m.destination),A.frequency.value=1200,A.type="sine",x.gain.setValueAtTime(.3,m.currentTime),x.gain.exponentialRampToValueAtTime(.01,m.currentTime+.1),A.start(),A.stop(m.currentTime+.1)}catch{}},Ft=(m=50)=>{"vibrate"in navigator&&navigator.vibrate(m)},Bt=()=>`${Date.now()}-${Math.random().toString(36).slice(2,11)}`,Be=e.forwardRef((m,A)=>{const{options:x,initialItems:k=[],onScan:p,onRemove:N,onBatchComplete:O,onQuantityChange:q,onError:o,validateScan:u,transformValue:S,className:D,children:b}=m,f={...Ot,...x},g=e.useRef(null),j=e.useRef(null),B=e.useRef(null),L=e.useRef(null),M=e.useRef(0),W=e.useRef(""),X=e.useRef(0),[F,z]=e.useState(k),[P,H]=e.useState(!1),[d,I]=e.useState(!1),[E,R]=e.useState(""),[i,a]=e.useState([]),[n,s]=e.useState(null);e.useEffect(()=>{(async()=>{if("BarcodeDetector"in window)try{const Q=await BarcodeDetector.getSupportedFormats();Q.length>0&&(L.current=new BarcodeDetector({formats:(x==null?void 0:x.formats)||Q}),I(!0))}catch{I(!1)}})()},[x==null?void 0:x.formats]);const r=e.useCallback(async(C,Q="unknown",K)=>{const J=S?S(C,Q):C;if(u&&!await u(J,Q))return;const Z=F.findIndex(ee=>ee.value===J);if(Z!==-1&&f.autoIncrementDuplicates){const ee=[...F];ee[Z]={...ee[Z],quantity:ee[Z].quantity+1,timestamp:Date.now()},z(ee),q==null||q(ee[Z],ee[Z].quantity)}else if(F.length<f.maxItems){const ee={id:Bt(),value:J,format:Q,timestamp:Date.now(),rawValue:C,quantity:1,boundingBox:K};z(te=>[ee,...te]),p==null||p(ee)}f.beepOnScan&&Mt(),f.vibrateOnScan&&Ft()},[F,f,u,S,p,q]),c=e.useCallback(C=>{const Q=F.find(K=>K.id===C);Q&&(z(K=>K.filter(J=>J.id!==C)),N==null||N(Q))},[F,N]),l=e.useCallback((C,Q)=>{if(Q<1){c(C);return}z(J=>J.map(Z=>Z.id===C?{...Z,quantity:Q}:Z));const K=F.find(J=>J.id===C);K&&(q==null||q(K,Q))},[F,c,q]),_=e.useCallback(()=>{z([])},[]),y=e.useCallback(async()=>{if(!g.current||!L.current||!j.current)return;const C=g.current,Q=j.current,K=Q.getContext("2d");if(!K||C.readyState!==C.HAVE_ENOUGH_DATA){M.current=requestAnimationFrame(y);return}Q.width=C.videoWidth,Q.height=C.videoHeight,K.drawImage(C,0,0);try{const J=await L.current.detect(Q);if(J.length>0){const Z=Date.now(),ee=[];for(const te of J)ee.push(te.boundingBox),(te.rawValue!==W.current||Z-X.current>2e3)&&(W.current=te.rawValue,X.current=Z,r(te.rawValue,te.format,te.boundingBox));f.showBoundingBox&&(a(ee),setTimeout(()=>a([]),500))}}catch(J){console.warn("Scan error:",J)}M.current=requestAnimationFrame(y)},[r,f.showBoundingBox]),h=e.useCallback(async()=>{if(!d||!L.current){s("Camera or BarcodeDetector not available"),o==null||o(new Error("Camera or BarcodeDetector not available"));return}try{const C=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:1280},height:{ideal:720}}});B.current=C,g.current&&(g.current.srcObject=C,await g.current.play()),H(!0),s(null),M.current=requestAnimationFrame(y)}catch(C){const Q=C instanceof Error?C.message:"Failed to start camera";s(Q),o==null||o(new Error(Q))}},[d,y,o]),v=e.useCallback(()=>{M.current&&cancelAnimationFrame(M.current),B.current&&(B.current.getTracks().forEach(C=>C.stop()),B.current=null),g.current&&(g.current.srcObject=null),H(!1),a([])},[]);e.useEffect(()=>()=>{v()},[v]);const T=e.useCallback(()=>{E.trim()&&(r(E.trim()),R(""))},[E,r]),w=e.useCallback(()=>{const C=["Value","Format","Quantity","Timestamp"],Q=F.map(K=>[`"${K.value.replace(/"/g,'""')}"`,K.format,K.quantity.toString(),new Date(K.timestamp).toISOString()]);return[C.join(","),...Q.map(K=>K.join(","))].join(`
|
|
7
|
-
`)},[
|
|
8
|
-
<rect width="100%" height="100%" fill="${
|
|
9
|
-
${
|
|
5
|
+
${F}
|
|
6
|
+
</svg>`}catch{return null}},[p,i]),V=e.useCallback(()=>d.current,[]),z=e.useCallback((G="barcode",E="png")=>{const $=document.createElement("a");if(E==="svg"){const R=U();if(!R)return;const k=new Blob([R],{type:"image/svg+xml"});$.href=URL.createObjectURL(k),$.download=`${G}.svg`}else{const R=q();if(!R)return;$.href=R,$.download=`${G}.png`}$.click()},[q,U]),Y=e.useCallback(()=>{A()},[A]);e.useImperativeHandle(f,()=>({toDataURL:q,toSVG:U,getCanvas:V,download:z,regenerate:Y}),[q,U,V,z,Y]);const B=["nice-barcode-generator",T&&"nice-barcode-generator--bordered",L&&"nice-barcode-generator--error",P].filter(Boolean).join(" ");return t.jsxs("div",{className:B,children:[t.jsx("canvas",{ref:d,className:"nice-barcode-generator__canvas"}),t.jsx("svg",{ref:b,style:{display:"none"}}),L&&t.jsx("div",{className:"nice-barcode-generator__error",children:t.jsx("span",{children:L})})]})});et.displayName="NiceBarcodeGenerator";const an={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"},cn=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",on=()=>typeof window<"u"&&"BarcodeDetector"in window,ln=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],un=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),p=n.createGain();f.connect(p),p.connect(n.destination),f.type="sine",f.frequency.value=1e3,p.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},100)}catch{}},dn=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate(50)},tt=e.forwardRef((n,f)=>{const{config:p,onScan:C,onBatchScan:h,onError:N,onCameraReady:T,customScanFrame:P,showScanFrame:i=!0,autoStart:d=!1,children:b,className:L}=n,x={...an,...p},u=e.useRef(null),y=e.useRef(null),A=e.useRef(null),q=e.useRef(null),U=e.useRef(null),V=e.useRef(null),[z,Y]=e.useState(!1),[B,G]=e.useState(!1),[E,$]=e.useState(null),[R,k]=e.useState(null),[S,D]=e.useState(null),[c,s]=e.useState(x.facingMode),[a,r]=e.useState(null),o=on(),l=e.useCallback(async()=>{try{return(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach(X=>X.stop()),D(!0),!0}catch{return D(!1),!1}},[]),j=e.useCallback(async()=>{if(!u.current)return;const M=ln(x.resolution),X={video:{facingMode:c,width:{ideal:M.width},height:{ideal:M.height}},audio:!1};try{const v=await navigator.mediaDevices.getUserMedia(X);A.current=v,u.current.srcObject=v,await u.current.play(),G(!0),D(!0),k(null),T==null||T()}catch(v){const J=v instanceof Error?v.message:"Failed to access camera";k(J),D(!1),N==null||N(new Error(J))}},[x.resolution,c,T,N]),F=e.useCallback(()=>{A.current&&(A.current.getTracks().forEach(M=>M.stop()),A.current=null),u.current&&(u.current.srcObject=null),G(!1)},[]),g=e.useCallback(async()=>{s(c==="user"?"environment":"user"),z&&F()},[c,z,F]),m=e.useCallback(async()=>{if(o)try{const M=window.BarcodeDetector,X=x.formats.map(v=>v.replace("_","-"));q.current=new M({formats:X})}catch(M){const X=M instanceof Error?M.message:"Failed to initialize barcode detector";k(X),N==null||N(new Error(X))}},[o,x.formats,N]),w=e.useCallback(async()=>{if(!(!u.current||!q.current||!B))try{const X=await q.current.detect(u.current);if(X.length>0){const v=X.map(Q=>({rawValue:Q.rawValue,format:cn(Q.format),boundingBox:Q.boundingBox?{x:Q.boundingBox.x,y:Q.boundingBox.y,width:Q.boundingBox.width,height:Q.boundingBox.height}:void 0,cornerPoints:Q.cornerPoints,timestamp:new Date})),J=v[0];if(x.continuous&&J.rawValue===V.current)return;V.current=J.rawValue,x.showBoundingBox&&J.boundingBox&&(r(J.boundingBox),setTimeout(()=>r(null),500)),x.beepOnScan&&un(),x.vibrateOnScan&&dn(),$(J),C==null||C(J),v.length>1&&(h==null||h(v)),setTimeout(()=>{V.current=null},1e3)}}catch{}},[B,x.continuous,x.showBoundingBox,x.beepOnScan,x.vibrateOnScan,C,h]),O=e.useCallback(async()=>{Y(!0),k(null),await m(),await j()},[m,j]),_=e.useCallback(()=>{Y(!1),U.current&&(clearInterval(U.current),U.current=null),F()},[F]),W=e.useCallback(async()=>{z?_():await O()},[z,O,_]),I=e.useCallback(()=>{if(!u.current||!y.current)return null;const M=y.current,X=u.current;M.width=X.videoWidth,M.height=X.videoHeight;const v=M.getContext("2d");return v?(v.drawImage(X,0,0),M.toDataURL("image/png")):null},[]);e.useEffect(()=>(z&&B&&x.continuous&&(U.current=setInterval(w,x.scanInterval)),()=>{U.current&&(clearInterval(U.current),U.current=null)}),[z,B,x.continuous,x.scanInterval,w]),e.useEffect(()=>(d&&O(),()=>{_()}),[]),e.useEffect(()=>{z&&!B&&j()},[c,z,B,j]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:z,isCameraReady:B,lastResult:E,error:R,isSupported:o,hasPermission:S}),start:O,stop:_,toggle:W,takeSnapshot:I,switchCamera:g,requestPermission:l}),[z,B,E,R,o,S,O,_,W,I,g,l]);const H=["nice-barcode-scanner",z&&"nice-barcode-scanner--scanning",B&&"nice-barcode-scanner--ready",R&&"nice-barcode-scanner--error",L].filter(Boolean).join(" ");return t.jsxs("div",{className:H,children:[t.jsx("video",{ref:u,className:"nice-barcode-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:y,className:"nice-barcode-scanner__canvas"}),i&&z&&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"})]}),a&&u.current&&t.jsx("div",{className:"nice-barcode-scanner__bounding-box",style:{left:`${a.x/u.current.videoWidth*100}%`,top:`${a.y/u.current.videoHeight*100}%`,width:`${a.width/u.current.videoWidth*100}%`,height:`${a.height/u.current.videoHeight*100}%`}}),R&&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:R}),t.jsx("button",{className:"nice-barcode-scanner__error-btn",onClick:()=>O(),children:"Try Again"})]}),!o&&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})]})});tt.displayName="NiceBarcodeScanner";const nt=e.createContext(null),fn=()=>{const n=e.useContext(nt);if(!n)throw new Error("useBatchScanner must be used within NiceBatchScannerProvider");return n},mn={autoIncrementDuplicates:!0,maxItems:1e3,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,showBoundingBox:!0,allowManualEntry:!0,minConfidence:0},hn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),p=n.createGain();f.connect(p),p.connect(n.destination),f.frequency.value=1200,f.type="sine",p.gain.setValueAtTime(.3,n.currentTime),p.gain.exponentialRampToValueAtTime(.01,n.currentTime+.1),f.start(),f.stop(n.currentTime+.1)}catch{}},gn=(n=50)=>{"vibrate"in navigator&&navigator.vibrate(n)},pn=()=>`${Date.now()}-${Math.random().toString(36).slice(2,11)}`,st=e.forwardRef((n,f)=>{const{options:p,initialItems:C=[],onScan:h,onRemove:N,onBatchComplete:T,onQuantityChange:P,onError:i,validateScan:d,transformValue:b,className:L,children:x}=n,u={...mn,...p},y=e.useRef(null),A=e.useRef(null),q=e.useRef(null),U=e.useRef(null),V=e.useRef(0),z=e.useRef(""),Y=e.useRef(0),[B,G]=e.useState(C),[E,$]=e.useState(!1),[R,k]=e.useState(!1),[S,D]=e.useState(""),[c,s]=e.useState([]),[a,r]=e.useState(null);e.useEffect(()=>{(async()=>{if("BarcodeDetector"in window)try{const J=await BarcodeDetector.getSupportedFormats();J.length>0&&(U.current=new BarcodeDetector({formats:(p==null?void 0:p.formats)||J}),k(!0))}catch{k(!1)}})()},[p==null?void 0:p.formats]);const o=e.useCallback(async(v,J="unknown",Q)=>{const K=b?b(v,J):v;if(d&&!await d(K,J))return;const Z=B.findIndex(ee=>ee.value===K);if(Z!==-1&&u.autoIncrementDuplicates){const ee=[...B];ee[Z]={...ee[Z],quantity:ee[Z].quantity+1,timestamp:Date.now()},G(ee),P==null||P(ee[Z],ee[Z].quantity)}else if(B.length<u.maxItems){const ee={id:pn(),value:K,format:J,timestamp:Date.now(),rawValue:v,quantity:1,boundingBox:Q};G(te=>[ee,...te]),h==null||h(ee)}u.beepOnScan&&hn(),u.vibrateOnScan&&gn()},[B,u,d,b,h,P]),l=e.useCallback(v=>{const J=B.find(Q=>Q.id===v);J&&(G(Q=>Q.filter(K=>K.id!==v)),N==null||N(J))},[B,N]),j=e.useCallback((v,J)=>{if(J<1){l(v);return}G(K=>K.map(Z=>Z.id===v?{...Z,quantity:J}:Z));const Q=B.find(K=>K.id===v);Q&&(P==null||P(Q,J))},[B,l,P]),F=e.useCallback(()=>{G([])},[]),g=e.useCallback(async()=>{if(!y.current||!U.current||!A.current)return;const v=y.current,J=A.current,Q=J.getContext("2d");if(!Q||v.readyState!==v.HAVE_ENOUGH_DATA){V.current=requestAnimationFrame(g);return}J.width=v.videoWidth,J.height=v.videoHeight,Q.drawImage(v,0,0);try{const K=await U.current.detect(J);if(K.length>0){const Z=Date.now(),ee=[];for(const te of K)ee.push(te.boundingBox),(te.rawValue!==z.current||Z-Y.current>2e3)&&(z.current=te.rawValue,Y.current=Z,o(te.rawValue,te.format,te.boundingBox));u.showBoundingBox&&(s(ee),setTimeout(()=>s([]),500))}}catch(K){console.warn("Scan error:",K)}V.current=requestAnimationFrame(g)},[o,u.showBoundingBox]),m=e.useCallback(async()=>{if(!R||!U.current){r("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}}});q.current=v,y.current&&(y.current.srcObject=v,await y.current.play()),$(!0),r(null),V.current=requestAnimationFrame(g)}catch(v){const J=v instanceof Error?v.message:"Failed to start camera";r(J),i==null||i(new Error(J))}},[R,g,i]),w=e.useCallback(()=>{V.current&&cancelAnimationFrame(V.current),q.current&&(q.current.getTracks().forEach(v=>v.stop()),q.current=null),y.current&&(y.current.srcObject=null),$(!1),s([])},[]);e.useEffect(()=>()=>{w()},[w]);const O=e.useCallback(()=>{S.trim()&&(o(S.trim()),D(""))},[S,o]),_=e.useCallback(()=>{const v=["Value","Format","Quantity","Timestamp"],J=B.map(Q=>[`"${Q.value.replace(/"/g,'""')}"`,Q.format,Q.quantity.toString(),new Date(Q.timestamp).toISOString()]);return[v.join(","),...J.map(Q=>Q.join(","))].join(`
|
|
7
|
+
`)},[B]),W=e.useCallback(()=>JSON.stringify(B,null,2),[B]),I=e.useCallback(()=>{w(),T==null||T(B)},[B,w,T]);e.useImperativeHandle(f,()=>({startScanning:m,stopScanning:w,getItems:()=>B,addItem:(v,J)=>o(v,J),removeItem:l,updateQuantity:j,clearAll:F,exportCSV:_,exportJSON:W,isScanning:()=>E}),[m,w,B,o,l,j,F,_,W,E]);const H={items:B,isScanning:E,addItem:(v,J)=>o(v,J),removeItem:l,updateQuantity:j,clearAll:F,startScanning:m,stopScanning:w},M=B.reduce((v,J)=>v+J.quantity,0),X=["nice-batch-scanner",E&&"nice-batch-scanner--scanning",L].filter(Boolean).join(" ");return t.jsx(nt.Provider,{value:H,children:t.jsxs("div",{className:X,children:[t.jsxs("div",{className:"nice-batch-scanner__scanner",children:[t.jsx("video",{ref:y,className:"nice-batch-scanner__video",playsInline:!0,muted:!0,autoPlay:!0}),t.jsx("canvas",{ref:A,className:"nice-batch-scanner__canvas"}),y.current&&c.map((v,J)=>{const Q=y.current,K=Q.clientWidth/Q.videoWidth,Z=Q.clientHeight/Q.videoHeight;return t.jsx("div",{className:"nice-batch-scanner__bounding-box",style:{left:v.x*K,top:v.y*Z,width:v.width*K,height:v.height*Z}},J)}),E&&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"})]}),a&&t.jsx("div",{className:"nice-batch-scanner__error",children:t.jsx("span",{children:a})}),!E&&!a&&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:"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--${E?"stop":"start"}`,onClick:E?w:m,children:E?"Stop Scanning":"Start Scanning"}),u.allowManualEntry&&t.jsxs("div",{className:"nice-batch-scanner__manual",children:[t.jsx("input",{type:"text",value:S,onChange:v=>D(v.target.value),onKeyDown:v=>v.key==="Enter"&&O(),placeholder:"Enter code manually...",className:"nice-batch-scanner__manual-input"}),t.jsx("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--add",onClick:O,disabled:!S.trim(),children:"Add"})]})]}),t.jsxs("div",{className:"nice-batch-scanner__summary",children:[t.jsxs("span",{className:"nice-batch-scanner__count",children:[t.jsx("strong",{children:B.length})," unique items"]}),t.jsxs("span",{className:"nice-batch-scanner__total",children:[t.jsx("strong",{children:M})," total quantity"]})]}),t.jsxs("div",{className:"nice-batch-scanner__items",children:[B.map(v=>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:v.value}),t.jsx("span",{className:"nice-batch-scanner__item-format",children:v.format})]}),t.jsxs("div",{className:"nice-batch-scanner__item-quantity",children:[t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>j(v.id,v.quantity-1),"aria-label":"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:v.quantity}),t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>j(v.id,v.quantity+1),"aria-label":"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:()=>l(v.id),"aria-label":"Remove item",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]},v.id)),B.length===0&&t.jsx("div",{className:"nice-batch-scanner__empty",children:"No items scanned yet"})]}),B.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:F,children:"Clear All"}),t.jsxs("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--primary",onClick:I,children:["Complete Batch (",M,")"]})]}),x]})})});st.displayName="NiceBatchScanner";const yn=({children:n})=>t.jsx(t.Fragment,{children:n}),bn={errorCorrection:"M",size:200,margin:2,darkColor:"#000000",lightColor:"#ffffff",logoSize:.2,logoMargin:1,cornerRadius:0},wn={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]},vn=(n,f)=>{const p=n.length,C=wn[f];for(let h=0;h<C.length;h++)if(C[h]>=p)return h+1;return 10},Re=(n,f)=>{const p=vn(n,f),C=p*4+17,h=Array(C).fill(null).map(()=>Array(C).fill(!1)),N=Array(C).fill(null).map(()=>Array(C).fill(!1)),T=(d,b)=>{for(let L=-1;L<=7;L++)for(let x=-1;x<=7;x++){const u=d+L,y=b+x;u<0||u>=C||y<0||y>=C||(N[u][y]=!0,L===-1||L===7||x===-1||x===7?h[u][y]=!1:L===0||L===6||x===0||x===6||L>=2&&L<=4&&x>=2&&x<=4?h[u][y]=!0:h[u][y]=!1)}};T(0,0),T(0,C-7),T(C-7,0);for(let d=8;d<C-8;d++)h[6][d]=d%2===0,h[d][6]=d%2===0,N[6][d]=!0,N[d][6]=!0;if(p>=2){const d=[6,C-7];p>=7&&d.splice(1,0,Math.floor(C/2));for(const b of d)for(const L of d)if(!(b<9&&L<9||b<9&&L>C-10||b>C-10&&L<9))for(let x=-2;x<=2;x++)for(let u=-2;u<=2;u++){const y=b+x,A=L+u;y<0||y>=C||A<0||A>=C||(N[y][A]=!0,h[y][A]=x===-2||x===2||u===-2||u===2||x===0&&u===0)}}const P=n.split("").reduce((d,b)=>(d<<5)-d+b.charCodeAt(0),0);let i=0;for(let d=C-1;d>=0;d-=2){d===6&&(d=5);for(let b=0;b<C;b++)for(let L=0;L<=1;L++){const x=d-L;if(N[b][x])continue;const u=i%n.length,y=n.charCodeAt(u)&1<<i%8,A=(P+b*C+x)%256>127;h[b][x]=y!==0!==A,i++}}return h},rt=e.forwardRef((n,f)=>{const{value:p,options:C,onGenerate:h,onError:N,showBorder:T=!1,className:P}=n,i={...bn,...C},d=e.useRef(null),b=e.useRef(null),[L,x]=e.useState(null),[u,y]=e.useState(!(C!=null&&C.logo));e.useEffect(()=>{if(C!=null&&C.logo){const B=new Image;B.crossOrigin="anonymous",B.onload=()=>{b.current=B,y(!0)},B.onerror=()=>{b.current=null,y(!0)},B.src=C.logo}else b.current=null,y(!0)},[C==null?void 0:C.logo]);const A=e.useCallback(()=>{if(!d.current||!p||!u)return;const B=d.current,G=B.getContext("2d");if(G)try{const E=Re(p,i.errorCorrection),$=E.length,R=Math.floor((i.size-i.margin*2)/$),k=$*R+i.margin*2*R;B.width=k,B.height=k,G.fillStyle=i.lightColor,G.fillRect(0,0,k,k),G.fillStyle=i.darkColor;const S=i.margin*R;for(let c=0;c<$;c++)for(let s=0;s<$;s++)if(E[c][s]){const a=S+s*R,r=S+c*R;if(i.cornerRadius>0){const o=Math.min(i.cornerRadius,R/2);G.beginPath(),G.roundRect(a,r,R,R,o),G.fill()}else G.fillRect(a,r,R,R)}if(b.current){const c=k*i.logoSize,s=(k-c)/2,a=(k-c)/2,r=i.logoMargin*R;G.fillStyle=i.lightColor,G.fillRect(s-r,a-r,c+r*2,c+r*2),G.drawImage(b.current,s,a,c,c)}const D=B.toDataURL("image/png");x(null),h==null||h(D)}catch(E){const $=E instanceof Error?E.message:"Failed to generate QR code";x($),N==null||N(new Error($))}},[p,i,u,h,N]);e.useEffect(()=>{A()},[A]);const q=e.useCallback((B="image/png",G=1)=>{var E;return((E=d.current)==null?void 0:E.toDataURL(B,G))||null},[]),U=e.useCallback(()=>{if(!d.current||!p)return null;try{const B=Re(p,i.errorCorrection),G=B.length,E=Math.floor((i.size-i.margin*2)/G),$=G*E+i.margin*2*E,R=i.margin*E,k=[];for(let S=0;S<G;S++)for(let D=0;D<G;D++)if(B[S][D]){const c=R+D*E,s=R+S*E;if(i.cornerRadius>0){const a=Math.min(i.cornerRadius,E/2);k.push(`<rect x="${c}" y="${s}" width="${E}" height="${E}" rx="${a}" fill="${i.darkColor}"/>`)}else k.push(`<rect x="${c}" y="${s}" width="${E}" height="${E}" fill="${i.darkColor}"/>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${$}" height="${$}" viewBox="0 0 ${$} ${$}">
|
|
8
|
+
<rect width="100%" height="100%" fill="${i.lightColor}"/>
|
|
9
|
+
${k.join(`
|
|
10
10
|
`)}
|
|
11
|
-
</svg>`}catch{return null}},[x,o]),M=e.useCallback((F="qrcode",z="png")=>{const P=document.createElement("a");if(z==="svg"){const H=L();if(!H)return;const d=new Blob([H],{type:"image/svg+xml"});P.href=URL.createObjectURL(d),P.download=`${F}.svg`}else{const H=B();if(!H)return;P.href=H,P.download=`${F}.png`}P.click()},[B,L]),W=e.useCallback(()=>{j()},[j]);e.useImperativeHandle(A,()=>({toDataURL:B,toSVG:L,download:M,regenerate:W}),[B,L,M,W]);const X=["nice-qr-generator",O&&"nice-qr-generator--bordered",D&&"nice-qr-generator--error",q].filter(Boolean).join(" ");return t.jsxs("div",{className:X,children:[t.jsx("canvas",{ref:u,className:"nice-qr-generator__canvas",style:{maxWidth:"100%",height:"auto"}}),D&&t.jsx("div",{className:"nice-qr-generator__error",children:t.jsx("span",{children:D})})]})});$e.displayName="NiceQRGenerator";const Ht={continuous:!0,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd",parseDataType:!0,highlightDetected:!0},zt=m=>{var A,x,k;if(/^https?:\/\//i.test(m))return{type:"url",data:{url:m}};if(/^mailto:/i.test(m)){const p=m.match(/^mailto:([^?]+)(?:\?(.*))?$/i);return{type:"email",data:{email:p==null?void 0:p[1],params:p==null?void 0:p[2]}}}if(/^tel:/i.test(m))return{type:"tel",data:{phone:m.replace(/^tel:/i,"")}};if(/^smsto?:/i.test(m)){const p=m.match(/^smsto?:([^:]+)(?::(.*))?$/i);return{type:"sms",data:{phone:p==null?void 0:p[1],message:p==null?void 0:p[2]}}}if(/^geo:/i.test(m)){const p=m.match(/^geo:(-?\d+\.?\d*),(-?\d+\.?\d*)(?:,(-?\d+\.?\d*))?/i);return{type:"geo",data:{latitude:parseFloat((p==null?void 0:p[1])||"0"),longitude:parseFloat((p==null?void 0:p[2])||"0"),altitude:p!=null&&p[3]?parseFloat(p[3]):void 0}}}if(/^BEGIN:VCARD/i.test(m))return{type:"vcard",data:{raw:m}};if(/^BEGIN:VEVENT/i.test(m))return{type:"vevent",data:{raw:m}};if(/^WIFI:/i.test(m)){const p=(A=m.match(/S:([^;]+)/))==null?void 0:A[1],N=(x=m.match(/P:([^;]+)/))==null?void 0:x[1],O=(k=m.match(/T:([^;]+)/))==null?void 0:k[1],q=m.includes("H:true");return{type:"wifi",data:{ssid:p,password:N,type:O,hidden:q}}}return{type:"text"}},Vt=()=>{try{const m=new(window.AudioContext||window.webkitAudioContext),A=m.createOscillator(),x=m.createGain();A.connect(x),x.connect(m.destination),A.type="square",A.frequency.value=1200,x.gain.value=.1,A.start(),setTimeout(()=>{A.stop(),m.close()},80)}catch{}},Wt=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate([50,30,50])},Gt=()=>typeof window<"u"&&"BarcodeDetector"in window,Yt=m=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[m],qe=e.forwardRef((m,A)=>{const{config:x,onScan:k,onError:p,onCameraReady:N,autoStart:O=!1,showScanFrame:q=!0,children:o,className:u}=m,S={...Ht,...x},D=e.useRef(null),b=e.useRef(null),f=e.useRef(null),g=e.useRef(null),j=e.useRef(null),B=e.useRef(null),[L,M]=e.useState(!1),[W,X]=e.useState(!1),[F,z]=e.useState(null),[P,H]=e.useState(null),[d,I]=e.useState(null),[E,R]=e.useState(S.facingMode),[i,a]=e.useState(!1),[n,s]=e.useState(!1),[r,c]=e.useState(null),l=Gt(),_=e.useCallback(async()=>{var Z;if(!D.current)return;const K=Yt(S.resolution),J={video:{facingMode:E,width:{ideal:K.width},height:{ideal:K.height}},audio:!1};try{const ee=await navigator.mediaDevices.getUserMedia(J);f.current=ee,D.current.srcObject=ee,await D.current.play();const te=ee.getVideoTracks()[0],ne=(Z=te.getCapabilities)==null?void 0:Z.call(te);a(!!(ne!=null&&ne.torch)),X(!0),I(!0),H(null),N==null||N()}catch(ee){const te=ee instanceof Error?ee.message:"Failed to access camera";H(te),I(!1),p==null||p(new Error(te))}},[S.resolution,E,N,p]),y=e.useCallback(()=>{f.current&&(f.current.getTracks().forEach(K=>K.stop()),f.current=null),D.current&&(D.current.srcObject=null),X(!1),s(!1)},[]),h=e.useCallback(async()=>{R(E==="user"?"environment":"user"),L&&y()},[E,L,y]),v=e.useCallback(async()=>{if(!f.current||!i)return;const K=f.current.getVideoTracks()[0],J=!n;try{await K.applyConstraints({advanced:[{torch:J}]}),s(J)}catch{}},[i,n]),T=e.useCallback(async()=>{if(l)try{const K=window.BarcodeDetector;g.current=new K({formats:["qr_code"]})}catch(K){const J=K instanceof Error?K.message:"Failed to initialize QR detector";H(J),p==null||p(new Error(J))}},[l,p]),w=e.useCallback((K,J)=>{const Z={text:K,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};if(S.parseDataType){const ee=zt(K);Z.dataType=ee.type,Z.parsedData=ee.data}return Z},[S.parseDataType]),U=e.useCallback(async()=>{if(!(!D.current||!g.current||!W))try{const J=await g.current.detect(D.current);if(J.length>0){const Z=J[0];if(S.continuous&&Z.rawValue===B.current)return;B.current=Z.rawValue;const ee=w(Z.rawValue,Z);S.highlightDetected&&ee.boundingBox&&(c(ee.boundingBox),setTimeout(()=>c(null),500)),S.beepOnScan&&Vt(),S.vibrateOnScan&&Wt(),z(ee),k==null||k(ee),setTimeout(()=>{B.current=null},1e3)}}catch{}},[W,S.continuous,S.highlightDetected,S.beepOnScan,S.vibrateOnScan,w,k]),$=e.useCallback(async()=>{M(!0),H(null),await T(),await _()},[T,_]),G=e.useCallback(()=>{M(!1),j.current&&(clearInterval(j.current),j.current=null),y()},[y]),V=e.useCallback(async()=>{L?G():await $()},[L,$,G]),Y=e.useCallback(()=>{if(!D.current||!b.current)return null;const K=b.current,J=D.current;K.width=J.videoWidth,K.height=J.videoHeight;const Z=K.getContext("2d");return Z?(Z.drawImage(J,0,0),K.toDataURL("image/png")):null},[]),C=e.useCallback(async K=>!l||!g.current?null:new Promise(J=>{const Z=new Image;Z.onload=async()=>{try{const te=await g.current.detect(Z);if(te.length>0){const ne=w(te[0].rawValue,te[0]);J(ne)}else J(null)}catch{J(null)}},Z.onerror=()=>J(null),Z.src=URL.createObjectURL(K)}),[l,w]);e.useEffect(()=>(L&&W&&S.continuous&&(j.current=setInterval(U,S.scanInterval)),()=>{j.current&&(clearInterval(j.current),j.current=null)}),[L,W,S.continuous,S.scanInterval,U]),e.useEffect(()=>(O&&$(),()=>{G()}),[]),e.useEffect(()=>{L&&!W&&_()},[E,L,W,_]),e.useImperativeHandle(A,()=>({getState:()=>({isScanning:L,isCameraReady:W,lastResult:F,error:P,isSupported:l,hasPermission:d,torchAvailable:i,torchOn:n}),start:$,stop:G,toggle:V,switchCamera:h,toggleTorch:v,takeSnapshot:Y,scanImage:C}),[L,W,F,P,l,d,i,n,$,G,V,h,v,Y,C]);const Q=["nice-qr-scanner",L&&"nice-qr-scanner--scanning",W&&"nice-qr-scanner--ready",P&&"nice-qr-scanner--error",u].filter(Boolean).join(" ");return t.jsxs("div",{className:Q,children:[t.jsx("video",{ref:D,className:"nice-qr-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:b,className:"nice-qr-scanner__canvas"}),q&&L&&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"})]}),r&&D.current&&t.jsx("div",{className:"nice-qr-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}%`}}),P&&t.jsxs("div",{className:"nice-qr-scanner__error",children:[t.jsx("div",{className:"nice-qr-scanner__error-icon",children:t.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),t.jsx("p",{className:"nice-qr-scanner__error-text",children:P}),t.jsx("button",{className:"nice-qr-scanner__error-btn",onClick:()=>$(),children:"Try Again"})]}),!l&&t.jsx("div",{className:"nice-qr-scanner__unsupported",children:t.jsx("p",{children:"QR scanning is not supported in this browser."})}),o&&t.jsx("div",{className:"nice-qr-scanner__overlay",children:o})]})});qe.displayName="NiceQRScanner";const Xt=e.createContext(null),se=[{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=(m,A)=>{const x=se.find(O=>O.id===A);if(!x)return{valid:!1,errors:["Unknown symbology"],warnings:[]};const k=[],p=[];if(x.fixedLength){const O=x.hasCheckDigit?x.fixedLength-1:x.fixedLength;m.length!==O&&k.push(`Expected ${O} characters, got ${m.length}`)}else m.length<x.minLength&&k.push(`Minimum ${x.minLength} characters required`),m.length>x.maxLength&&k.push(`Maximum ${x.maxLength} characters allowed`);switch(A){case"ean13":case"ean8":case"ean5":case"ean2":case"upc_a":case"upc_e":case"itf":case"itf14":case"msi":case"pharmacode":/^\d+$/.test(m)||k.push("Only numeric digits allowed");break;case"code128c":/^\d+$/.test(m)||k.push("Only numeric digits allowed"),m.length%2!==0&&p.push("Length should be even for optimal encoding");break;case"code39":case"code93":/^[0-9A-Z\-. $/+%]+$/.test(m.toUpperCase())||k.push("Invalid characters for this symbology");break;case"codabar":/^[0-9\-$:/.+ABCD]+$/.test(m.toUpperCase())||k.push("Invalid characters for Codabar");break;case"plessey":/^[0-9A-F]+$/i.test(m)||k.push("Only hex characters (0-9, A-F) allowed");break}let N;if(x.hasCheckDigit&&k.length===0)switch(A){case"ean13":case"ean8":case"upc_a":case"itf14":{const O=m.split("").map(Number);let q=0;const o=A==="ean13"||A==="upc_a"||A==="itf14";for(let u=0;u<O.length;u++){const S=o?u%2===0?1:3:u%2===0?3:1;q+=O[u]*S}N=String((10-q%10)%10);break}}return A==="itf"&&m.length%2!==0&&k.push("ITF requires even number of digits"),{valid:k.length===0,errors:k,warnings:p,checkDigit:N,formattedValue:N?m+N:m}},Ae={linear:"Linear (1D)","2d":"2D Matrix",postal:"Postal",gs1:"GS1 Standards"},Ue=e.forwardRef((m,A)=>{const{selected:x,onChange:k,category:p="all",multiSelect:N=!0,showDetails:O=!0,showValidation:q=!1,testValue:o="",readOnly:u=!1,className:S}=m,[D,b]=e.useState([]),[f,g]=e.useState(null),j=x??D,B=e.useMemo(()=>p==="all"?se:se.filter(i=>i.category===p),[p]),L=e.useMemo(()=>{const i={};for(const a of B)i[a.category]||(i[a.category]=[]),i[a.category].push(a);return i},[B]),M=e.useCallback(i=>{x||b(i),k==null||k(i)},[x,k]),W=e.useCallback(i=>{N?j.includes(i)||M([...j,i]):M([i])},[j,N,M]),X=e.useCallback(i=>{M(j.filter(a=>a!==i))},[j,M]),F=e.useCallback(i=>{u||(j.includes(i)?X(i):W(i))},[j,u,W,X]),z=e.useCallback(()=>{M(B.map(i=>i.id))},[B,M]),P=e.useCallback(()=>{M([])},[M]),H=e.useCallback(i=>se.find(a=>a.id===i),[]),d=e.useMemo(()=>!q||!o||!f?null:de(o,f),[q,o,f]);e.useImperativeHandle(A,()=>({getSelected:()=>j,select:W,deselect:X,selectAll:z,clearSelection:P,validate:de,getInfo:H,getAll:()=>se}),[j,W,X,z,P,H]);const I=e.useMemo(()=>({symbologies:se,selected:j,validate:de,getInfo:H}),[j,H]),E=f?H(f):null,R=["nice-symbology-config",u&&"nice-symbology-config--readonly",S].filter(Boolean).join(" ");return t.jsx(Xt.Provider,{value:I,children:t.jsxs("div",{className:R,children:[N&&!u&&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:"Select All"}),t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:P,children:"Clear"}),t.jsxs("span",{className:"nice-symbology-config__count",children:[j.length," / ",B.length," selected"]})]}),t.jsxs("div",{className:"nice-symbology-config__content",children:[t.jsx("div",{className:"nice-symbology-config__list",children:Object.entries(L).map(([i,a])=>t.jsxs("div",{className:"nice-symbology-config__group",children:[t.jsx("h3",{className:"nice-symbology-config__group-title",children:Ae[i]||i}),t.jsx("div",{className:"nice-symbology-config__grid",children:a.map(n=>{const s=j.includes(n.id),r=f===n.id;return t.jsxs("div",{className:["nice-symbology-config__item",s&&"nice-symbology-config__item--selected",r&&"nice-symbology-config__item--active"].filter(Boolean).join(" "),onClick:()=>{F(n.id),g(n.id)},role:"option","aria-selected":s,tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),F(n.id),g(n.id))},children:[N&&t.jsx("span",{className:`nice-symbology-config__checkbox ${s?"nice-symbology-config__checkbox--checked":""}`,children:s&&"✓"}),t.jsxs("div",{className:"nice-symbology-config__item-info",children:[t.jsx("span",{className:"nice-symbology-config__item-name",children:n.name}),t.jsx("span",{className:"nice-symbology-config__item-desc",children:n.fixedLength?`${n.fixedLength} digits`:`${n.minLength}-${n.maxLength} chars`})]})]},n.id)})})]},i))}),O&&E&&t.jsxs("div",{className:"nice-symbology-config__details",children:[t.jsx("h3",{className:"nice-symbology-config__details-title",children:E.name}),t.jsx("p",{className:"nice-symbology-config__details-desc",children:E.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:Ae[E.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:E.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:E.fixedLength?`Fixed: ${E.fixedLength}`:`${E.minLength} – ${E.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:E.hasCheckDigit?"Yes":"No"})]}),E.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:E.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:E.useCases.map(i=>t.jsx("span",{className:"nice-symbology-config__tag",children:i},i))})]}),q&&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((i,a)=>t.jsx("div",{className:"nice-symbology-config__validation-error",children:i},a)),d.warnings.map((i,a)=>t.jsx("div",{className:"nice-symbology-config__validation-warning",children:i},a))]})]})]})]})})});Ue.displayName="NiceSymbologyConfig";const Kt=e.createContext(null),Qt={dbName:"nice-background-sync",storeName:"sync-queue",defaultMaxAttempts:5,retryDelay:1e3,backoffFactor:2,maxRetryDelay:6e4,autoSyncOnConnect:!0,periodicSyncInterval:0},Jt=()=>`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Zt=m=>new Promise(A=>setTimeout(A,m)),ye=e.forwardRef((m,A)=>{const{config:x,handlers:k,onSyncStart:p,onSyncComplete:N,onTaskSuccess:O,onTaskFailed:q,onOnlineChange:o,children:u}=m,S={...Qt,...x},D=e.useRef(null),b=e.useRef(!1),[f,g]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,pendingCount:0,failedCount:0,syncProgress:0}),j=e.useCallback(async()=>D.current?D.current:new Promise((s,r)=>{const c=indexedDB.open(S.dbName,1);c.onerror=()=>r(c.error),c.onupgradeneeded=()=>{const l=c.result;if(!l.objectStoreNames.contains(S.storeName)){const _=l.createObjectStore(S.storeName,{keyPath:"id"});_.createIndex("tag","tag",{unique:!1}),_.createIndex("status","status",{unique:!1}),_.createIndex("priority","priority",{unique:!1})}},c.onsuccess=()=>{D.current=c.result,s(c.result)}}),[S.dbName,S.storeName]),B=e.useCallback(async(s,r,c)=>{const l=await j(),_={id:Jt(),tag:s,data:r,status:"pending",createdAt:new Date,attempts:0,maxAttempts:(c==null?void 0:c.maxAttempts)??S.defaultMaxAttempts,priority:(c==null?void 0:c.priority)??0};return new Promise((y,h)=>{const w=l.transaction(S.storeName,"readwrite").objectStore(S.storeName).add(_);w.onerror=()=>h(w.error),w.onsuccess=()=>{g(U=>({...U,pendingCount:U.pendingCount+1})),y(_.id)}})},[j,S.storeName,S.defaultMaxAttempts]),L=e.useCallback(async s=>{const r=await j();return new Promise((c,l)=>{const h=r.transaction(S.storeName,"readwrite").objectStore(S.storeName).delete(s);h.onerror=()=>l(h.error),h.onsuccess=()=>c(!0)})},[j,S.storeName]),M=e.useCallback(async s=>{const r=await j();return new Promise((c,l)=>{const y=r.transaction(S.storeName,"readonly").objectStore(S.storeName),h=s?y.index("tag").getAll(s):y.getAll();h.onerror=()=>l(h.error),h.onsuccess=()=>c(h.result)})},[j,S.storeName]),W=e.useCallback(async s=>(await M(s)).filter(c=>c.status==="pending"),[M]),X=e.useCallback(async s=>(await M(s)).filter(c=>c.status==="failed"),[M]),F=e.useCallback(async s=>{const r=await j();return new Promise((c,l)=>{const h=r.transaction(S.storeName,"readwrite").objectStore(S.storeName).put(s);h.onerror=()=>l(h.error),h.onsuccess=()=>c()})},[j,S.storeName]),z=e.useCallback(async()=>{const s=await M(),r=s.filter(l=>l.status==="pending").length,c=s.filter(l=>l.status==="failed").length;g(l=>({...l,pendingCount:r,failedCount:c}))},[M]),P=e.useCallback(async s=>{const r=k[s.tag];if(!r)return console.warn(`No handler registered for tag: ${s.tag}`),!1;s.status="syncing",s.lastAttemptAt=new Date,s.attempts++,await F(s);try{return await r.handler(s),s.status="success",await F(s),O==null||O(s),await L(s.id),!0}catch(c){const l=c instanceof Error?c.message:"Unknown error";return s.error=l,s.attempts>=s.maxAttempts?(s.status="failed",q==null||q(s,c instanceof Error?c:new Error(l))):s.status="pending",await F(s),!1}},[k,F,L,O,q]),H=e.useCallback(async s=>{if(f.isSyncing)return{success:0,failed:0};b.current=!1,g(c=>({...c,isSyncing:!0,syncProgress:0,error:void 0})),p==null||p();const r={success:0,failed:0};try{const c=await W(s);c.sort((_,y)=>y.priority-_.priority);const l=c.length;for(let _=0;_<c.length&&!b.current;_++){const y=c[_],h=await P(y);if(h?r.success++:y.attempts>=y.maxAttempts&&r.failed++,!h&&y.attempts<y.maxAttempts){const v=Math.min(S.retryDelay*Math.pow(S.backoffFactor,y.attempts-1),S.maxRetryDelay);await Zt(v)}g(v=>({...v,syncProgress:Math.round((_+1)/l*100)}))}}catch(c){const l=c instanceof Error?c.message:"Sync failed";g(_=>({..._,error:l}))}return await z(),g(c=>({...c,isSyncing:!1,lastSyncAt:new Date,syncProgress:100})),N==null||N(r),r},[f.isSyncing,W,P,S.retryDelay,S.backoffFactor,S.maxRetryDelay,z,p,N]),d=e.useCallback(()=>{b.current=!0},[]),I=e.useCallback(async s=>{const c=(await M()).find(l=>l.id===s);c&&c.status==="failed"&&(c.status="pending",c.attempts=0,c.error=void 0,await F(c),await z())},[M,F,z]),E=e.useCallback(async s=>{const r=await X(s);for(const c of r)c.status="pending",c.attempts=0,c.error=void 0,await F(c);await z()},[X,F,z]),R=e.useCallback(async s=>{const r=await j(),c=await M(s);return new Promise((l,_)=>{const y=r.transaction(S.storeName,"readwrite"),h=y.objectStore(S.storeName);y.onerror=()=>_(y.error),y.oncomplete=async()=>{await z(),l()};for(const v of c)h.delete(v.id)})},[j,M,S.storeName,z]),i=e.useCallback(async s=>{const r=await j(),c=await X(s);return new Promise((l,_)=>{const y=r.transaction(S.storeName,"readwrite"),h=y.objectStore(S.storeName);y.onerror=()=>_(y.error),y.oncomplete=async()=>{await z(),l()};for(const v of c)h.delete(v.id)})},[j,X,S.storeName,z]),a=e.useCallback(async s=>{if(!("serviceWorker"in navigator))return!1;try{const r=await navigator.serviceWorker.ready;if("sync"in r)return await r.sync.register(s),!0}catch(r){console.warn("Background Sync registration failed:",r)}return!1},[]);e.useEffect(()=>{const s=()=>{g(c=>({...c,isOnline:!0})),o==null||o(!0),S.autoSyncOnConnect&&H()},r=()=>{g(c=>({...c,isOnline:!1})),o==null||o(!1)};return window.addEventListener("online",s),window.addEventListener("offline",r),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",r)}},[S.autoSyncOnConnect,H,o]),e.useEffect(()=>{if(S.periodicSyncInterval<=0)return;const s=setInterval(()=>{f.isOnline&&!f.isSyncing&&H()},S.periodicSyncInterval);return()=>clearInterval(s)},[S.periodicSyncInterval,f.isOnline,f.isSyncing,H]),e.useEffect(()=>{z()},[z]),e.useImperativeHandle(A,()=>({getState:()=>f,addTask:B,removeTask:L,getTasks:M,getPendingTasks:W,getFailedTasks:X,retryTask:I,retryAllFailed:E,clearTasks:R,clearFailed:i,syncNow:H,cancelSync:d,registerBackgroundSync:a}),[f,B,L,M,W,X,I,E,R,i,H,d,a]);const n={...f,addTask:B,removeTask:L,getTasks:M,getPendingTasks:W,getFailedTasks:X,retryTask:I,retryAllFailed:E,clearTasks:R,clearFailed:i,syncNow:H,cancelSync:d};return t.jsx(Kt.Provider,{value:n,children:u})});ye.displayName="NiceBackgroundSync";const en=ye;en.displayName="NiceBackgroundSyncProvider";const tn=e.createContext(null),nn={cacheName:"nice-cache-strategies",defaultTTL:300*1e3,maxEntries:500,defaultStrategy:"stale-while-revalidate",networkTimeout:5e3,serveStale:!0,staleThreshold:60*1e3};class sn{constructor(){ae(this,"dbName","nice-cache-db");ae(this,"storeName","cache-entries");ae(this,"db",null)}async init(){if(!this.db)return new Promise((A,x)=>{const k=indexedDB.open(this.dbName,1);k.onerror=()=>x(k.error),k.onupgradeneeded=()=>{const p=k.result;p.objectStoreNames.contains(this.storeName)||p.createObjectStore(this.storeName,{keyPath:"key"})},k.onsuccess=()=>{this.db=k.result,A()}})}async get(A){if(await this.init(),!!this.db)return new Promise((x,k)=>{const O=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(A);O.onerror=()=>k(O.error),O.onsuccess=()=>{const q=O.result;x(q?q.value:void 0)}})}async set(A,x){if(await this.init(),!!this.db)return new Promise((k,p)=>{const q=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:A,value:x});q.onerror=()=>p(q.error),q.onsuccess=()=>k()})}async delete(A){return await this.init(),this.db?new Promise((x,k)=>{const O=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(A);O.onerror=()=>k(O.error),O.onsuccess=()=>x(!0)}):!1}async keys(){return await this.init(),this.db?new Promise((A,x)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();N.onerror=()=>x(N.error),N.onsuccess=()=>A(N.result)}):[]}async clear(){if(await this.init(),!!this.db)return new Promise((A,x)=>{const N=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();N.onerror=()=>x(N.error),N.onsuccess=()=>A()})}async getAll(){return await this.init(),this.db?new Promise((A,x)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();N.onerror=()=>x(N.error),N.onsuccess=()=>A(N.result)}):[]}}const be=e.forwardRef((m,A)=>{const{config:x,routeStrategies:k={},precacheUrls:p=[],onFetch:N,onCacheHit:O,onCacheMiss:q,onNetworkError:o,children:u}=m,S={...nn,...x},D=e.useRef(new sn),[b,f]=e.useState({isFetching:!1,totalSize:0,entryCount:0,hits:0,misses:0,strategy:S.defaultStrategy}),g=e.useCallback(i=>{for(const[a,n]of Object.entries(k))if(new RegExp(a).test(i))return n;return b.strategy},[k,b.strategy]),j=e.useCallback(i=>{f(a=>({...a,strategy:i}))},[]),B=e.useCallback(async i=>{const a=await D.current.get(i);if(!a)return;const n=Date.now(),s=a.expiresAt&&a.expiresAt<n,r=a.timestamp+S.staleThreshold<n;if(s&&!S.serveStale){await D.current.delete(i);return}return{data:a.data,timestamp:new Date(a.timestamp),expiresAt:a.expiresAt?new Date(a.expiresAt):void 0,etag:a.etag,key:i,isStale:r||!!s,source:"cache",url:a.url}},[S.staleThreshold,S.serveStale]),L=e.useCallback(async(i,a,n)=>{const s=Date.now(),r={data:a,timestamp:s,expiresAt:n?s+n:s+S.defaultTTL};await D.current.set(i,r);const c=await D.current.keys();if(f(l=>({...l,entryCount:c.length})),c.length>S.maxEntries){const l=await D.current.getAll();l.sort((y,h)=>y.value.timestamp-h.value.timestamp);const _=l.slice(0,l.length-S.maxEntries);for(const y of _)await D.current.delete(y.key)}},[S.defaultTTL,S.maxEntries]),M=e.useCallback(async i=>{const a=await D.current.delete(i),n=await D.current.keys();return f(s=>({...s,entryCount:n.length})),a},[]),W=e.useCallback(async()=>{await D.current.clear(),f(i=>({...i,entryCount:0,totalSize:0}))},[]),X=e.useCallback(async()=>D.current.keys(),[]),F=e.useCallback(async i=>await B(i)!==void 0,[B]),z=e.useCallback(async i=>{const a=await D.current.keys();let n=0;for(const r of a)i.test(r)&&(await D.current.delete(r),n++);const s=await D.current.keys();return f(r=>({...r,entryCount:s.length})),n},[]),P=e.useCallback(async(i,a,n)=>{const s=new AbortController,r=setTimeout(()=>s.abort(),n);try{const c=await fetch(i,{...a,signal:s.signal});return clearTimeout(r),c}catch(c){throw clearTimeout(r),c}},[]),H=e.useCallback(async(i,a={})=>{const{strategy:n=g(i),ttl:s,cacheKey:r=i,forceRefresh:c=!1,timeout:l=S.networkTimeout,..._}=a;f(h=>({...h,isFetching:!0}));const y=async()=>{try{const h=await P(i,_,l);if(!h.ok)throw new Error(`HTTP ${h.status}`);const v=await h.json(),T=h.headers.get("etag")||void 0;await L(r,v,s);const w={data:v,timestamp:new Date,etag:T,key:r,isStale:!1,source:"network",url:i};return f(U=>({...U,isFetching:!1})),N==null||N(w),w}catch(h){throw o==null||o(h instanceof Error?h:new Error(String(h)),i),h}};try{switch(n){case"cache-only":{const h=await B(r);if(h)return f(v=>({...v,isFetching:!1,hits:v.hits+1})),O==null||O(h),h;throw f(v=>({...v,isFetching:!1,misses:v.misses+1})),q==null||q(i),new Error("No cache entry found")}case"network-only":return f(h=>({...h,misses:h.misses+1})),await y();case"cache-first":{if(!c){const h=await B(r);if(h&&!h.isStale)return f(v=>({...v,isFetching:!1,hits:v.hits+1})),O==null||O(h),h}return f(h=>({...h,misses:h.misses+1})),await y()}case"network-first":try{return f(h=>({...h,misses:h.misses+1})),await y()}catch(h){const v=await B(r);if(v)return f(T=>({...T,isFetching:!1,hits:T.hits+1})),O==null||O(v),v;throw h}case"stale-while-revalidate":default:{const h=await B(r);return h&&!c?(f(v=>({...v,hits:v.hits+1})),O==null||O(h),h.isStale&&y().catch(()=>{}),f(v=>({...v,isFetching:!1})),h):(f(v=>({...v,misses:v.misses+1})),await y())}}}catch(h){throw f(v=>({...v,isFetching:!1})),h}},[g,S.networkTimeout,P,B,L,N,O,q,o]),d=e.useCallback(async(i,a)=>(await H(i,a)).data,[H]),I=e.useCallback(async(i,a)=>{await Promise.all(i.map(n=>H(n,{...a,strategy:"network-first"}).catch(()=>{})))},[H]),E=e.useCallback(async()=>{const i=await D.current.getAll();let a=0,n,s;for(const r of i){const c=JSON.stringify(r.value.data).length;a+=c,(!n||r.value.timestamp<n)&&(n=r.value.timestamp),(!s||r.value.timestamp>s)&&(s=r.value.timestamp)}return{size:a,entryCount:i.length,oldestEntry:n?new Date(n):void 0,newestEntry:s?new Date(s):void 0}},[]);e.useEffect(()=>{p.length>0&&I(p)},[p,I]),e.useEffect(()=>{(async()=>{await D.current.init();const a=await E();f(n=>({...n,totalSize:a.size,entryCount:a.entryCount}))})()},[E]),e.useImperativeHandle(A,()=>({getState:()=>b,fetch:H,fetchJSON:d,getFromCache:B,addToCache:L,removeFromCache:M,clearCache:W,getCacheKeys:X,getCacheStats:E,prefetch:I,isCached:F,invalidateByPattern:z,setStrategy:j,getStrategyForUrl:g}),[b,H,d,B,L,M,W,X,E,I,F,z,j,g]);const R={...b,fetch:H,fetchJSON:d,getFromCache:B,addToCache:L,removeFromCache:M,clearCache:W,getCacheKeys:X,prefetch:I,isCached:F,setStrategy:j,getStrategyForUrl:g};return t.jsx(tn.Provider,{value:R,children:u})});be.displayName="NiceCacheStrategies";const rn=be;rn.displayName="NiceCacheStrategiesProvider";const an=e.createContext(null),cn={defaultStrategy:"manual",autoResolve:!1,maxPendingConflicts:100,persistConflicts:!0,storageKey:"nice-conflict-resolution"},on=()=>`conflict-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ln=m=>JSON.stringify(m),dn=(m,A)=>JSON.stringify(m)===JSON.stringify(A),un=(m,A,x)=>({...m,...A}),we=e.forwardRef((m,A)=>{const{config:x,handlers:k={},showConflictUI:p=!0,uiPosition:N="modal",autoOpenUI:O=!0,onConflictDetected:q,onConflictResolved:o,onResolutionFailed:u,renderConflictList:S,renderConflictItem:D,children:b}=m,f={...cn,...x},[g,j]=e.useState([]),[B,L]=e.useState(!1),[M,W]=e.useState(!1),X=e.useCallback($=>k[$]||{},[k]),F=e.useCallback($=>({pending:$.filter(G=>G.status==="pending").length,resolving:$.filter(G=>G.status==="resolving").length,resolved:$.filter(G=>G.status==="resolved").length,failed:$.filter(G=>G.status==="failed").length}),[]),z={conflicts:g,isResolving:B,counts:F(g)},P=e.useCallback(()=>{if(f.persistConflicts)try{const $=localStorage.getItem(f.storageKey);if($){const V=JSON.parse($).map(Y=>({...Y,createdAt:new Date(Y.createdAt),resolvedAt:Y.resolvedAt?new Date(Y.resolvedAt):void 0,clientVersion:{...Y.clientVersion,timestamp:new Date(Y.clientVersion.timestamp)},serverVersion:{...Y.serverVersion,timestamp:new Date(Y.serverVersion.timestamp)},baseVersion:Y.baseVersion?{...Y.baseVersion,timestamp:new Date(Y.baseVersion.timestamp)}:void 0}));j(V)}}catch($){console.warn("Failed to load persisted conflicts:",$)}},[f.persistConflicts,f.storageKey]),H=e.useCallback($=>{if(f.persistConflicts)try{const G=$.filter(V=>V.status==="pending"||V.status==="failed");localStorage.setItem(f.storageKey,JSON.stringify(G))}catch(G){console.warn("Failed to persist conflicts:",G)}},[f.persistConflicts,f.storageKey]);e.useEffect(()=>{P()},[P]),e.useEffect(()=>{H(g)},[g,H]);const d=e.useCallback(($,G,V,Y,C)=>{const Q=X($),K=Q.compare||dn,J=Q.hash||ln,Z=Q.getConflictingFields;if(K(V.data,Y.data)||V.timestamp<Y.timestamp&&C&&K(V.data,C.data))return null;const ee={id:on(),entityType:$,entityId:G,clientVersion:{...V,hash:J(V.data)},serverVersion:{...Y,hash:J(Y.data)},baseVersion:C?{...C,hash:J(C.data)}:void 0,status:"pending",createdAt:new Date,conflictingFields:Z?Z(V.data,Y.data):void 0};return I(ee),ee},[X]),I=e.useCallback($=>{j(G=>{const V=G.findIndex(C=>C.entityType===$.entityType&&C.entityId===$.entityId);let Y;return V>=0?(Y=[...G],Y[V]=$):Y=[...G,$],Y.length>f.maxPendingConflicts&&(Y=Y.slice(-f.maxPendingConflicts)),Y}),q==null||q($),O&&p&&W(!0),f.autoResolve&&f.defaultStrategy!=="manual"&&E($.id,f.defaultStrategy)},[f.maxPendingConflicts,f.autoResolve,f.defaultStrategy,O,p,q]),E=e.useCallback(async($,G,V)=>{var K;const Y=g.findIndex(J=>J.id===$);if(Y===-1)return;const C=g[Y],Q=X(C.entityType);L(!0),j(J=>{const Z=[...J];return Z[Y]={...C,status:"resolving"},Z});try{let J;switch(G){case"client-wins":J=C.clientVersion.data;break;case"server-wins":J=C.serverVersion.data;break;case"latest-wins":J=C.clientVersion.timestamp>C.serverVersion.timestamp?C.clientVersion.data:C.serverVersion.data;break;case"merge":{J=await(Q.merge||un)(C.clientVersion.data,C.serverVersion.data,(K=C.baseVersion)==null?void 0:K.data);break}case"manual":if(V===void 0)throw new Error("Manual resolution requires merged data");J=V;break}const Z={...C,status:"resolved",resolvedVersion:{data:J,timestamp:new Date,source:G==="client-wins"?"client":"server"},resolvedWith:G,resolvedAt:new Date};j(ee=>{const te=[...ee];return te[Y]=Z,te}),o==null||o(Z)}catch(J){const Z=J instanceof Error?J.message:"Resolution failed";j(ee=>{const te=[...ee];return te[Y]={...C,status:"failed",error:Z},te}),u==null||u(C,J instanceof Error?J:new Error(Z))}finally{L(!1)}},[g,X,o,u]),R=e.useCallback(async $=>{const G=g.filter(V=>V.status==="pending");for(const V of G)await E(V.id,$)},[g,E]),i=e.useCallback($=>g.find(G=>G.id===$),[g]),a=e.useCallback(($,G)=>g.filter(V=>V.entityType===$&&(G===void 0||V.entityId===G)),[g]),n=e.useCallback(()=>g.filter($=>$.status==="pending"),[g]),s=e.useCallback($=>{j(G=>G.filter(V=>V.id!==$))},[]),r=e.useCallback(()=>{j($=>$.filter(G=>G.status!=="resolved"))},[]),c=e.useCallback(()=>{j([])},[]),l=e.useCallback(()=>W(!0),[]),_=e.useCallback(()=>W(!1),[]);e.useImperativeHandle(A,()=>({getState:()=>z,detectConflict:d,addConflict:I,resolveConflict:E,resolveAll:R,getConflict:i,getConflictsByEntity:a,getPendingConflicts:n,dismissConflict:s,clearResolved:r,clearAll:c,openUI:l,closeUI:_}),[z,d,I,E,R,i,a,n,s,r,c,l,_]);const y={...z,detectConflict:d,addConflict:I,resolveConflict:E,resolveAll:R,getConflict:i,getConflictsByEntity:a,getPendingConflicts:n,dismissConflict:s,clearResolved:r,clearAll:c},h=n(),v=($,G,V)=>{E($,G,V)},T=$=>{s($)},w=$=>D?D({conflict:$,onResolve:(G,V)=>v($.id,G,V),onDismiss:()=>T($.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(G=>t.jsx("code",{children:G},G))]}),t.jsxs("div",{className:"nice-conflict-item__actions",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>v($.id,"client-wins"),disabled:B,children:"Keep Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>v($.id,"server-wins"),disabled:B,children:"Use Server"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--merge",onClick:()=>v($.id,"merge"),disabled:B,children:"Merge"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--dismiss",onClick:()=>T($.id),disabled:B,children:"Dismiss"})]})]},$.id),U=()=>{if(!p||!M||h.length===0)return null;if(S)return S({conflicts:h,onResolve:v,onDismiss:T});const $=t.jsxs("div",{className:"nice-conflict-list",children:[t.jsxs("div",{className:"nice-conflict-list__header",children:[t.jsxs("h3",{children:["Sync Conflicts (",h.length,")"]}),t.jsx("button",{className:"nice-conflict-list__close",onClick:_,children:"✕"})]}),t.jsx("div",{className:"nice-conflict-list__items",children:h.map(w)}),h.length>1&&t.jsxs("div",{className:"nice-conflict-list__bulk",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>R("client-wins"),disabled:B,children:"Keep All Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>R("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(an.Provider,{value:y,children:[b,U()]})});we.displayName="NiceConflictResolution";const fn=we;fn.displayName="NiceConflictResolutionProvider";const mn=e.createContext(null),ve=e.forwardRef((m,A)=>{const{config:x,autoOpen:k=!0,onOpen:p,onError:N,onClose:O,children:q}=m,o=e.useRef(null),[u,S]=e.useState({isOpen:!1,isLoading:!1,storeNames:[]}),D=e.useCallback(async()=>{if(o.current)return o.current;if(!("indexedDB"in window))throw new Error("IndexedDB is not supported in this browser");return S(a=>({...a,isLoading:!0,error:void 0})),new Promise((a,n)=>{const s=indexedDB.open(x.dbName,x.version);s.onerror=()=>{var c;const r=new Error(((c=s.error)==null?void 0:c.message)||"Failed to open database");S(l=>({...l,isLoading:!1,error:r.message})),N==null||N(r),n(r)},s.onblocked=()=>{var r;(r=x.onBlocked)==null||r.call(x)},s.onupgradeneeded=r=>{var y;const c=s.result,l=r.oldVersion,_=r.newVersion;for(const h of x.stores)if(!c.objectStoreNames.contains(h.name)){const v=c.createObjectStore(h.name,{keyPath:h.keyPath,autoIncrement:h.autoIncrement});if(h.indexes)for(const T of h.indexes)v.createIndex(T.name,T.keyPath,T.options)}(y=x.onUpgrade)==null||y.call(x,c,l,_)},s.onsuccess=()=>{const r=s.result;o.current=r,r.onclose=()=>{o.current=null,S(c=>({...c,isOpen:!1,db:void 0})),O==null||O()},r.onerror=c=>{var _;const l=c.target;N==null||N(new Error(((_=l.error)==null?void 0:_.message)||"Database error"))},S({db:r,isOpen:!0,isLoading:!1,version:r.version,storeNames:Array.from(r.objectStoreNames)}),p==null||p(r),a(r)}})},[x,p,N,O]),b=e.useCallback(()=>{o.current&&(o.current.close(),o.current=null,S(a=>({...a,isOpen:!1,db:void 0})),O==null||O())},[O]),f=e.useCallback(async()=>(b(),new Promise((a,n)=>{const s=indexedDB.deleteDatabase(x.dbName);s.onerror=()=>{var r;n(new Error(((r=s.error)==null?void 0:r.message)||"Failed to delete database"))},s.onsuccess=()=>{S({isOpen:!1,isLoading:!1,storeNames:[]}),a()}})),[x.dbName,b]),g=e.useCallback(async()=>o.current?o.current:D(),[D]),j=e.useCallback(async(a,n)=>{const s=await g();return new Promise((r,c)=>{const y=s.transaction(a,"readonly").objectStore(a).get(n);y.onerror=()=>{var h;return c(new Error((h=y.error)==null?void 0:h.message))},y.onsuccess=()=>r(y.result)})},[g]),B=e.useCallback(async(a,n)=>{const s=await g();return new Promise((r,c)=>{const _=s.transaction(a,"readonly").objectStore(a),h=(n!=null&&n.index?_.index(n.index):_).getAll(n==null?void 0:n.range,n==null?void 0:n.limit);h.onerror=()=>{var v;return c(new Error((v=h.error)==null?void 0:v.message))},h.onsuccess=()=>{let v=h.result;n!=null&&n.offset&&(v=v.slice(n.offset)),r(v)}})},[g]),L=e.useCallback(async(a,n)=>{const s=await g();return new Promise((r,c)=>{const _=s.transaction(a,"readonly").objectStore(a),h=(n!=null&&n.index?_.index(n.index):_).getAllKeys(n==null?void 0:n.range,n==null?void 0:n.limit);h.onerror=()=>{var v;return c(new Error((v=h.error)==null?void 0:v.message))},h.onsuccess=()=>r(h.result)})},[g]),M=e.useCallback(async(a,n,s)=>{const r=await g();return new Promise((c,l)=>{const h=r.transaction(a,"readwrite").objectStore(a).add(n,s);h.onerror=()=>{var v;return l(new Error((v=h.error)==null?void 0:v.message))},h.onsuccess=()=>c(h.result)})},[g]),W=e.useCallback(async(a,n,s)=>{const r=await g();return new Promise((c,l)=>{const h=r.transaction(a,"readwrite").objectStore(a).put(n,s);h.onerror=()=>{var v;return l(new Error((v=h.error)==null?void 0:v.message))},h.onsuccess=()=>c(h.result)})},[g]),X=e.useCallback(async(a,n)=>{const s=await g();return new Promise((r,c)=>{const y=s.transaction(a,"readwrite").objectStore(a).delete(n);y.onerror=()=>{var h;return c(new Error((h=y.error)==null?void 0:h.message))},y.onsuccess=()=>r()})},[g]),F=e.useCallback(async a=>{const n=await g();return new Promise((s,r)=>{const _=n.transaction(a,"readwrite").objectStore(a).clear();_.onerror=()=>{var y;return r(new Error((y=_.error)==null?void 0:y.message))},_.onsuccess=()=>s()})},[g]),z=e.useCallback(async(a,n)=>{const s=await g();return new Promise((r,c)=>{const y=s.transaction(a,"readonly").objectStore(a).count(n);y.onerror=()=>{var h;return c(new Error((h=y.error)==null?void 0:h.message))},y.onsuccess=()=>r(y.result)})},[g]),P=e.useCallback(async(a,n)=>{const s=await g(),r=[];return new Promise((c,l)=>{const y=s.transaction(a,"readonly").objectStore(a),v=(n.index?y.index(n.index):y).openCursor(n.range,n.direction);let T=0,w=0;v.onerror=()=>{var U;return l(new Error((U=v.error)==null?void 0:U.message))},v.onsuccess=()=>{const U=v.result;if(U){if(n.offset&&T<n.offset){T++,U.continue();return}if(n.limit&&w>=n.limit){c(r);return}r.push(U.value),w++,U.continue()}else c(r)}})},[g]),H=e.useCallback(async(a,n)=>{const r=(await g()).transaction(a.stores,a.mode||"readwrite");return new Promise((c,l)=>{r.onerror=()=>{var _;return l(new Error((_=r.error)==null?void 0:_.message))},r.onabort=()=>l(new Error("Transaction aborted")),n(r).then(_=>{r.oncomplete=()=>c(_)}).catch(l)})},[g]),d=e.useCallback(async(a,n)=>{const s=await g(),r=[];return new Promise((c,l)=>{const _=s.transaction(a,"readwrite"),y=_.objectStore(a);_.onerror=()=>{var h;return l(new Error((h=_.error)==null?void 0:h.message))},_.oncomplete=()=>c(r);for(const h of n){const v=y.add(h);v.onsuccess=()=>r.push(v.result)}})},[g]),I=e.useCallback(async(a,n)=>{const s=await g(),r=[];return new Promise((c,l)=>{const _=s.transaction(a,"readwrite"),y=_.objectStore(a);_.onerror=()=>{var h;return l(new Error((h=_.error)==null?void 0:h.message))},_.oncomplete=()=>c(r);for(const h of n){const v=y.put(h);v.onsuccess=()=>r.push(v.result)}})},[g]),E=e.useCallback(async(a,n)=>{const s=await g();return new Promise((r,c)=>{const l=s.transaction(a,"readwrite"),_=l.objectStore(a);l.onerror=()=>{var y;return c(new Error((y=l.error)==null?void 0:y.message))},l.oncomplete=()=>r();for(const y of n)_.delete(y)})},[g]),R=e.useCallback(async()=>{const a=await g(),n=[];for(const s of a.objectStoreNames){const c=a.transaction(s,"readonly").objectStore(s);n.push({name:c.name,keyPath:c.keyPath,autoIncrement:c.autoIncrement,indexNames:Array.from(c.indexNames)})}return{name:a.name,version:a.version,stores:n}},[g]);e.useEffect(()=>(k&&D().catch(()=>{}),()=>{b()}),[k,D,b]),e.useImperativeHandle(A,()=>({getState:()=>u,open:D,close:b,deleteDatabase:f,get:j,getAll:B,getAllKeys:L,add:M,put:W,delete:X,clear:F,count:z,query:P,transaction:H,bulkAdd:d,bulkPut:I,bulkDelete:E,getInfo:R}),[u,D,b,f,j,B,L,M,W,X,F,z,P,H,d,I,E,R]);const i={...u,open:D,close:b,deleteDatabase:f,get:j,getAll:B,getAllKeys:L,add:M,put:W,delete:X,clear:F,count:z,query:P,transaction:H,bulkAdd:d,bulkPut:I,bulkDelete:E};return t.jsx(mn.Provider,{value:i,children:q})});ve.displayName="NiceIndexedDB";const hn=ve;hn.displayName="NiceIndexedDBProvider";const gn=e.createContext(null),pn={dbName:"nice-offline-forms",autoSaveInterval:5e3,maxDraftsPerForm:50,autoSubmitOnline:!0,retryFailed:!0,maxRetryAttempts:3,retryDelay:5e3},yn=()=>`draft-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,xe=e.forwardRef((m,A)=>{const{config:x,submitHandlers:k={},onDraftSaved:p,onFormSubmitted:N,onSubmissionFailed:O,onSyncComplete:q,children:o}=m,u={...pn,...x},S=e.useRef(null),D=e.useRef(k),[b,f]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,draftCounts:{},pendingCount:0,failedCount:0}),g=e.useCallback(async()=>S.current?S.current:new Promise((a,n)=>{const s=indexedDB.open(u.dbName,1);s.onerror=()=>n(s.error),s.onupgradeneeded=()=>{const r=s.result;if(!r.objectStoreNames.contains("drafts")){const c=r.createObjectStore("drafts",{keyPath:"id"});c.createIndex("formId","formId",{unique:!1}),c.createIndex("status","status",{unique:!1})}},s.onsuccess=()=>{S.current=s.result,a(s.result)}}),[u.dbName]),j=e.useCallback(async(a,n,s)=>{const r=await g(),c={id:yn(),formId:a,data:n,status:"draft",createdAt:new Date,modifiedAt:new Date,attempts:0,version:1,submittedOffline:!1,metadata:s};return new Promise((l,_)=>{const v=r.transaction("drafts","readwrite").objectStore("drafts").add(c);v.onerror=()=>_(v.error),v.onsuccess=()=>{p==null||p(c),R(),l(c.id)}})},[g,p]),B=e.useCallback(async a=>{const n=await g();return new Promise((s,r)=>{const _=n.transaction("drafts","readonly").objectStore("drafts").get(a);_.onerror=()=>r(_.error),_.onsuccess=()=>{const y=_.result;y&&(y.createdAt=new Date(y.createdAt),y.modifiedAt=new Date(y.modifiedAt),y.syncedAt&&(y.syncedAt=new Date(y.syncedAt))),s(y)}})},[g]),L=e.useCallback(async a=>{const n=await g();return new Promise((s,r)=>{const y=n.transaction("drafts","readonly").objectStore("drafts").index("formId").getAll(a);y.onerror=()=>r(y.error),y.onsuccess=()=>{const h=y.result.map(v=>({...v,createdAt:new Date(v.createdAt),modifiedAt:new Date(v.modifiedAt),syncedAt:v.syncedAt?new Date(v.syncedAt):void 0}));s(h)}})},[g]),M=e.useCallback(async()=>{const a=await g();return new Promise((n,s)=>{const l=a.transaction("drafts","readonly").objectStore("drafts").getAll();l.onerror=()=>s(l.error),l.onsuccess=()=>{const _=l.result.filter(y=>y.status==="pending"||y.status==="failed").map(y=>({...y,createdAt:new Date(y.createdAt),modifiedAt:new Date(y.modifiedAt),syncedAt:y.syncedAt?new Date(y.syncedAt):void 0}));n(_)}})},[g]),W=e.useCallback(async(a,n)=>{const s=await B(a);if(!s)return;const r=await g(),c={...s,data:{...s.data,...n},modifiedAt:new Date,version:s.version+1};return new Promise((l,_)=>{const v=r.transaction("drafts","readwrite").objectStore("drafts").put(c);v.onerror=()=>_(v.error),v.onsuccess=()=>{p==null||p(c),l()}})},[g,B,p]),X=e.useCallback(async(a,n,s)=>{const r=await B(a);if(!r)return;const c=await g(),l={...r,status:n,error:s,attempts:n==="syncing"?r.attempts+1:r.attempts,syncedAt:n==="synced"?new Date:r.syncedAt};return new Promise((_,y)=>{const T=c.transaction("drafts","readwrite").objectStore("drafts").put(l);T.onerror=()=>y(T.error),T.onsuccess=()=>{R(),_()}})},[g,B]),F=e.useCallback(async a=>{const n=await g();return new Promise((s,r)=>{const _=n.transaction("drafts","readwrite").objectStore("drafts").delete(a);_.onerror=()=>r(_.error),_.onsuccess=()=>{R(),s()}})},[g]),z=e.useCallback(async a=>{const n=await L(a),s=await g();return new Promise((r,c)=>{const l=s.transaction("drafts","readwrite"),_=l.objectStore("drafts");l.onerror=()=>c(l.error),l.oncomplete=()=>{R(),r()};for(const y of n)_.delete(y.id)})},[g,L]),P=e.useCallback(async a=>{const n=await B(a);if(!n)throw new Error("Draft not found");const s=D.current[n.formId];if(!s)throw new Error(`No handler registered for form: ${n.formId}`);if(!b.isOnline){await X(a,"pending");return}await X(a,"syncing"),f(r=>({...r,isSyncing:!0}));try{await s(n.data,n),await X(a,"synced"),N==null||N(n),await F(a)}catch(r){const c=r instanceof Error?r.message:"Submission failed";await X(a,"failed",c),O==null||O(n,r instanceof Error?r:new Error(c))}finally{f(r=>({...r,isSyncing:!1}))}},[B,b.isOnline,X,F,N,O]),H=e.useCallback(async(a,n)=>{const s=await j(a,n);await X(s,"pending"),await P(s)},[j,X,P]),d=e.useCallback(async()=>{const a=await M(),n={synced:0,failed:0};f(s=>({...s,isSyncing:!0}));for(const s of a)if(!(s.status==="failed"&&s.attempts>=u.maxRetryAttempts))try{await P(s.id),n.synced++}catch{n.failed++}return f(s=>({...s,isSyncing:!1,lastSyncAt:new Date})),q==null||q(n),n},[M,P,u.maxRetryAttempts,q]),I=e.useCallback(async()=>{const n=(await M()).filter(s=>s.status==="failed");for(const s of n)s.attempts<u.maxRetryAttempts&&await X(s.id,"pending");await d()},[M,u.maxRetryAttempts,X,d]),E=e.useCallback((a,n)=>{D.current[a]=n},[]),R=e.useCallback(async()=>{try{const r=(await g()).transaction("drafts","readonly").objectStore("drafts").getAll();r.onsuccess=()=>{const c=r.result,l={};for(const h of c)l[h.formId]=(l[h.formId]||0)+1;const _=c.filter(h=>h.status==="pending").length,y=c.filter(h=>h.status==="failed").length;f(h=>({...h,draftCounts:l,pendingCount:_,failedCount:y}))}}catch{}},[g]);e.useEffect(()=>{const a=()=>{f(s=>({...s,isOnline:!0})),u.autoSubmitOnline&&d()},n=()=>{f(s=>({...s,isOnline:!1}))};return window.addEventListener("online",a),window.addEventListener("offline",n),()=>{window.removeEventListener("online",a),window.removeEventListener("offline",n)}},[u.autoSubmitOnline,d]),e.useEffect(()=>{g().then(()=>R())},[g,R]),e.useImperativeHandle(A,()=>({getState:()=>b,saveDraft:j,getDraft:B,getDrafts:L,getPendingDrafts:M,updateDraft:W,deleteDraft:F,submitDraft:P,submitForm:H,syncPending:d,retryFailed:I,clearDrafts:z,registerHandler:E}),[b,j,B,L,M,W,F,P,H,d,I,z,E]);const i={...b,saveDraft:j,getDraft:B,getDrafts:L,getPendingDrafts:M,updateDraft:W,deleteDraft:F,submitDraft:P,submitForm:H,syncPending:d,retryFailed:I,clearDrafts:z,registerHandler:E};return t.jsx(gn.Provider,{value:i,children:o})});xe.displayName="NiceOfflineForms";const bn=xe;bn.displayName="NiceOfflineFormsProvider";const De=()=>{const m=navigator;return m.connection?{type:m.connection.type,effectiveType:m.connection.effectiveType,downlink:m.connection.downlink,rtt:m.connection.rtt,saveData:m.connection.saveData}:{}},Ee=m=>{if(!m.effectiveType)return m.downlink?Math.min(100,m.downlink*10):50;switch(m.effectiveType){case"4g":return 100;case"3g":return 75;case"2g":return 50;case"slow-2g":return 25;default:return 50}},He=e.forwardRef((m,A)=>{const{mode:x="banner",position:k="top",showWhenOnline:p=!1,autoHideOnlineDelay:N=3e3,showSlowConnectionWarning:O=!0,slowConnectionThreshold:q=1,showReconnecting:o=!0,reconnectCheckInterval:u=5e3,offlineMessage:S="You're offline",onlineMessage:D="Back online",slowConnectionMessage:b="Slow connection",reconnectingMessage:f="Reconnecting...",showDetails:g=!1,animated:j=!0,pulseWhenOffline:B=!0,offlineIcon:L,onlineIcon:M,slowIcon:W,renderContent:X,onStatusChange:F,onReconnect:z,className:P,style:H}=m,[d,I]=e.useState(()=>{const Y=De();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...Y,quality:Ee(Y)}}),[E,R]=e.useState(!d.isOnline||p),[i,a]=e.useState(!1),[n,s]=e.useState(null),r=e.useCallback(()=>{const Y=De(),C=navigator.onLine;I(Q=>{const K={isOnline:C,...Y,quality:C?Ee(Y):0,lastOnlineAt:C?new Date:Q.lastOnlineAt,offlineDuration:!C&&n?Date.now()-n.getTime():void 0};return(Q.isOnline!==K.isOnline||Q.quality!==K.quality)&&(F==null||F(K)),K})},[n,F]),c=e.useCallback(async()=>{try{return(await fetch("/favicon.ico",{method:"HEAD",cache:"no-store"})).ok}catch{return!1}},[]);e.useEffect(()=>{const Y=()=>{a(!1),s(null),r(),R(!0),z==null||z(),N>0&&setTimeout(()=>{R(p)},N)},C=()=>{s(new Date),r(),R(!0),a(o)};window.addEventListener("online",Y),window.addEventListener("offline",C);const Q=navigator;return Q.connection&&Q.connection.addEventListener("change",r),()=>{window.removeEventListener("online",Y),window.removeEventListener("offline",C),Q.connection&&Q.connection.removeEventListener("change",r)}},[r,N,p,o,z]),e.useEffect(()=>{if(!i||d.isOnline)return;const Y=setInterval(async()=>{await c()&&window.dispatchEvent(new Event("online"))},u);return()=>clearInterval(Y)},[i,d.isOnline,u,c]),e.useEffect(()=>{if(d.isOnline||!n)return;const Y=setInterval(()=>{I(C=>({...C,offlineDuration:Date.now()-n.getTime()}))},1e3);return()=>clearInterval(Y)},[d.isOnline,n]),e.useImperativeHandle(A,()=>({getConnectionInfo:()=>d,checkConnection:c,show:()=>R(!0),hide:()=>R(!1),toggle:()=>R(Y=>!Y)}),[d,c]);const l=d.isOnline&&O&&d.downlink!==void 0&&d.downlink<q,y=d.isOnline?l?"slow":"online":i?"reconnecting":"offline",h=()=>{switch(y){case"offline":return S;case"reconnecting":return f;case"slow":return b;case"online":return D}},v=()=>{switch(y){case"offline":case"reconnecting":return L||"📴";case"slow":return W||"🐌";case"online":return M||"✅"}},T=Y=>{const C=Math.floor(Y/1e3);if(C<60)return`${C}s`;const Q=Math.floor(C/60);return Q<60?`${Q}m ${C%60}s`:`${Math.floor(Q/60)}h ${Q%60}m`};if(!E||d.isOnline&&!p&&!l)return null;const w=["nice-offline-indicator",`nice-offline-indicator--${x}`,`nice-offline-indicator--${k}`,`nice-offline-indicator--${y}`,j&&"nice-offline-indicator--animated",B&&y==="offline"&&"nice-offline-indicator--pulse",P].filter(Boolean).join(" ");if(X)return t.jsx("div",{className:w,style:H,children:X(d)});const U=()=>t.jsx("span",{className:"nice-offline-indicator__icon",children:v()}),$=()=>t.jsx("span",{className:"nice-offline-indicator__message",children:h()}),G=()=>g?t.jsxs("div",{className:"nice-offline-indicator__details",children:[d.offlineDuration!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__duration",children:["Offline for ",T(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,V=()=>!g||!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(x){case"icon-only":return t.jsx("div",{className:w,style:H,title:h(),children:U()});case"minimal":return t.jsxs("div",{className:w,style:H,children:[U(),$()]});case"badge":return t.jsxs("div",{className:w,style:H,children:[t.jsx("div",{className:"nice-offline-indicator__badge-dot"}),t.jsx("span",{className:"nice-offline-indicator__badge-text",children:h()})]});case"toast":return t.jsx("div",{className:w,style:H,children:t.jsxs("div",{className:"nice-offline-indicator__toast",children:[U(),t.jsxs("div",{className:"nice-offline-indicator__toast-content",children:[$(),G()]})]})});case"detailed":return t.jsx("div",{className:w,style:H,children:t.jsxs("div",{className:"nice-offline-indicator__detailed",children:[U(),t.jsxs("div",{className:"nice-offline-indicator__detailed-content",children:[$(),G(),V()]})]})});case"banner":default:return t.jsx("div",{className:w,style:H,children:t.jsxs("div",{className:"nice-offline-indicator__banner",children:[U(),$(),g&&t.jsxs(t.Fragment,{children:[G(),i&&t.jsx("span",{className:"nice-offline-indicator__spinner"})]})]})})}});He.displayName="NiceOfflineIndicator";const wn=e.createContext(null),vn={dbName:"nice-offline-media",maxCacheSize:500*1024*1024,maxConcurrentDownloads:3,autoResumeOnReconnect:!0,defaultCacheDuration:10080*60*1e3,autoCleanup:!0,cleanupInterval:3600*1e3},xn=()=>`media-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Cn=(m,A)=>{var p;const x=((p=m.split(".").pop())==null?void 0:p.toLowerCase())||"",k=(A==null?void 0:A.toLowerCase())||"";return k.startsWith("image/")||["jpg","jpeg","png","gif","webp","svg"].includes(x)?"image":k.startsWith("video/")||["mp4","webm","ogg","mov","avi"].includes(x)?"video":k.startsWith("audio/")||["mp3","wav","ogg","flac","m4a"].includes(x)?"audio":["pdf","doc","docx","xls","xlsx","ppt","pptx"].includes(x)?"document":"other"},kn=m=>{try{return new URL(m).pathname.split("/").pop()||"unknown"}catch{return m.split("/").pop()||"unknown"}},Ce=e.forwardRef((m,A)=>{const{config:x,onDownloadStart:k,onDownloadProgress:p,onDownloadComplete:N,onDownloadFailed:O,onMediaRemoved:q,children:o}=m,u={...vn,...x},S=e.useRef(null),D=e.useRef(new Map),b=e.useRef(new Map),[f,g]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,activeDownloads:0,queuedDownloads:0,cachedCount:0,totalCacheSize:0,isDownloading:!1}),j=e.useCallback(async()=>S.current?S.current:new Promise((T,w)=>{const U=indexedDB.open(u.dbName,1);U.onerror=()=>w(U.error),U.onupgradeneeded=()=>{const $=U.result;if(!$.objectStoreNames.contains("media")){const G=$.createObjectStore("media",{keyPath:"id"});G.createIndex("url","url",{unique:!0}),G.createIndex("type","type",{unique:!1}),G.createIndex("status","status",{unique:!1})}$.objectStoreNames.contains("blobs")||$.createObjectStore("blobs",{keyPath:"id"})},U.onsuccess=()=>{S.current=U.result,T(U.result)}}),[u.dbName]),B=e.useCallback(async T=>{const w=await j();return new Promise((U,$)=>{const Y=w.transaction("media","readwrite").objectStore("media").put(T);Y.onerror=()=>$(Y.error),Y.onsuccess=()=>U()})},[j]),L=e.useCallback(async(T,w)=>{const U=await j();return new Promise(($,G)=>{const C=U.transaction("blobs","readwrite").objectStore("blobs").put({id:T,blob:w});C.onerror=()=>G(C.error),C.onsuccess=()=>$()})},[j]),M=e.useCallback(async T=>{const w=await j();return new Promise((U,$)=>{const Y=w.transaction("blobs","readonly").objectStore("blobs").get(T);Y.onerror=()=>$(Y.error),Y.onsuccess=()=>{var C;return U((C=Y.result)==null?void 0:C.blob)}})},[j]),W=e.useCallback(async T=>{const w=await j();return new Promise((U,$)=>{const Y=w.transaction("media","readonly").objectStore("media").get(T);Y.onerror=()=>$(Y.error),Y.onsuccess=()=>{const C=Y.result;C&&(C.cachedAt=C.cachedAt?new Date(C.cachedAt):void 0,C.expiresAt=C.expiresAt?new Date(C.expiresAt):void 0),U(C)}})},[j]),X=e.useCallback(async()=>{const T=await j();return new Promise((w,U)=>{const V=T.transaction("media","readonly").objectStore("media").getAll();V.onerror=()=>U(V.error),V.onsuccess=()=>{w(V.result.map(Y=>({...Y,cachedAt:Y.cachedAt?new Date(Y.cachedAt):void 0,expiresAt:Y.expiresAt?new Date(Y.expiresAt):void 0})))}})},[j]),F=e.useCallback(async T=>{const w=await j();return new Promise((U,$)=>{const C=w.transaction("media","readonly").objectStore("media").index("type").getAll(T);C.onerror=()=>$(C.error),C.onsuccess=()=>U(C.result)})},[j]),z=e.useCallback(async T=>(await X()).filter(U=>{var $;return($=U.tags)==null?void 0:$.includes(T)}),[X]),P=e.useCallback(async T=>{const w=await j();return new Promise((U,$)=>{const C=w.transaction("media","readonly").objectStore("media").index("url").get(T);C.onerror=()=>$(C.error),C.onsuccess=()=>U(C.result)})},[j]),H=e.useCallback(async T=>{const w=await P(T);return(w==null?void 0:w.status)==="completed"},[P]),d=e.useCallback(async T=>{const w=b.current.get(T);if(w)return w;const U=await M(T);if(!U)return;const $=URL.createObjectURL(U);return b.current.set(T,$),$},[M]),I=e.useCallback(async(T,w)=>{var Y;const U=await P(T);if((U==null?void 0:U.status)==="completed")return U.id;const $=new AbortController,G=(U==null?void 0:U.id)||xn(),V={id:G,url:T,type:(w==null?void 0:w.type)||"other",name:(w==null?void 0:w.name)||kn(T),mimeType:"",size:0,status:"queued",progress:0,downloadedBytes:0,metadata:w==null?void 0:w.metadata,tags:w==null?void 0:w.tags,priority:w==null?void 0:w.priority};D.current.set(G,$),await B(V),k==null||k(V),g(C=>({...C,queuedDownloads:C.queuedDownloads+1,isDownloading:!0}));try{V.status="downloading",await B(V),g(re=>({...re,activeDownloads:re.activeDownloads+1,queuedDownloads:re.queuedDownloads-1}));const C=await fetch(T,{signal:$.signal,headers:w==null?void 0:w.headers});if(!C.ok)throw new Error(`HTTP ${C.status}`);const Q=C.headers.get("content-length"),K=C.headers.get("content-type")||"",J=Q?parseInt(Q,10):0;V.size=J,V.mimeType=K,V.type=(w==null?void 0:w.type)||Cn(T,K);const Z=(Y=C.body)==null?void 0:Y.getReader();if(!Z)throw new Error("No response body");const ee=[];let te=0;for(;;){const{done:re,value:Se}=await Z.read();if(re)break;ee.push(Se),te+=Se.length,V.downloadedBytes=te,V.progress=J>0?Math.round(te/J*100):0,await B(V),p==null||p(V)}const ne=new Blob(ee,{type:K});return await L(G,ne),V.status="completed",V.progress=100,V.size=ne.size,V.cachedAt=new Date,V.expiresAt=w!=null&&w.cacheDuration?new Date(Date.now()+w.cacheDuration):new Date(Date.now()+u.defaultCacheDuration),await B(V),N==null||N(V),G}catch(C){throw C.name==="AbortError"?V.status="cancelled":(V.status="failed",V.error=C instanceof Error?C.message:"Download failed",O==null||O(V,C instanceof Error?C:new Error(String(C)))),await B(V),C}finally{D.current.delete(G),g(C=>({...C,activeDownloads:Math.max(0,C.activeDownloads-1),isDownloading:C.activeDownloads>1})),await h()}},[P,B,L,u.defaultCacheDuration,k,p,N,O]),E=e.useCallback(async T=>{const w=[];for(let U=0;U<T.length;U+=u.maxConcurrentDownloads){const $=T.slice(U,U+u.maxConcurrentDownloads),G=await Promise.allSettled($.map(V=>I(V.url,V.options)));for(const V of G)V.status==="fulfilled"&&w.push(V.value)}return w},[I,u.maxConcurrentDownloads]),R=e.useCallback(T=>{const w=D.current.get(T);w&&w.abort()},[]),i=e.useCallback(async T=>{const w=await W(T);w&&(w.status==="paused"||w.status==="failed")&&await I(w.url,{type:w.type,name:w.name,metadata:w.metadata,tags:w.tags})},[W,I]),a=e.useCallback(T=>{R(T)},[R]),n=e.useCallback(()=>{for(const[T]of D.current)R(T)},[R]),s=e.useCallback(async()=>{const w=(await X()).filter(U=>U.status==="paused"||U.status==="failed");await E(w.map(U=>({url:U.url})))},[X,E]),r=e.useCallback(async T=>{const w=await j(),U=b.current.get(T);U&&(URL.revokeObjectURL(U),b.current.delete(T)),await new Promise(($,G)=>{const V=w.transaction(["media","blobs"],"readwrite");V.objectStore("media").delete(T),V.objectStore("blobs").delete(T),V.onerror=()=>G(V.error),V.oncomplete=()=>$()}),q==null||q(T),await h()},[j,q]),c=e.useCallback(async()=>{const T=await j();for(const[,w]of b.current)URL.revokeObjectURL(w);b.current.clear(),await new Promise((w,U)=>{const $=T.transaction(["media","blobs"],"readwrite");$.objectStore("media").clear(),$.objectStore("blobs").clear(),$.onerror=()=>U($.error),$.oncomplete=()=>w()}),await h()},[j]),l=e.useCallback(async()=>{const T=await X(),w=Date.now();let U=0;for(const $ of T)$.expiresAt&&$.expiresAt.getTime()<w&&(await r($.id),U++);return U},[X,r]),_=e.useCallback(async()=>{const w=(await X()).filter(G=>G.status==="completed"),U={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 G of w)$+=G.size,U[G.type].count++,U[G.type].size+=G.size;return{totalSize:$,itemCount:w.length,byType:U}},[X]),y=e.useCallback(async T=>{await E(T.map(w=>({url:w,options:{priority:-1}})))},[E]),h=e.useCallback(async()=>{const T=await _();g(w=>({...w,cachedCount:T.itemCount,totalCacheSize:T.totalSize}))},[_]);e.useEffect(()=>{const T=()=>{g(U=>({...U,isOnline:!0})),u.autoResumeOnReconnect&&s()},w=()=>{g(U=>({...U,isOnline:!1})),n()};return window.addEventListener("online",T),window.addEventListener("offline",w),()=>{window.removeEventListener("online",T),window.removeEventListener("offline",w)}},[u.autoResumeOnReconnect,s,n]),e.useEffect(()=>{if(!u.autoCleanup)return;const T=setInterval(()=>{l()},u.cleanupInterval);return()=>clearInterval(T)},[u.autoCleanup,u.cleanupInterval,l]),e.useEffect(()=>{j().then(()=>h());const T=b.current;return()=>{for(const[,w]of T)URL.revokeObjectURL(w)}},[j,h]),e.useImperativeHandle(A,()=>({getState:()=>f,download:I,downloadMultiple:E,getCachedMedia:W,getAllCachedMedia:X,getMediaByType:F,getMediaByTag:z,getBlobUrl:d,isCached:H,pauseDownload:R,resumeDownload:i,cancelDownload:a,pauseAll:n,resumeAll:s,removeMedia:r,clearCache:c,clearExpired:l,getCacheStats:_,preload:y}),[f,I,E,W,X,F,z,d,H,R,i,a,n,s,r,c,l,_,y]);const v={...f,download:I,downloadMultiple:E,getCachedMedia:W,getAllCachedMedia:X,getMediaByType:F,getMediaByTag:z,getBlobUrl:d,isCached:H,pauseDownload:R,resumeDownload:i,cancelDownload:a,removeMedia:r,clearCache:c,preload:y};return t.jsx(wn.Provider,{value:v,children:o})});Ce.displayName="NiceOfflineMedia";const Sn=Ce;Sn.displayName="NiceOfflineMediaProvider";const _n=e.createContext(null),Nn={swPath:"/service-worker.js",scope:"/",updateCheckInterval:6e4,autoUpdate:!1,skipWaiting:!1,reloadOnActivation:!0},ke=e.forwardRef((m,A)=>{const{config:x,showUpdateNotification:k=!0,showOfflineIndicator:p=!0,renderUpdateNotification:N,renderOfflineIndicator:O,notificationPosition:q="bottom",autoDismissDelay:o=0,onRegistered:u,onUpdateAvailable:S,onActivated:D,onError:b,onOnlineStatusChange:f,children:g,className:j}=m,B={...Nn,...x},[L,M]=e.useState({status:"idle",updateAvailable:!1,waitingWorker:!1,cachedUrls:[],caches:[],isOnline:typeof navigator<"u"?navigator.onLine:!0}),[W,X]=e.useState(!1);e.useEffect(()=>{const l=()=>{M(y=>({...y,isOnline:!0})),f==null||f(!0)},_=()=>{M(y=>({...y,isOnline:!1})),f==null||f(!1)};return window.addEventListener("online",l),window.addEventListener("offline",_),()=>{window.removeEventListener("online",l),window.removeEventListener("offline",_)}},[f]);const F=e.useCallback(async()=>{if(!("caches"in window))return[];const l=await caches.keys(),_=[];for(const y of l){const h=await caches.open(y),v=await h.keys();let T=0;for(const w of v){const U=await h.match(w);if(U){const $=await U.clone().blob();T+=$.size}}_.push({name:y,size:T,itemCount:v.length})}return M(y=>({...y,caches:_})),_},[]),z=e.useCallback(async l=>{if(!("caches"in window))return!1;const _=await caches.delete(l);return await F(),_},[F]),P=e.useCallback(async()=>{if(!("caches"in window))return;const l=await caches.keys();await Promise.all(l.map(_=>caches.delete(_))),M(_=>({..._,caches:[],cachedUrls:[]}))},[]),H=e.useCallback(async(l,_)=>{if(!("caches"in window))return;await(await caches.open(l)).addAll(_),await F()},[F]),d=e.useCallback(async(l,_)=>{if(!("caches"in window))return!1;const h=await(await caches.open(l)).delete(_);return await F(),h},[F]),I=e.useCallback(async l=>"caches"in window?(await(await caches.open(l)).keys()).map(h=>h.url):[],[]),E=e.useCallback(async()=>{if(!("serviceWorker"in navigator)){M(l=>({...l,status:"error",error:"Service Worker not supported"}));return}M(l=>({...l,status:"registering"}));try{const l=await navigator.serviceWorker.register(B.swPath,{scope:B.scope});M(y=>({...y,status:"registered",registration:l})),u==null||u(l),l.addEventListener("updatefound",()=>{const y=l.installing;y&&y.addEventListener("statechange",()=>{switch(y.state){case"installing":M(h=>({...h,status:"installing"}));break;case"installed":navigator.serviceWorker.controller?(M(h=>({...h,status:"installed",updateAvailable:!0,waitingWorker:!0})),X(!0),S==null||S()):M(h=>({...h,status:"installed"}));break;case"activating":M(h=>({...h,status:"activating"}));break;case"activated":M(h=>({...h,status:"activated",updateAvailable:!1,waitingWorker:!1})),D==null||D(),B.reloadOnActivation&&window.location.reload();break;case"redundant":M(h=>({...h,status:"redundant"}));break}})}),l.waiting&&(M(y=>({...y,updateAvailable:!0,waitingWorker:!0})),X(!0),S==null||S());let _=!1;return navigator.serviceWorker.addEventListener("controllerchange",()=>{!_&&B.reloadOnActivation&&(_=!0,window.location.reload())}),await F(),l}catch(l){const _=l instanceof Error?l.message:"Registration failed";M(y=>({...y,status:"error",error:_})),b==null||b(l instanceof Error?l:new Error(_));return}},[B,u,S,D,b,F]),R=e.useCallback(async()=>{if(!L.registration)return!1;const l=await L.registration.unregister();return l&&M(_=>({..._,status:"idle",registration:void 0,updateAvailable:!1,waitingWorker:!1})),l},[L.registration]),i=e.useCallback(async()=>{L.registration&&await L.registration.update()},[L.registration]),a=e.useCallback(()=>{var l;(l=L.registration)!=null&&l.waiting&&L.registration.waiting.postMessage({type:"SKIP_WAITING"})},[L.registration]),n=e.useCallback(()=>{B.skipWaiting&&a(),X(!1)},[B.skipWaiting,a]),s=e.useCallback(()=>{window.location.reload()},[]);e.useEffect(()=>{E()},[E]),e.useEffect(()=>{if(!B.updateCheckInterval||B.updateCheckInterval<=0)return;const l=setInterval(()=>{i()},B.updateCheckInterval);return()=>clearInterval(l)},[B.updateCheckInterval,i]),e.useEffect(()=>{if(!W||o<=0)return;const l=setTimeout(()=>{X(!1)},o);return()=>clearTimeout(l)},[W,o]),e.useImperativeHandle(A,()=>({getState:()=>L,register:E,unregister:R,checkForUpdates:i,applyUpdate:n,skipWaiting:a,getCachesInfo:F,clearCache:z,clearAllCaches:P,addToCache:H,removeFromCache:d,getCachedUrls:I,forceReload:s}),[L,E,R,i,n,a,F,z,P,H,d,I,s]);const r={...L,register:E,unregister:R,checkForUpdates:i,applyUpdate:n,skipWaiting:a,getCachesInfo:F,clearCache:z,clearAllCaches:P,addToCache:H,removeFromCache:d,getCachedUrls:I},c=`nice-sw-notification--${q}`;return t.jsx(_n.Provider,{value:r,children:t.jsxs("div",{className:`nice-service-worker ${j||""}`,children:[g,k&&W&&L.updateAvailable&&t.jsx("div",{className:`nice-sw-notification ${c}`,children:N?N({onUpdate:n,onDismiss:()=>X(!1)}):t.jsxs("div",{className:"nice-sw-notification__content",children:[t.jsx("div",{className:"nice-sw-notification__icon",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:n,children:"Update Now"}),t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--secondary",onClick:()=>X(!1),children:"Later"})]})]})}),p&&!L.isOnline&&t.jsx("div",{className:`nice-sw-offline ${c}`,children:O?O({isOnline:L.isOnline}):t.jsxs("div",{className:"nice-sw-offline__content",children:[t.jsx("div",{className:"nice-sw-offline__icon",children:"📴"}),t.jsx("span",{children:"You are offline"})]})})]})})});ke.displayName="NiceServiceWorker";const ze=e.forwardRef((m,A)=>t.jsx(ke,{...m,ref:A}));ze.displayName="NiceServiceWorkerProvider";exports.NiceAutoStart=ue;exports.NiceBackgroundSync=ye;exports.NiceBarcodeScanner=Fe;exports.NiceBatchScanner=Be;exports.NiceCacheStrategies=be;exports.NiceConflictResolution=we;exports.NiceExternalDisplay=fe;exports.NiceHardwareBarcodeGenerator=Me;exports.NiceHardwareQRGenerator=$e;exports.NiceIndexedDB=ve;exports.NiceKioskMode=me;exports.NiceLowPowerMode=he;exports.NiceOfflineForms=xe;exports.NiceOfflineIndicator=He;exports.NiceOfflineMedia=Ce;exports.NiceOrientationLock=ge;exports.NiceQRScanner=qe;exports.NiceRemoteManagement=pe;exports.NiceScreenBurnPrevention=Re;exports.NiceServiceWorker=ke;exports.NiceServiceWorkerProvider=ze;exports.NiceSymbologyConfig=Ue;exports.NiceTouchCalibration=Pe;
|
|
11
|
+
</svg>`}catch{return null}},[p,i]),V=e.useCallback((B="qrcode",G="png")=>{const E=document.createElement("a");if(G==="svg"){const $=U();if(!$)return;const R=new Blob([$],{type:"image/svg+xml"});E.href=URL.createObjectURL(R),E.download=`${B}.svg`}else{const $=q();if(!$)return;E.href=$,E.download=`${B}.png`}E.click()},[q,U]),z=e.useCallback(()=>{A()},[A]);e.useImperativeHandle(f,()=>({toDataURL:q,toSVG:U,download:V,regenerate:z}),[q,U,V,z]);const Y=["nice-qr-generator",T&&"nice-qr-generator--bordered",L&&"nice-qr-generator--error",P].filter(Boolean).join(" ");return t.jsxs("div",{className:Y,children:[t.jsx("canvas",{ref:d,className:"nice-qr-generator__canvas",style:{maxWidth:"100%",height:"auto"}}),L&&t.jsx("div",{className:"nice-qr-generator__error",children:t.jsx("span",{children:L})})]})});rt.displayName="NiceQRGenerator";const xn={continuous:!0,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd",parseDataType:!0,highlightDetected:!0},Cn=n=>{var f,p,C;if(/^https?:\/\//i.test(n))return{type:"url",data:{url:n}};if(/^mailto:/i.test(n)){const h=n.match(/^mailto:([^?]+)(?:\?(.*))?$/i);return{type:"email",data:{email:h==null?void 0:h[1],params:h==null?void 0:h[2]}}}if(/^tel:/i.test(n))return{type:"tel",data:{phone:n.replace(/^tel:/i,"")}};if(/^smsto?:/i.test(n)){const h=n.match(/^smsto?:([^:]+)(?::(.*))?$/i);return{type:"sms",data:{phone:h==null?void 0:h[1],message:h==null?void 0:h[2]}}}if(/^geo:/i.test(n)){const h=n.match(/^geo:(-?\d+\.?\d*),(-?\d+\.?\d*)(?:,(-?\d+\.?\d*))?/i);return{type:"geo",data:{latitude:parseFloat((h==null?void 0:h[1])||"0"),longitude:parseFloat((h==null?void 0:h[2])||"0"),altitude:h!=null&&h[3]?parseFloat(h[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 h=(f=n.match(/S:([^;]+)/))==null?void 0:f[1],N=(p=n.match(/P:([^;]+)/))==null?void 0:p[1],T=(C=n.match(/T:([^;]+)/))==null?void 0:C[1],P=n.includes("H:true");return{type:"wifi",data:{ssid:h,password:N,type:T,hidden:P}}}return{type:"text"}},kn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),p=n.createGain();f.connect(p),p.connect(n.destination),f.type="square",f.frequency.value=1200,p.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},80)}catch{}},Sn=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate([50,30,50])},_n=()=>typeof window<"u"&&"BarcodeDetector"in window,Nn=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],at=e.forwardRef((n,f)=>{const{config:p,onScan:C,onError:h,onCameraReady:N,autoStart:T=!1,showScanFrame:P=!0,children:i,className:d}=n,b={...xn,...p},L=e.useRef(null),x=e.useRef(null),u=e.useRef(null),y=e.useRef(null),A=e.useRef(null),q=e.useRef(null),[U,V]=e.useState(!1),[z,Y]=e.useState(!1),[B,G]=e.useState(null),[E,$]=e.useState(null),[R,k]=e.useState(null),[S,D]=e.useState(b.facingMode),[c,s]=e.useState(!1),[a,r]=e.useState(!1),[o,l]=e.useState(null),j=_n(),F=e.useCallback(async()=>{var Z;if(!L.current)return;const Q=Nn(b.resolution),K={video:{facingMode:S,width:{ideal:Q.width},height:{ideal:Q.height}},audio:!1};try{const ee=await navigator.mediaDevices.getUserMedia(K);u.current=ee,L.current.srcObject=ee,await L.current.play();const te=ee.getVideoTracks()[0],ne=(Z=te.getCapabilities)==null?void 0:Z.call(te);s(!!(ne!=null&&ne.torch)),Y(!0),k(!0),$(null),N==null||N()}catch(ee){const te=ee instanceof Error?ee.message:"Failed to access camera";$(te),k(!1),h==null||h(new Error(te))}},[b.resolution,S,N,h]),g=e.useCallback(()=>{u.current&&(u.current.getTracks().forEach(Q=>Q.stop()),u.current=null),L.current&&(L.current.srcObject=null),Y(!1),r(!1)},[]),m=e.useCallback(async()=>{D(S==="user"?"environment":"user"),U&&g()},[S,U,g]),w=e.useCallback(async()=>{if(!u.current||!c)return;const Q=u.current.getVideoTracks()[0],K=!a;try{await Q.applyConstraints({advanced:[{torch:K}]}),r(K)}catch{}},[c,a]),O=e.useCallback(async()=>{if(j)try{const Q=window.BarcodeDetector;y.current=new Q({formats:["qr_code"]})}catch(Q){const K=Q instanceof Error?Q.message:"Failed to initialize QR detector";$(K),h==null||h(new Error(K))}},[j,h]),_=e.useCallback((Q,K)=>{const Z={text:Q,boundingBox:K.boundingBox?{x:K.boundingBox.x,y:K.boundingBox.y,width:K.boundingBox.width,height:K.boundingBox.height}:void 0,cornerPoints:K.cornerPoints,timestamp:new Date};if(b.parseDataType){const ee=Cn(Q);Z.dataType=ee.type,Z.parsedData=ee.data}return Z},[b.parseDataType]),W=e.useCallback(async()=>{if(!(!L.current||!y.current||!z))try{const K=await y.current.detect(L.current);if(K.length>0){const Z=K[0];if(b.continuous&&Z.rawValue===q.current)return;q.current=Z.rawValue;const ee=_(Z.rawValue,Z);b.highlightDetected&&ee.boundingBox&&(l(ee.boundingBox),setTimeout(()=>l(null),500)),b.beepOnScan&&kn(),b.vibrateOnScan&&Sn(),G(ee),C==null||C(ee),setTimeout(()=>{q.current=null},1e3)}}catch{}},[z,b.continuous,b.highlightDetected,b.beepOnScan,b.vibrateOnScan,_,C]),I=e.useCallback(async()=>{V(!0),$(null),await O(),await F()},[O,F]),H=e.useCallback(()=>{V(!1),A.current&&(clearInterval(A.current),A.current=null),g()},[g]),M=e.useCallback(async()=>{U?H():await I()},[U,I,H]),X=e.useCallback(()=>{if(!L.current||!x.current)return null;const Q=x.current,K=L.current;Q.width=K.videoWidth,Q.height=K.videoHeight;const Z=Q.getContext("2d");return Z?(Z.drawImage(K,0,0),Q.toDataURL("image/png")):null},[]),v=e.useCallback(async Q=>!j||!y.current?null:new Promise(K=>{const Z=new Image;Z.onload=async()=>{try{const te=await y.current.detect(Z);if(te.length>0){const ne=_(te[0].rawValue,te[0]);K(ne)}else K(null)}catch{K(null)}},Z.onerror=()=>K(null),Z.src=URL.createObjectURL(Q)}),[j,_]);e.useEffect(()=>(U&&z&&b.continuous&&(A.current=setInterval(W,b.scanInterval)),()=>{A.current&&(clearInterval(A.current),A.current=null)}),[U,z,b.continuous,b.scanInterval,W]),e.useEffect(()=>(T&&I(),()=>{H()}),[]),e.useEffect(()=>{U&&!z&&F()},[S,U,z,F]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:U,isCameraReady:z,lastResult:B,error:E,isSupported:j,hasPermission:R,torchAvailable:c,torchOn:a}),start:I,stop:H,toggle:M,switchCamera:m,toggleTorch:w,takeSnapshot:X,scanImage:v}),[U,z,B,E,j,R,c,a,I,H,M,m,w,X,v]);const J=["nice-qr-scanner",U&&"nice-qr-scanner--scanning",z&&"nice-qr-scanner--ready",E&&"nice-qr-scanner--error",d].filter(Boolean).join(" ");return t.jsxs("div",{className:J,children:[t.jsx("video",{ref:L,className:"nice-qr-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:x,className:"nice-qr-scanner__canvas"}),P&&U&&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"})]}),o&&L.current&&t.jsx("div",{className:"nice-qr-scanner__bounding-box",style:{left:`${o.x/L.current.videoWidth*100}%`,top:`${o.y/L.current.videoHeight*100}%`,width:`${o.width/L.current.videoWidth*100}%`,height:`${o.height/L.current.videoHeight*100}%`}}),E&&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:E}),t.jsx("button",{className:"nice-qr-scanner__error-btn",onClick:()=>I(),children:"Try Again"})]}),!j&&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})]})});at.displayName="NiceQRScanner";const ve=e.createContext(null),In=()=>{const n=e.useContext(ve);if(!n)throw new Error("useSymbology must be used within NiceSymbologyConfigProvider");return n},ae=[{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"}],ue=(n,f)=>{const p=ae.find(i=>i.id===f);if(!p)return{valid:!1,errors:["Unknown symbology"],warnings:[]};const C=[],h=[],N=p.fixedLength&&p.hasCheckDigit?p.fixedLength-1:p.fixedLength,T=!!p.fixedLength&&p.hasCheckDigit&&n.length===p.fixedLength;switch(p.fixedLength?n.length!==N&&!T&&C.push(p.hasCheckDigit?`Expected ${N} digits, or ${p.fixedLength} with the check digit; got ${n.length}`:`Expected ${p.fixedLength} characters, got ${n.length}`):(n.length<p.minLength&&C.push(`Minimum ${p.minLength} characters required`),n.length>p.maxLength&&C.push(`Maximum ${p.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)||C.push("Only numeric digits allowed");break;case"code128c":/^\d+$/.test(n)||C.push("Only numeric digits allowed"),n.length%2!==0&&h.push("Length should be even for optimal encoding");break;case"code39":case"code93":/^[0-9A-Z\-. $/+%]+$/.test(n.toUpperCase())||C.push("Invalid characters for this symbology");break;case"codabar":/^[0-9\-$:/.+ABCD]+$/.test(n.toUpperCase())||C.push("Invalid characters for Codabar");break;case"plessey":/^[0-9A-F]+$/i.test(n)||C.push("Only hex characters (0-9, A-F) allowed");break}let P;if(p.hasCheckDigit&&C.length===0)switch(f){case"ean13":case"ean8":case"upc_a":case"itf14":{const i=(T?n.slice(0,-1):n).split("").map(Number);let d=0;for(let b=0;b<i.length;b++)d+=i[b]*((i.length-1-b)%2===0?3:1);P=String((10-d%10)%10),T&&n[n.length-1]!==P&&C.push(`Check digit should be ${P}, not ${n[n.length-1]}`);break}}return f==="itf"&&n.length%2!==0&&C.push("ITF requires even number of digits"),{valid:C.length===0,errors:C,warnings:h,checkDigit:P,formattedValue:P&&!T?n+P:n}},Oe={linear:"Linear (1D)","2d":"2D Matrix",postal:"Postal",gs1:"GS1 Standards"},it=e.forwardRef((n,f)=>{const{selected:p,onChange:C,category:h="all",multiSelect:N=!0,showDetails:T=!0,showValidation:P=!1,testValue:i="",readOnly:d=!1,className:b}=n,[L,x]=e.useState([]),[u,y]=e.useState(null),A=p??L,q=e.useMemo(()=>h==="all"?ae:ae.filter(c=>c.category===h),[h]),U=e.useMemo(()=>{const c={};for(const s of q)c[s.category]||(c[s.category]=[]),c[s.category].push(s);return c},[q]),V=e.useCallback(c=>{p||x(c),C==null||C(c)},[p,C]),z=e.useCallback(c=>{N?A.includes(c)||V([...A,c]):V([c])},[A,N,V]),Y=e.useCallback(c=>{V(A.filter(s=>s!==c))},[A,V]),B=e.useCallback(c=>{d||(A.includes(c)?Y(c):z(c))},[A,d,z,Y]),G=e.useCallback(()=>{V(q.map(c=>c.id))},[q,V]),E=e.useCallback(()=>{V([])},[V]),$=e.useCallback(c=>ae.find(s=>s.id===c),[]),R=e.useMemo(()=>!P||!i||!u?null:ue(i,u),[P,i,u]);e.useImperativeHandle(f,()=>({getSelected:()=>A,select:z,deselect:Y,selectAll:G,clearSelection:E,validate:ue,getInfo:$,getAll:()=>ae}),[A,z,Y,G,E,$]);const k=e.useMemo(()=>({symbologies:ae,selected:A,validate:ue,getInfo:$}),[A,$]),S=u?$(u):null,D=["nice-symbology-config",d&&"nice-symbology-config--readonly",b].filter(Boolean).join(" ");return t.jsx(ve.Provider,{value:k,children:t.jsxs("div",{className:D,children:[N&&!d&&t.jsxs("div",{className:"nice-symbology-config__toolbar",children:[t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:G,children:"Select All"}),t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:E,children:"Clear"}),t.jsxs("span",{className:"nice-symbology-config__count",children:[A.length," / ",q.length," selected"]})]}),t.jsxs("div",{className:"nice-symbology-config__content",children:[t.jsx("div",{className:"nice-symbology-config__list",children:Object.entries(U).map(([c,s])=>t.jsxs("div",{className:"nice-symbology-config__group",children:[t.jsx("h3",{className:"nice-symbology-config__group-title",children:Oe[c]||c}),t.jsx("div",{className:"nice-symbology-config__grid",children:s.map(a=>{const r=A.includes(a.id),o=u===a.id;return t.jsxs("div",{className:["nice-symbology-config__item",r&&"nice-symbology-config__item--selected",o&&"nice-symbology-config__item--active"].filter(Boolean).join(" "),onClick:()=>{B(a.id),y(a.id)},role:"option","aria-selected":r,tabIndex:0,onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),B(a.id),y(a.id))},children:[N&&t.jsx("span",{className:`nice-symbology-config__checkbox ${r?"nice-symbology-config__checkbox--checked":""}`,children:r&&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:a.name}),t.jsx("span",{className:"nice-symbology-config__item-desc",children:a.fixedLength?`${a.fixedLength} digits`:`${a.minLength}-${a.maxLength} chars`})]})]},a.id)})})]},c))}),T&&S&&t.jsxs("div",{className:"nice-symbology-config__details",children:[t.jsx("h3",{className:"nice-symbology-config__details-title",children:S.name}),t.jsx("p",{className:"nice-symbology-config__details-desc",children:S.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:Oe[S.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:S.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:S.fixedLength?`Fixed: ${S.fixedLength}`:`${S.minLength} – ${S.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:S.hasCheckDigit?"Yes":"No"})]}),S.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:S.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:S.useCases.map(c=>t.jsx("span",{className:"nice-symbology-config__tag",children:c},c))})]}),P&&R&&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 ${R.valid?"nice-symbology-config__validation-result--valid":"nice-symbology-config__validation-result--invalid"}`,children:[t.jsx("span",{children:R.valid?"Valid":"Invalid"}),R.checkDigit&&t.jsxs("span",{children:["Check digit: ",R.checkDigit]})]}),R.errors.map((c,s)=>t.jsx("div",{className:"nice-symbology-config__validation-error",children:c},s)),R.warnings.map((c,s)=>t.jsx("div",{className:"nice-symbology-config__validation-warning",children:c},s))]})]})]})]})})});it.displayName="NiceSymbologyConfig";const jn=({children:n})=>{const f=e.useCallback(C=>ae.find(h=>h.id===C),[]),p={symbologies:ae,selected:[],validate:ue,getInfo:f};return t.jsx(ve.Provider,{value:p,children:n})},ct=e.createContext(null),An=()=>{const n=e.useContext(ct);if(!n)throw new Error("useBackgroundSync must be used within NiceBackgroundSyncProvider");return n},Dn={dbName:"nice-background-sync",storeName:"sync-queue",defaultMaxAttempts:5,retryDelay:1e3,backoffFactor:2,maxRetryDelay:6e4,autoSyncOnConnect:!0,periodicSyncInterval:0},En=()=>`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Ln=n=>new Promise(f=>setTimeout(f,n)),xe=e.forwardRef((n,f)=>{const{config:p,handlers:C,onSyncStart:h,onSyncComplete:N,onTaskSuccess:T,onTaskFailed:P,onOnlineChange:i,children:d}=n,b={...Dn,...p},L=e.useRef(null),x=e.useRef(!1),[u,y]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,pendingCount:0,failedCount:0,syncProgress:0}),A=e.useCallback(async()=>L.current?L.current:new Promise((r,o)=>{const l=indexedDB.open(b.dbName,1);l.onerror=()=>o(l.error),l.onupgradeneeded=()=>{const j=l.result;if(!j.objectStoreNames.contains(b.storeName)){const F=j.createObjectStore(b.storeName,{keyPath:"id"});F.createIndex("tag","tag",{unique:!1}),F.createIndex("status","status",{unique:!1}),F.createIndex("priority","priority",{unique:!1})}},l.onsuccess=()=>{L.current=l.result,r(l.result)}}),[b.dbName,b.storeName]),q=e.useCallback(async(r,o,l)=>{const j=await A(),F={id:En(),tag:r,data:o,status:"pending",createdAt:new Date,attempts:0,maxAttempts:(l==null?void 0:l.maxAttempts)??b.defaultMaxAttempts,priority:(l==null?void 0:l.priority)??0};return new Promise((g,m)=>{const _=j.transaction(b.storeName,"readwrite").objectStore(b.storeName).add(F);_.onerror=()=>m(_.error),_.onsuccess=()=>{y(W=>({...W,pendingCount:W.pendingCount+1})),g(F.id)}})},[A,b.storeName,b.defaultMaxAttempts]),U=e.useCallback(async r=>{const o=await A();return new Promise((l,j)=>{const m=o.transaction(b.storeName,"readwrite").objectStore(b.storeName).delete(r);m.onerror=()=>j(m.error),m.onsuccess=()=>l(!0)})},[A,b.storeName]),V=e.useCallback(async r=>{const o=await A();return new Promise((l,j)=>{const g=o.transaction(b.storeName,"readonly").objectStore(b.storeName),m=r?g.index("tag").getAll(r):g.getAll();m.onerror=()=>j(m.error),m.onsuccess=()=>l(m.result)})},[A,b.storeName]),z=e.useCallback(async r=>(await V(r)).filter(l=>l.status==="pending"),[V]),Y=e.useCallback(async r=>(await V(r)).filter(l=>l.status==="failed"),[V]),B=e.useCallback(async r=>{const o=await A();return new Promise((l,j)=>{const m=o.transaction(b.storeName,"readwrite").objectStore(b.storeName).put(r);m.onerror=()=>j(m.error),m.onsuccess=()=>l()})},[A,b.storeName]),G=e.useCallback(async()=>{const r=await V(),o=r.filter(j=>j.status==="pending").length,l=r.filter(j=>j.status==="failed").length;y(j=>({...j,pendingCount:o,failedCount:l}))},[V]),E=e.useCallback(async r=>{const o=C[r.tag];if(!o)return console.warn(`No handler registered for tag: ${r.tag}`),!1;r.status="syncing",r.lastAttemptAt=new Date,r.attempts++,await B(r);try{return await o.handler(r),r.status="success",await B(r),T==null||T(r),await U(r.id),!0}catch(l){const j=l instanceof Error?l.message:"Unknown error";return r.error=j,r.attempts>=r.maxAttempts?(r.status="failed",P==null||P(r,l instanceof Error?l:new Error(j))):r.status="pending",await B(r),!1}},[C,B,U,T,P]),$=e.useCallback(async r=>{if(u.isSyncing)return{success:0,failed:0};x.current=!1,y(l=>({...l,isSyncing:!0,syncProgress:0,error:void 0})),h==null||h();const o={success:0,failed:0};try{const l=await z(r);l.sort((F,g)=>g.priority-F.priority);const j=l.length;for(let F=0;F<l.length&&!x.current;F++){const g=l[F],m=await E(g);if(m?o.success++:g.attempts>=g.maxAttempts&&o.failed++,!m&&g.attempts<g.maxAttempts){const w=Math.min(b.retryDelay*Math.pow(b.backoffFactor,g.attempts-1),b.maxRetryDelay);await Ln(w)}y(w=>({...w,syncProgress:Math.round((F+1)/j*100)}))}}catch(l){const j=l instanceof Error?l.message:"Sync failed";y(F=>({...F,error:j}))}return await G(),y(l=>({...l,isSyncing:!1,lastSyncAt:new Date,syncProgress:100})),N==null||N(o),o},[u.isSyncing,z,E,b.retryDelay,b.backoffFactor,b.maxRetryDelay,G,h,N]),R=e.useCallback(()=>{x.current=!0},[]),k=e.useCallback(async r=>{const l=(await V()).find(j=>j.id===r);l&&l.status==="failed"&&(l.status="pending",l.attempts=0,l.error=void 0,await B(l),await G())},[V,B,G]),S=e.useCallback(async r=>{const o=await Y(r);for(const l of o)l.status="pending",l.attempts=0,l.error=void 0,await B(l);await G()},[Y,B,G]),D=e.useCallback(async r=>{const o=await A(),l=await V(r);return new Promise((j,F)=>{const g=o.transaction(b.storeName,"readwrite"),m=g.objectStore(b.storeName);g.onerror=()=>F(g.error),g.oncomplete=async()=>{await G(),j()};for(const w of l)m.delete(w.id)})},[A,V,b.storeName,G]),c=e.useCallback(async r=>{const o=await A(),l=await Y(r);return new Promise((j,F)=>{const g=o.transaction(b.storeName,"readwrite"),m=g.objectStore(b.storeName);g.onerror=()=>F(g.error),g.oncomplete=async()=>{await G(),j()};for(const w of l)m.delete(w.id)})},[A,Y,b.storeName,G]),s=e.useCallback(async r=>{if(!("serviceWorker"in navigator))return!1;try{const o=await navigator.serviceWorker.ready;if("sync"in o)return await o.sync.register(r),!0}catch(o){console.warn("Background Sync registration failed:",o)}return!1},[]);e.useEffect(()=>{const r=()=>{y(l=>({...l,isOnline:!0})),i==null||i(!0),b.autoSyncOnConnect&&$()},o=()=>{y(l=>({...l,isOnline:!1})),i==null||i(!1)};return window.addEventListener("online",r),window.addEventListener("offline",o),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",o)}},[b.autoSyncOnConnect,$,i]),e.useEffect(()=>{if(b.periodicSyncInterval<=0)return;const r=setInterval(()=>{u.isOnline&&!u.isSyncing&&$()},b.periodicSyncInterval);return()=>clearInterval(r)},[b.periodicSyncInterval,u.isOnline,u.isSyncing,$]),e.useEffect(()=>{G()},[G]),e.useImperativeHandle(f,()=>({getState:()=>u,addTask:q,removeTask:U,getTasks:V,getPendingTasks:z,getFailedTasks:Y,retryTask:k,retryAllFailed:S,clearTasks:D,clearFailed:c,syncNow:$,cancelSync:R,registerBackgroundSync:s}),[u,q,U,V,z,Y,k,S,D,c,$,R,s]);const a={...u,addTask:q,removeTask:U,getTasks:V,getPendingTasks:z,getFailedTasks:Y,retryTask:k,retryAllFailed:S,clearTasks:D,clearFailed:c,syncNow:$,cancelSync:R};return t.jsx(ct.Provider,{value:a,children:d})});xe.displayName="NiceBackgroundSync";const ot=xe;ot.displayName="NiceBackgroundSyncProvider";const lt=e.createContext(null),ut=()=>{const n=e.useContext(lt);if(!n)throw new Error("useCacheStrategies must be used within NiceCacheStrategiesProvider");return n},Pn={cacheName:"nice-cache-strategies",defaultTTL:300*1e3,maxEntries:500,defaultStrategy:"stale-while-revalidate",networkTimeout:5e3,serveStale:!0,staleThreshold:60*1e3};class Rn{constructor(){ce(this,"dbName","nice-cache-db");ce(this,"storeName","cache-entries");ce(this,"db",null)}async init(){if(!this.db)return new Promise((f,p)=>{const C=indexedDB.open(this.dbName,1);C.onerror=()=>p(C.error),C.onupgradeneeded=()=>{const h=C.result;h.objectStoreNames.contains(this.storeName)||h.createObjectStore(this.storeName,{keyPath:"key"})},C.onsuccess=()=>{this.db=C.result,f()}})}async get(f){if(await this.init(),!!this.db)return new Promise((p,C)=>{const T=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(f);T.onerror=()=>C(T.error),T.onsuccess=()=>{const P=T.result;p(P?P.value:void 0)}})}async set(f,p){if(await this.init(),!!this.db)return new Promise((C,h)=>{const P=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:f,value:p});P.onerror=()=>h(P.error),P.onsuccess=()=>C()})}async delete(f){return await this.init(),this.db?new Promise((p,C)=>{const T=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(f);T.onerror=()=>C(T.error),T.onsuccess=()=>p(!0)}):!1}async keys(){return await this.init(),this.db?new Promise((f,p)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();N.onerror=()=>p(N.error),N.onsuccess=()=>f(N.result)}):[]}async clear(){if(await this.init(),!!this.db)return new Promise((f,p)=>{const N=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();N.onerror=()=>p(N.error),N.onsuccess=()=>f()})}async getAll(){return await this.init(),this.db?new Promise((f,p)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();N.onerror=()=>p(N.error),N.onsuccess=()=>f(N.result)}):[]}}const Ce=e.forwardRef((n,f)=>{const{config:p,routeStrategies:C={},precacheUrls:h=[],onFetch:N,onCacheHit:T,onCacheMiss:P,onNetworkError:i,children:d}=n,b={...Pn,...p},L=e.useRef(new Rn),[x,u]=e.useState({isFetching:!1,totalSize:0,entryCount:0,hits:0,misses:0,strategy:b.defaultStrategy}),y=e.useCallback(c=>{for(const[s,a]of Object.entries(C))if(new RegExp(s).test(c))return a;return x.strategy},[C,x.strategy]),A=e.useCallback(c=>{u(s=>({...s,strategy:c}))},[]),q=e.useCallback(async c=>{const s=await L.current.get(c);if(!s)return;const a=Date.now(),r=s.expiresAt&&s.expiresAt<a,o=s.timestamp+b.staleThreshold<a;if(r&&!b.serveStale){await L.current.delete(c);return}return{data:s.data,timestamp:new Date(s.timestamp),expiresAt:s.expiresAt?new Date(s.expiresAt):void 0,etag:s.etag,key:c,isStale:o||!!r,source:"cache",url:s.url}},[b.staleThreshold,b.serveStale]),U=e.useCallback(async(c,s,a)=>{const r=Date.now(),o={data:s,timestamp:r,expiresAt:a?r+a:r+b.defaultTTL};await L.current.set(c,o);const l=await L.current.keys();if(u(j=>({...j,entryCount:l.length})),l.length>b.maxEntries){const j=await L.current.getAll();j.sort((g,m)=>g.value.timestamp-m.value.timestamp);const F=j.slice(0,j.length-b.maxEntries);for(const g of F)await L.current.delete(g.key)}},[b.defaultTTL,b.maxEntries]),V=e.useCallback(async c=>{const s=await L.current.delete(c),a=await L.current.keys();return u(r=>({...r,entryCount:a.length})),s},[]),z=e.useCallback(async()=>{await L.current.clear(),u(c=>({...c,entryCount:0,totalSize:0}))},[]),Y=e.useCallback(async()=>L.current.keys(),[]),B=e.useCallback(async c=>await q(c)!==void 0,[q]),G=e.useCallback(async c=>{const s=await L.current.keys();let a=0;for(const o of s)c.test(o)&&(await L.current.delete(o),a++);const r=await L.current.keys();return u(o=>({...o,entryCount:r.length})),a},[]),E=e.useCallback(async(c,s,a)=>{const r=new AbortController,o=setTimeout(()=>r.abort(),a);try{const l=await fetch(c,{...s,signal:r.signal});return clearTimeout(o),l}catch(l){throw clearTimeout(o),l}},[]),$=e.useCallback(async(c,s={})=>{const{strategy:a=y(c),ttl:r,cacheKey:o=c,forceRefresh:l=!1,timeout:j=b.networkTimeout,...F}=s;u(m=>({...m,isFetching:!0}));const g=async()=>{try{const m=await E(c,F,j);if(!m.ok)throw new Error(`HTTP ${m.status}`);const w=await m.json(),O=m.headers.get("etag")||void 0;await U(o,w,r);const _={data:w,timestamp:new Date,etag:O,key:o,isStale:!1,source:"network",url:c};return u(W=>({...W,isFetching:!1})),N==null||N(_),_}catch(m){throw i==null||i(m instanceof Error?m:new Error(String(m)),c),m}};try{switch(a){case"cache-only":{const m=await q(o);if(m)return u(w=>({...w,isFetching:!1,hits:w.hits+1})),T==null||T(m),m;throw u(w=>({...w,isFetching:!1,misses:w.misses+1})),P==null||P(c),new Error("No cache entry found")}case"network-only":return u(m=>({...m,misses:m.misses+1})),await g();case"cache-first":{if(!l){const m=await q(o);if(m&&!m.isStale)return u(w=>({...w,isFetching:!1,hits:w.hits+1})),T==null||T(m),m}return u(m=>({...m,misses:m.misses+1})),await g()}case"network-first":try{return u(m=>({...m,misses:m.misses+1})),await g()}catch(m){const w=await q(o);if(w)return u(O=>({...O,isFetching:!1,hits:O.hits+1})),T==null||T(w),w;throw m}case"stale-while-revalidate":default:{const m=await q(o);return m&&!l?(u(w=>({...w,hits:w.hits+1})),T==null||T(m),m.isStale&&g().catch(()=>{}),u(w=>({...w,isFetching:!1})),m):(u(w=>({...w,misses:w.misses+1})),await g())}}}catch(m){throw u(w=>({...w,isFetching:!1})),m}},[y,b.networkTimeout,E,q,U,N,T,P,i]),R=e.useCallback(async(c,s)=>(await $(c,s)).data,[$]),k=e.useCallback(async(c,s)=>{await Promise.all(c.map(a=>$(a,{...s,strategy:"network-first"}).catch(()=>{})))},[$]),S=e.useCallback(async()=>{const c=await L.current.getAll();let s=0,a,r;for(const o of c){const l=JSON.stringify(o.value.data).length;s+=l,(!a||o.value.timestamp<a)&&(a=o.value.timestamp),(!r||o.value.timestamp>r)&&(r=o.value.timestamp)}return{size:s,entryCount:c.length,oldestEntry:a?new Date(a):void 0,newestEntry:r?new Date(r):void 0}},[]);e.useEffect(()=>{h.length>0&&k(h)},[h,k]),e.useEffect(()=>{(async()=>{await L.current.init();const s=await S();u(a=>({...a,totalSize:s.size,entryCount:s.entryCount}))})()},[S]),e.useImperativeHandle(f,()=>({getState:()=>x,fetch:$,fetchJSON:R,getFromCache:q,addToCache:U,removeFromCache:V,clearCache:z,getCacheKeys:Y,getCacheStats:S,prefetch:k,isCached:B,invalidateByPattern:G,setStrategy:A,getStrategyForUrl:y}),[x,$,R,q,U,V,z,Y,S,k,B,G,A,y]);const D={...x,fetch:$,fetchJSON:R,getFromCache:q,addToCache:U,removeFromCache:V,clearCache:z,getCacheKeys:Y,prefetch:k,isCached:B,setStrategy:A,getStrategyForUrl:y};return t.jsx(lt.Provider,{value:D,children:d})});Ce.displayName="NiceCacheStrategies";const dt=Ce;dt.displayName="NiceCacheStrategiesProvider";function On(n,f){const p=ut(),[C,h]=e.useState(void 0),[N,T]=e.useState(!1),[P,i]=e.useState(void 0),d=e.useCallback(async()=>{if(n){T(!0),i(void 0);try{const b=await p.fetchJSON(n,f);h(b)}catch(b){i(b instanceof Error?b:new Error(String(b)))}finally{T(!1)}}},[n,f,p]);return e.useEffect(()=>{d()},[d]),{data:C,isLoading:N,error:P,refetch:d}}const ft=e.createContext(null),Tn=()=>{const n=e.useContext(ft);if(!n)throw new Error("useConflictResolution must be used within NiceConflictResolutionProvider");return n},Mn={defaultStrategy:"manual",autoResolve:!1,maxPendingConflicts:100,persistConflicts:!0,storageKey:"nice-conflict-resolution"},Fn=()=>`conflict-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Bn=n=>JSON.stringify(n),$n=(n,f)=>JSON.stringify(n)===JSON.stringify(f),qn=(n,f,p)=>({...n,...f}),ke=e.forwardRef((n,f)=>{const{config:p,handlers:C={},showConflictUI:h=!0,uiPosition:N="modal",autoOpenUI:T=!0,onConflictDetected:P,onConflictResolved:i,onResolutionFailed:d,renderConflictList:b,renderConflictItem:L,children:x}=n,u={...Mn,...p},[y,A]=e.useState([]),[q,U]=e.useState(!1),[V,z]=e.useState(!1),Y=e.useCallback(I=>C[I]||{},[C]),B=e.useCallback(I=>({pending:I.filter(H=>H.status==="pending").length,resolving:I.filter(H=>H.status==="resolving").length,resolved:I.filter(H=>H.status==="resolved").length,failed:I.filter(H=>H.status==="failed").length}),[]),G={conflicts:y,isResolving:q,counts:B(y)},E=e.useCallback(()=>{if(u.persistConflicts)try{const I=localStorage.getItem(u.storageKey);if(I){const M=JSON.parse(I).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}));A(M)}}catch(I){console.warn("Failed to load persisted conflicts:",I)}},[u.persistConflicts,u.storageKey]),$=e.useCallback(I=>{if(u.persistConflicts)try{const H=I.filter(M=>M.status==="pending"||M.status==="failed");localStorage.setItem(u.storageKey,JSON.stringify(H))}catch(H){console.warn("Failed to persist conflicts:",H)}},[u.persistConflicts,u.storageKey]);e.useEffect(()=>{E()},[E]),e.useEffect(()=>{$(y)},[y,$]);const R=e.useCallback((I,H,M,X,v)=>{const J=Y(I),Q=J.compare||$n,K=J.hash||Bn,Z=J.getConflictingFields;if(Q(M.data,X.data)||M.timestamp<X.timestamp&&v&&Q(M.data,v.data))return null;const ee={id:Fn(),entityType:I,entityId:H,clientVersion:{...M,hash:K(M.data)},serverVersion:{...X,hash:K(X.data)},baseVersion:v?{...v,hash:K(v.data)}:void 0,status:"pending",createdAt:new Date,conflictingFields:Z?Z(M.data,X.data):void 0};return k(ee),ee},[Y]),k=e.useCallback(I=>{A(H=>{const M=H.findIndex(v=>v.entityType===I.entityType&&v.entityId===I.entityId);let X;return M>=0?(X=[...H],X[M]=I):X=[...H,I],X.length>u.maxPendingConflicts&&(X=X.slice(-u.maxPendingConflicts)),X}),P==null||P(I),T&&h&&z(!0),u.autoResolve&&u.defaultStrategy!=="manual"&&S(I.id,u.defaultStrategy)},[u.maxPendingConflicts,u.autoResolve,u.defaultStrategy,T,h,P]),S=e.useCallback(async(I,H,M)=>{var Q;const X=y.findIndex(K=>K.id===I);if(X===-1)return;const v=y[X],J=Y(v.entityType);U(!0),A(K=>{const Z=[...K];return Z[X]={...v,status:"resolving"},Z});try{let K;switch(H){case"client-wins":K=v.clientVersion.data;break;case"server-wins":K=v.serverVersion.data;break;case"latest-wins":K=v.clientVersion.timestamp>v.serverVersion.timestamp?v.clientVersion.data:v.serverVersion.data;break;case"merge":{K=await(J.merge||qn)(v.clientVersion.data,v.serverVersion.data,(Q=v.baseVersion)==null?void 0:Q.data);break}case"manual":if(M===void 0)throw new Error("Manual resolution requires merged data");K=M;break}const Z={...v,status:"resolved",resolvedVersion:{data:K,timestamp:new Date,source:H==="client-wins"?"client":"server"},resolvedWith:H,resolvedAt:new Date};A(ee=>{const te=[...ee];return te[X]=Z,te}),i==null||i(Z)}catch(K){const Z=K instanceof Error?K.message:"Resolution failed";A(ee=>{const te=[...ee];return te[X]={...v,status:"failed",error:Z},te}),d==null||d(v,K instanceof Error?K:new Error(Z))}finally{U(!1)}},[y,Y,i,d]),D=e.useCallback(async I=>{const H=y.filter(M=>M.status==="pending");for(const M of H)await S(M.id,I)},[y,S]),c=e.useCallback(I=>y.find(H=>H.id===I),[y]),s=e.useCallback((I,H)=>y.filter(M=>M.entityType===I&&(H===void 0||M.entityId===H)),[y]),a=e.useCallback(()=>y.filter(I=>I.status==="pending"),[y]),r=e.useCallback(I=>{A(H=>H.filter(M=>M.id!==I))},[]),o=e.useCallback(()=>{A(I=>I.filter(H=>H.status!=="resolved"))},[]),l=e.useCallback(()=>{A([])},[]),j=e.useCallback(()=>z(!0),[]),F=e.useCallback(()=>z(!1),[]);e.useImperativeHandle(f,()=>({getState:()=>G,detectConflict:R,addConflict:k,resolveConflict:S,resolveAll:D,getConflict:c,getConflictsByEntity:s,getPendingConflicts:a,dismissConflict:r,clearResolved:o,clearAll:l,openUI:j,closeUI:F}),[G,R,k,S,D,c,s,a,r,o,l,j,F]);const g={...G,detectConflict:R,addConflict:k,resolveConflict:S,resolveAll:D,getConflict:c,getConflictsByEntity:s,getPendingConflicts:a,dismissConflict:r,clearResolved:o,clearAll:l},m=a(),w=(I,H,M)=>{S(I,H,M)},O=I=>{r(I)},_=I=>L?L({conflict:I,onResolve:(H,M)=>w(I.id,H,M),onDismiss:()=>O(I.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:I.entityType}),t.jsxs("span",{className:"nice-conflict-item__id",children:["ID: ",I.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:I.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:I.serverVersion.timestamp.toLocaleString()})]})]}),I.conflictingFields&&I.conflictingFields.length>0&&t.jsxs("div",{className:"nice-conflict-item__fields",children:[t.jsx("span",{children:"Conflicting fields:"}),I.conflictingFields.map(H=>t.jsx("code",{children:H},H))]}),t.jsxs("div",{className:"nice-conflict-item__actions",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>w(I.id,"client-wins"),disabled:q,children:"Keep Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>w(I.id,"server-wins"),disabled:q,children:"Use Server"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--merge",onClick:()=>w(I.id,"merge"),disabled:q,children:"Merge"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--dismiss",onClick:()=>O(I.id),disabled:q,children:"Dismiss"})]})]},I.id),W=()=>{if(!h||!V||m.length===0)return null;if(b)return b({conflicts:m,onResolve:w,onDismiss:O});const I=t.jsxs("div",{className:"nice-conflict-list",children:[t.jsxs("div",{className:"nice-conflict-list__header",children:[t.jsxs("h3",{children:["Sync Conflicts (",m.length,")"]}),t.jsx("button",{className:"nice-conflict-list__close",onClick:F,"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:m.map(_)}),m.length>1&&t.jsxs("div",{className:"nice-conflict-list__bulk",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>D("client-wins"),disabled:q,children:"Keep All Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>D("server-wins"),disabled:q,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:I})});case"drawer":return t.jsx("div",{className:"nice-conflict-drawer nice-conflict-drawer--open",children:I});case"toast":return t.jsx("div",{className:"nice-conflict-toast",children:I});case"inline":default:return I}};return t.jsxs(ft.Provider,{value:g,children:[x,W()]})});ke.displayName="NiceConflictResolution";const mt=ke;mt.displayName="NiceConflictResolutionProvider";const ht=e.createContext(null),gt=()=>{const n=e.useContext(ht);if(!n)throw new Error("useIndexedDB must be used within NiceIndexedDBProvider");return n};function Un(n){const f=gt(),p=e.useCallback(u=>f.get(n,u),[f,n]),C=e.useCallback(u=>f.getAll(n,u),[f,n]),h=e.useCallback((u,y)=>f.add(n,u,y),[f,n]),N=e.useCallback((u,y)=>f.put(n,u,y),[f,n]),T=e.useCallback(u=>f.delete(n,u),[f,n]),P=e.useCallback(()=>f.clear(n),[f,n]),i=e.useCallback(u=>f.count(n,u),[f,n]),d=e.useCallback(u=>f.query(n,u),[f,n]),b=e.useCallback(u=>f.bulkAdd(n,u),[f,n]),L=e.useCallback(u=>f.bulkPut(n,u),[f,n]),x=e.useCallback(u=>f.bulkDelete(n,u),[f,n]);return{isOpen:f.isOpen,isLoading:f.isLoading,error:f.error,get:p,getAll:C,add:h,put:N,remove:T,clear:P,count:i,query:d,bulkAdd:b,bulkPut:L,bulkDelete:x}}const Se=e.forwardRef((n,f)=>{const{config:p,autoOpen:C=!0,onOpen:h,onError:N,onClose:T,children:P}=n,i=e.useRef(null),[d,b]=e.useState({isOpen:!1,isLoading:!1,storeNames:[]}),L=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,a)=>{const r=indexedDB.open(p.dbName,p.version);r.onerror=()=>{var l;const o=new Error(((l=r.error)==null?void 0:l.message)||"Failed to open database");b(j=>({...j,isLoading:!1,error:o.message})),N==null||N(o),a(o)},r.onblocked=()=>{var o;(o=p.onBlocked)==null||o.call(p)},r.onupgradeneeded=o=>{var g;const l=r.result,j=o.oldVersion,F=o.newVersion;for(const m of p.stores)if(!l.objectStoreNames.contains(m.name)){const w=l.createObjectStore(m.name,{keyPath:m.keyPath,autoIncrement:m.autoIncrement});if(m.indexes)for(const O of m.indexes)w.createIndex(O.name,O.keyPath,O.options)}(g=p.onUpgrade)==null||g.call(p,l,j,F)},r.onsuccess=()=>{const o=r.result;i.current=o,o.onclose=()=>{i.current=null,b(l=>({...l,isOpen:!1,db:void 0})),T==null||T()},o.onerror=l=>{var F;const j=l.target;N==null||N(new Error(((F=j.error)==null?void 0:F.message)||"Database error"))},b({db:o,isOpen:!0,isLoading:!1,version:o.version,storeNames:Array.from(o.objectStoreNames)}),h==null||h(o),s(o)}})},[p,h,N,T]),x=e.useCallback(()=>{i.current&&(i.current.close(),i.current=null,b(s=>({...s,isOpen:!1,db:void 0})),T==null||T())},[T]),u=e.useCallback(async()=>(x(),new Promise((s,a)=>{const r=indexedDB.deleteDatabase(p.dbName);r.onerror=()=>{var o;a(new Error(((o=r.error)==null?void 0:o.message)||"Failed to delete database"))},r.onsuccess=()=>{b({isOpen:!1,isLoading:!1,storeNames:[]}),s()}})),[p.dbName,x]),y=e.useCallback(async()=>i.current?i.current:L(),[L]),A=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const g=r.transaction(s,"readonly").objectStore(s).get(a);g.onerror=()=>{var m;return l(new Error((m=g.error)==null?void 0:m.message))},g.onsuccess=()=>o(g.result)})},[y]),q=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const F=r.transaction(s,"readonly").objectStore(s),m=(a!=null&&a.index?F.index(a.index):F).getAll(a==null?void 0:a.range,a==null?void 0:a.limit);m.onerror=()=>{var w;return l(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>{let w=m.result;a!=null&&a.offset&&(w=w.slice(a.offset)),o(w)}})},[y]),U=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const F=r.transaction(s,"readonly").objectStore(s),m=(a!=null&&a.index?F.index(a.index):F).getAllKeys(a==null?void 0:a.range,a==null?void 0:a.limit);m.onerror=()=>{var w;return l(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>o(m.result)})},[y]),V=e.useCallback(async(s,a,r)=>{const o=await y();return new Promise((l,j)=>{const m=o.transaction(s,"readwrite").objectStore(s).add(a,r);m.onerror=()=>{var w;return j(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>l(m.result)})},[y]),z=e.useCallback(async(s,a,r)=>{const o=await y();return new Promise((l,j)=>{const m=o.transaction(s,"readwrite").objectStore(s).put(a,r);m.onerror=()=>{var w;return j(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>l(m.result)})},[y]),Y=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const g=r.transaction(s,"readwrite").objectStore(s).delete(a);g.onerror=()=>{var m;return l(new Error((m=g.error)==null?void 0:m.message))},g.onsuccess=()=>o()})},[y]),B=e.useCallback(async s=>{const a=await y();return new Promise((r,o)=>{const F=a.transaction(s,"readwrite").objectStore(s).clear();F.onerror=()=>{var g;return o(new Error((g=F.error)==null?void 0:g.message))},F.onsuccess=()=>r()})},[y]),G=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const g=r.transaction(s,"readonly").objectStore(s).count(a);g.onerror=()=>{var m;return l(new Error((m=g.error)==null?void 0:m.message))},g.onsuccess=()=>o(g.result)})},[y]),E=e.useCallback(async(s,a)=>{const r=await y(),o=[];return new Promise((l,j)=>{const g=r.transaction(s,"readonly").objectStore(s),w=(a.index?g.index(a.index):g).openCursor(a.range,a.direction);let O=0,_=0;w.onerror=()=>{var W;return j(new Error((W=w.error)==null?void 0:W.message))},w.onsuccess=()=>{const W=w.result;if(W){if(a.offset&&O<a.offset){O++,W.continue();return}if(a.limit&&_>=a.limit){l(o);return}o.push(W.value),_++,W.continue()}else l(o)}})},[y]),$=e.useCallback(async(s,a)=>{const o=(await y()).transaction(s.stores,s.mode||"readwrite");return new Promise((l,j)=>{o.onerror=()=>{var F;return j(new Error((F=o.error)==null?void 0:F.message))},o.onabort=()=>j(new Error("Transaction aborted")),a(o).then(F=>{o.oncomplete=()=>l(F)}).catch(j)})},[y]),R=e.useCallback(async(s,a)=>{const r=await y(),o=[];return new Promise((l,j)=>{const F=r.transaction(s,"readwrite"),g=F.objectStore(s);F.onerror=()=>{var m;return j(new Error((m=F.error)==null?void 0:m.message))},F.oncomplete=()=>l(o);for(const m of a){const w=g.add(m);w.onsuccess=()=>o.push(w.result)}})},[y]),k=e.useCallback(async(s,a)=>{const r=await y(),o=[];return new Promise((l,j)=>{const F=r.transaction(s,"readwrite"),g=F.objectStore(s);F.onerror=()=>{var m;return j(new Error((m=F.error)==null?void 0:m.message))},F.oncomplete=()=>l(o);for(const m of a){const w=g.put(m);w.onsuccess=()=>o.push(w.result)}})},[y]),S=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const j=r.transaction(s,"readwrite"),F=j.objectStore(s);j.onerror=()=>{var g;return l(new Error((g=j.error)==null?void 0:g.message))},j.oncomplete=()=>o();for(const g of a)F.delete(g)})},[y]),D=e.useCallback(async()=>{const s=await y(),a=[];for(const r of s.objectStoreNames){const l=s.transaction(r,"readonly").objectStore(r);a.push({name:l.name,keyPath:l.keyPath,autoIncrement:l.autoIncrement,indexNames:Array.from(l.indexNames)})}return{name:s.name,version:s.version,stores:a}},[y]);e.useEffect(()=>(C&&L().catch(()=>{}),()=>{x()}),[C,L,x]),e.useImperativeHandle(f,()=>({getState:()=>d,open:L,close:x,deleteDatabase:u,get:A,getAll:q,getAllKeys:U,add:V,put:z,delete:Y,clear:B,count:G,query:E,transaction:$,bulkAdd:R,bulkPut:k,bulkDelete:S,getInfo:D}),[d,L,x,u,A,q,U,V,z,Y,B,G,E,$,R,k,S,D]);const c={...d,open:L,close:x,deleteDatabase:u,get:A,getAll:q,getAllKeys:U,add:V,put:z,delete:Y,clear:B,count:G,query:E,transaction:$,bulkAdd:R,bulkPut:k,bulkDelete:S};return t.jsx(ht.Provider,{value:c,children:P})});Se.displayName="NiceIndexedDB";const pt=Se;pt.displayName="NiceIndexedDBProvider";const yt=e.createContext(null),bt=()=>{const n=e.useContext(yt);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)}`,_e=e.forwardRef((n,f)=>{const{config:p,submitHandlers:C={},onDraftSaved:h,onFormSubmitted:N,onSubmissionFailed:T,onSyncComplete:P,children:i}=n,d={...Hn,...p},b=e.useRef(null),L=e.useRef(C),[x,u]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,draftCounts:{},pendingCount:0,failedCount:0}),y=e.useCallback(async()=>b.current?b.current:new Promise((s,a)=>{const r=indexedDB.open(d.dbName,1);r.onerror=()=>a(r.error),r.onupgradeneeded=()=>{const o=r.result;if(!o.objectStoreNames.contains("drafts")){const l=o.createObjectStore("drafts",{keyPath:"id"});l.createIndex("formId","formId",{unique:!1}),l.createIndex("status","status",{unique:!1})}},r.onsuccess=()=>{b.current=r.result,s(r.result)}}),[d.dbName]),A=e.useCallback(async(s,a,r)=>{const o=await y(),l={id:Wn(),formId:s,data:a,status:"draft",createdAt:new Date,modifiedAt:new Date,attempts:0,version:1,submittedOffline:!1,metadata:r};return new Promise((j,F)=>{const w=o.transaction("drafts","readwrite").objectStore("drafts").add(l);w.onerror=()=>F(w.error),w.onsuccess=()=>{h==null||h(l),D(),j(l.id)}})},[y,h]),q=e.useCallback(async s=>{const a=await y();return new Promise((r,o)=>{const F=a.transaction("drafts","readonly").objectStore("drafts").get(s);F.onerror=()=>o(F.error),F.onsuccess=()=>{const g=F.result;g&&(g.createdAt=new Date(g.createdAt),g.modifiedAt=new Date(g.modifiedAt),g.syncedAt&&(g.syncedAt=new Date(g.syncedAt))),r(g)}})},[y]),U=e.useCallback(async s=>{const a=await y();return new Promise((r,o)=>{const g=a.transaction("drafts","readonly").objectStore("drafts").index("formId").getAll(s);g.onerror=()=>o(g.error),g.onsuccess=()=>{const m=g.result.map(w=>({...w,createdAt:new Date(w.createdAt),modifiedAt:new Date(w.modifiedAt),syncedAt:w.syncedAt?new Date(w.syncedAt):void 0}));r(m)}})},[y]),V=e.useCallback(async()=>{const s=await y();return new Promise((a,r)=>{const j=s.transaction("drafts","readonly").objectStore("drafts").getAll();j.onerror=()=>r(j.error),j.onsuccess=()=>{const F=j.result.filter(g=>g.status==="pending"||g.status==="failed").map(g=>({...g,createdAt:new Date(g.createdAt),modifiedAt:new Date(g.modifiedAt),syncedAt:g.syncedAt?new Date(g.syncedAt):void 0}));a(F)}})},[y]),z=e.useCallback(async(s,a)=>{const r=await q(s);if(!r)return;const o=await y(),l={...r,data:{...r.data,...a},modifiedAt:new Date,version:r.version+1};return new Promise((j,F)=>{const w=o.transaction("drafts","readwrite").objectStore("drafts").put(l);w.onerror=()=>F(w.error),w.onsuccess=()=>{h==null||h(l),j()}})},[y,q,h]),Y=e.useCallback(async(s,a,r)=>{const o=await q(s);if(!o)return;const l=await y(),j={...o,status:a,error:r,attempts:a==="syncing"?o.attempts+1:o.attempts,syncedAt:a==="synced"?new Date:o.syncedAt};return new Promise((F,g)=>{const O=l.transaction("drafts","readwrite").objectStore("drafts").put(j);O.onerror=()=>g(O.error),O.onsuccess=()=>{D(),F()}})},[y,q]),B=e.useCallback(async s=>{const a=await y();return new Promise((r,o)=>{const F=a.transaction("drafts","readwrite").objectStore("drafts").delete(s);F.onerror=()=>o(F.error),F.onsuccess=()=>{D(),r()}})},[y]),G=e.useCallback(async s=>{const a=await U(s),r=await y();return new Promise((o,l)=>{const j=r.transaction("drafts","readwrite"),F=j.objectStore("drafts");j.onerror=()=>l(j.error),j.oncomplete=()=>{D(),o()};for(const g of a)F.delete(g.id)})},[y,U]),E=e.useCallback(async s=>{const a=await q(s);if(!a)throw new Error("Draft not found");const r=L.current[a.formId];if(!r)throw new Error(`No handler registered for form: ${a.formId}`);if(!x.isOnline){await Y(s,"pending");return}await Y(s,"syncing"),u(o=>({...o,isSyncing:!0}));try{await r(a.data,a),await Y(s,"synced"),N==null||N(a),await B(s)}catch(o){const l=o instanceof Error?o.message:"Submission failed";await Y(s,"failed",l),T==null||T(a,o instanceof Error?o:new Error(l))}finally{u(o=>({...o,isSyncing:!1}))}},[q,x.isOnline,Y,B,N,T]),$=e.useCallback(async(s,a)=>{const r=await A(s,a);await Y(r,"pending"),await E(r)},[A,Y,E]),R=e.useCallback(async()=>{const s=await V(),a={synced:0,failed:0};u(r=>({...r,isSyncing:!0}));for(const r of s)if(!(r.status==="failed"&&r.attempts>=d.maxRetryAttempts))try{await E(r.id),a.synced++}catch{a.failed++}return u(r=>({...r,isSyncing:!1,lastSyncAt:new Date})),P==null||P(a),a},[V,E,d.maxRetryAttempts,P]),k=e.useCallback(async()=>{const a=(await V()).filter(r=>r.status==="failed");for(const r of a)r.attempts<d.maxRetryAttempts&&await Y(r.id,"pending");await R()},[V,d.maxRetryAttempts,Y,R]),S=e.useCallback((s,a)=>{L.current[s]=a},[]),D=e.useCallback(async()=>{try{const o=(await y()).transaction("drafts","readonly").objectStore("drafts").getAll();o.onsuccess=()=>{const l=o.result,j={};for(const m of l)j[m.formId]=(j[m.formId]||0)+1;const F=l.filter(m=>m.status==="pending").length,g=l.filter(m=>m.status==="failed").length;u(m=>({...m,draftCounts:j,pendingCount:F,failedCount:g}))}}catch{}},[y]);e.useEffect(()=>{const s=()=>{u(r=>({...r,isOnline:!0})),d.autoSubmitOnline&&R()},a=()=>{u(r=>({...r,isOnline:!1}))};return window.addEventListener("online",s),window.addEventListener("offline",a),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",a)}},[d.autoSubmitOnline,R]),e.useEffect(()=>{y().then(()=>D())},[y,D]),e.useImperativeHandle(f,()=>({getState:()=>x,saveDraft:A,getDraft:q,getDrafts:U,getPendingDrafts:V,updateDraft:z,deleteDraft:B,submitDraft:E,submitForm:$,syncPending:R,retryFailed:k,clearDrafts:G,registerHandler:S}),[x,A,q,U,V,z,B,E,$,R,k,G,S]);const c={...x,saveDraft:A,getDraft:q,getDrafts:U,getPendingDrafts:V,updateDraft:z,deleteDraft:B,submitDraft:E,submitForm:$,syncPending:R,retryFailed:k,clearDrafts:G,registerHandler:S};return t.jsx(yt.Provider,{value:c,children:i})});_e.displayName="NiceOfflineForms";const wt=_e;wt.displayName="NiceOfflineFormsProvider";function Vn(n){const{formId:f,initialData:p={},autoSave:C=!0,autoSaveInterval:h=5e3,onSubmit:N}=n,T=bt(),[P,i]=e.useState(p),[d,b]=e.useState(),[L,x]=e.useState(!1),[u,y]=e.useState();e.useEffect(()=>{T.registerHandler(f,N)},[T,f,N]),e.useEffect(()=>{if(!C)return;const z=setInterval(async()=>{if(Object.keys(P).length>0)if(d)await T.updateDraft(d,P);else{const Y=await T.saveDraft(f,P);b(Y)}},h);return()=>clearInterval(z)},[C,h,P,d,f,T]);const A=e.useCallback(z=>{const{name:Y,value:B,type:G}=z.target;i(E=>({...E,[Y]:G==="checkbox"?z.target.checked:B}))},[]),q=e.useCallback(async z=>{z==null||z.preventDefault(),x(!0),y(void 0);try{await T.submitForm(f,P),i(p),b(void 0)}catch(Y){y(Y instanceof Error?Y.message:"Submission failed")}finally{x(!1)}},[T,f,P,p]),U=e.useCallback(()=>{i(p),y(void 0),d&&(T.deleteDraft(d),b(void 0))},[p,d,T]),V=e.useCallback(async z=>{const Y=await T.getDraft(z);Y&&(i(Y.data),b(z))},[T]);return{data:P,setData:i,draftId:d,isSubmitting:L,error:u,isOnline:T.isOnline,isSyncing:T.isSyncing,pendingCount:T.pendingCount,handleChange:A,handleSubmit:q,reset:U,loadDraft:V}}const de=()=>{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}:{}},fe=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}},vt=e.forwardRef((n,f)=>{const{mode:p="banner",position:C="top",showWhenOnline:h=!1,autoHideOnlineDelay:N=3e3,showSlowConnectionWarning:T=!0,slowConnectionThreshold:P=1,showReconnecting:i=!0,reconnectCheckInterval:d=5e3,offlineMessage:b="You're offline",onlineMessage:L="Back online",slowConnectionMessage:x="Slow connection",reconnectingMessage:u="Reconnecting...",showDetails:y=!1,animated:A=!0,pulseWhenOffline:q=!0,offlineIcon:U,onlineIcon:V,slowIcon:z,renderContent:Y,onStatusChange:B,onReconnect:G,className:E,style:$}=n,[R,k]=e.useState(()=>{const v=de();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...v,quality:fe(v)}}),[S,D]=e.useState(!R.isOnline||h),[c,s]=e.useState(!1),[a,r]=e.useState(null),o=e.useCallback(()=>{const v=de(),J=navigator.onLine;k(Q=>{const K={isOnline:J,...v,quality:J?fe(v):0,lastOnlineAt:J?new Date:Q.lastOnlineAt,offlineDuration:!J&&a?Date.now()-a.getTime():void 0};return(Q.isOnline!==K.isOnline||Q.quality!==K.quality)&&(B==null||B(K)),K})},[a,B]),l=e.useCallback(async()=>{try{return(await fetch("/favicon.ico",{method:"HEAD",cache:"no-store"})).ok}catch{return!1}},[]);e.useEffect(()=>{const v=()=>{s(!1),r(null),o(),D(!0),G==null||G(),N>0&&setTimeout(()=>{D(h)},N)},J=()=>{r(new Date),o(),D(!0),s(i)};window.addEventListener("online",v),window.addEventListener("offline",J);const Q=navigator;return Q.connection&&Q.connection.addEventListener("change",o),()=>{window.removeEventListener("online",v),window.removeEventListener("offline",J),Q.connection&&Q.connection.removeEventListener("change",o)}},[o,N,h,i,G]),e.useEffect(()=>{if(!c||R.isOnline)return;const v=setInterval(async()=>{await l()&&window.dispatchEvent(new Event("online"))},d);return()=>clearInterval(v)},[c,R.isOnline,d,l]),e.useEffect(()=>{if(R.isOnline||!a)return;const v=setInterval(()=>{k(J=>({...J,offlineDuration:Date.now()-a.getTime()}))},1e3);return()=>clearInterval(v)},[R.isOnline,a]),e.useImperativeHandle(f,()=>({getConnectionInfo:()=>R,checkConnection:l,show:()=>D(!0),hide:()=>D(!1),toggle:()=>D(v=>!v)}),[R,l]);const j=R.isOnline&&T&&R.downlink!==void 0&&R.downlink<P,g=R.isOnline?j?"slow":"online":c?"reconnecting":"offline",m=()=>{switch(g){case"offline":return b;case"reconnecting":return u;case"slow":return x;case"online":return L}},w=v=>({display:"inline-block",width:10,height:10,borderRadius:"50%",background:v}),O=()=>{switch(g){case"offline":case"reconnecting":return U||t.jsx("span",{style:w("var(--nice-color-error, #ef4444)")});case"slow":return z||t.jsx("span",{style:w("var(--nice-color-warning, #f59e0b)")});case"online":return V||t.jsx("span",{style:w("var(--nice-color-success, #22c55e)")})}},_=v=>{const J=Math.floor(v/1e3);if(J<60)return`${J}s`;const Q=Math.floor(J/60);return Q<60?`${Q}m ${J%60}s`:`${Math.floor(Q/60)}h ${Q%60}m`};if(!S||R.isOnline&&!h&&!j)return null;const W=["nice-offline-indicator",`nice-offline-indicator--${p}`,`nice-offline-indicator--${C}`,`nice-offline-indicator--${g}`,A&&"nice-offline-indicator--animated",q&&g==="offline"&&"nice-offline-indicator--pulse",E].filter(Boolean).join(" ");if(Y)return t.jsx("div",{className:W,style:$,children:Y(R)});const I=()=>t.jsx("span",{className:"nice-offline-indicator__icon",children:O()}),H=()=>t.jsx("span",{className:"nice-offline-indicator__message",children:m()}),M=()=>y?t.jsxs("div",{className:"nice-offline-indicator__details",children:[R.offlineDuration!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__duration",children:["Offline for ",_(R.offlineDuration)]}),R.effectiveType&&t.jsx("span",{className:"nice-offline-indicator__type",children:R.effectiveType.toUpperCase()}),R.downlink!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__speed",children:[R.downlink.toFixed(1)," Mbps"]}),R.rtt!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__latency",children:[R.rtt,"ms"]})]}):null,X=()=>!y||!R.isOnline?null:t.jsx("div",{className:"nice-offline-indicator__quality",children:t.jsx("div",{className:"nice-offline-indicator__quality-bar",style:{width:`${R.quality}%`,backgroundColor:R.quality>=75?"var(--nice-color-success, #22c55e)":R.quality>=50?"var(--nice-color-warning, #eab308)":"var(--nice-color-error, #ef4444)"}})});switch(p){case"icon-only":return t.jsx("div",{className:W,style:$,title:m(),children:I()});case"minimal":return t.jsxs("div",{className:W,style:$,children:[I(),H()]});case"badge":return t.jsxs("div",{className:W,style:$,children:[t.jsx("div",{className:"nice-offline-indicator__badge-dot"}),t.jsx("span",{className:"nice-offline-indicator__badge-text",children:m()})]});case"toast":return t.jsx("div",{className:W,style:$,children:t.jsxs("div",{className:"nice-offline-indicator__toast",children:[I(),t.jsxs("div",{className:"nice-offline-indicator__toast-content",children:[H(),M()]})]})});case"detailed":return t.jsx("div",{className:W,style:$,children:t.jsxs("div",{className:"nice-offline-indicator__detailed",children:[I(),t.jsxs("div",{className:"nice-offline-indicator__detailed-content",children:[H(),M(),X()]})]})});case"banner":default:return t.jsx("div",{className:W,style:$,children:t.jsxs("div",{className:"nice-offline-indicator__banner",children:[I(),H(),y&&t.jsxs(t.Fragment,{children:[M(),c&&t.jsx("span",{className:"nice-offline-indicator__spinner"})]})]})})}});vt.displayName="NiceOfflineIndicator";function zn(){const[n,f]=e.useState(()=>{const p=de();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...p,quality:fe(p)}});return e.useEffect(()=>{const p=()=>{const h=de();f(N=>({...N,isOnline:navigator.onLine,...h,quality:navigator.onLine?fe(h):0,lastOnlineAt:navigator.onLine?new Date:N.lastOnlineAt}))};window.addEventListener("online",p),window.addEventListener("offline",p);const C=navigator;return C.connection&&C.connection.addEventListener("change",p),()=>{window.removeEventListener("online",p),window.removeEventListener("offline",p),C.connection&&C.connection.removeEventListener("change",p)}},[]),n}const xt=e.createContext(null),Ct=()=>{const n=e.useContext(xt);if(!n)throw new Error("useOfflineMedia must be used within NiceOfflineMediaProvider");return n},Gn={dbName:"nice-offline-media",maxCacheSize:500*1024*1024,maxConcurrentDownloads:3,autoResumeOnReconnect:!0,defaultCacheDuration:10080*60*1e3,autoCleanup:!0,cleanupInterval:3600*1e3},Yn=()=>`media-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Xn=(n,f)=>{var h;const p=((h=n.split(".").pop())==null?void 0:h.toLowerCase())||"",C=(f==null?void 0:f.toLowerCase())||"";return C.startsWith("image/")||["jpg","jpeg","png","gif","webp","svg"].includes(p)?"image":C.startsWith("video/")||["mp4","webm","ogg","mov","avi"].includes(p)?"video":C.startsWith("audio/")||["mp3","wav","ogg","flac","m4a"].includes(p)?"audio":["pdf","doc","docx","xls","xlsx","ppt","pptx"].includes(p)?"document":"other"},Kn=n=>{try{return new URL(n).pathname.split("/").pop()||"unknown"}catch{return n.split("/").pop()||"unknown"}},Ne=e.forwardRef((n,f)=>{const{config:p,onDownloadStart:C,onDownloadProgress:h,onDownloadComplete:N,onDownloadFailed:T,onMediaRemoved:P,children:i}=n,d={...Gn,...p},b=e.useRef(null),L=e.useRef(new Map),x=e.useRef(new Map),[u,y]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,activeDownloads:0,queuedDownloads:0,cachedCount:0,totalCacheSize:0,isDownloading:!1}),A=e.useCallback(async()=>b.current?b.current:new Promise((O,_)=>{const W=indexedDB.open(d.dbName,1);W.onerror=()=>_(W.error),W.onupgradeneeded=()=>{const I=W.result;if(!I.objectStoreNames.contains("media")){const H=I.createObjectStore("media",{keyPath:"id"});H.createIndex("url","url",{unique:!0}),H.createIndex("type","type",{unique:!1}),H.createIndex("status","status",{unique:!1})}I.objectStoreNames.contains("blobs")||I.createObjectStore("blobs",{keyPath:"id"})},W.onsuccess=()=>{b.current=W.result,O(W.result)}}),[d.dbName]),q=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const X=_.transaction("media","readwrite").objectStore("media").put(O);X.onerror=()=>I(X.error),X.onsuccess=()=>W()})},[A]),U=e.useCallback(async(O,_)=>{const W=await A();return new Promise((I,H)=>{const v=W.transaction("blobs","readwrite").objectStore("blobs").put({id:O,blob:_});v.onerror=()=>H(v.error),v.onsuccess=()=>I()})},[A]),V=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const X=_.transaction("blobs","readonly").objectStore("blobs").get(O);X.onerror=()=>I(X.error),X.onsuccess=()=>{var v;return W((v=X.result)==null?void 0:v.blob)}})},[A]),z=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const X=_.transaction("media","readonly").objectStore("media").get(O);X.onerror=()=>I(X.error),X.onsuccess=()=>{const v=X.result;v&&(v.cachedAt=v.cachedAt?new Date(v.cachedAt):void 0,v.expiresAt=v.expiresAt?new Date(v.expiresAt):void 0),W(v)}})},[A]),Y=e.useCallback(async()=>{const O=await A();return new Promise((_,W)=>{const M=O.transaction("media","readonly").objectStore("media").getAll();M.onerror=()=>W(M.error),M.onsuccess=()=>{_(M.result.map(X=>({...X,cachedAt:X.cachedAt?new Date(X.cachedAt):void 0,expiresAt:X.expiresAt?new Date(X.expiresAt):void 0})))}})},[A]),B=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const v=_.transaction("media","readonly").objectStore("media").index("type").getAll(O);v.onerror=()=>I(v.error),v.onsuccess=()=>W(v.result)})},[A]),G=e.useCallback(async O=>(await Y()).filter(W=>{var I;return(I=W.tags)==null?void 0:I.includes(O)}),[Y]),E=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const v=_.transaction("media","readonly").objectStore("media").index("url").get(O);v.onerror=()=>I(v.error),v.onsuccess=()=>W(v.result)})},[A]),$=e.useCallback(async O=>{const _=await E(O);return(_==null?void 0:_.status)==="completed"},[E]),R=e.useCallback(async O=>{const _=x.current.get(O);if(_)return _;const W=await V(O);if(!W)return;const I=URL.createObjectURL(W);return x.current.set(O,I),I},[V]),k=e.useCallback(async(O,_)=>{var X;const W=await E(O);if((W==null?void 0:W.status)==="completed")return W.id;const I=new AbortController,H=(W==null?void 0:W.id)||Yn(),M={id:H,url:O,type:(_==null?void 0:_.type)||"other",name:(_==null?void 0:_.name)||Kn(O),mimeType:"",size:0,status:"queued",progress:0,downloadedBytes:0,metadata:_==null?void 0:_.metadata,tags:_==null?void 0:_.tags,priority:_==null?void 0:_.priority};L.current.set(H,I),await q(M),C==null||C(M),y(v=>({...v,queuedDownloads:v.queuedDownloads+1,isDownloading:!0}));try{M.status="downloading",await q(M),y(re=>({...re,activeDownloads:re.activeDownloads+1,queuedDownloads:re.queuedDownloads-1}));const v=await fetch(O,{signal:I.signal,headers:_==null?void 0:_.headers});if(!v.ok)throw new Error(`HTTP ${v.status}`);const J=v.headers.get("content-length"),Q=v.headers.get("content-type")||"",K=J?parseInt(J,10):0;M.size=K,M.mimeType=Q,M.type=(_==null?void 0:_.type)||Xn(O,Q);const Z=(X=v.body)==null?void 0:X.getReader();if(!Z)throw new Error("No response body");const ee=[];let te=0;for(;;){const{done:re,value:ie}=await Z.read();if(re)break;ee.push(ie),te+=ie.length,M.downloadedBytes=te,M.progress=K>0?Math.round(te/K*100):0,await q(M),h==null||h(M)}const ne=new Blob(ee,{type:Q});return await U(H,ne),M.status="completed",M.progress=100,M.size=ne.size,M.cachedAt=new Date,M.expiresAt=_!=null&&_.cacheDuration?new Date(Date.now()+_.cacheDuration):new Date(Date.now()+d.defaultCacheDuration),await q(M),N==null||N(M),H}catch(v){throw v.name==="AbortError"?M.status="cancelled":(M.status="failed",M.error=v instanceof Error?v.message:"Download failed",T==null||T(M,v instanceof Error?v:new Error(String(v)))),await q(M),v}finally{L.current.delete(H),y(v=>({...v,activeDownloads:Math.max(0,v.activeDownloads-1),isDownloading:v.activeDownloads>1})),await m()}},[E,q,U,d.defaultCacheDuration,C,h,N,T]),S=e.useCallback(async O=>{const _=[];for(let W=0;W<O.length;W+=d.maxConcurrentDownloads){const I=O.slice(W,W+d.maxConcurrentDownloads),H=await Promise.allSettled(I.map(M=>k(M.url,M.options)));for(const M of H)M.status==="fulfilled"&&_.push(M.value)}return _},[k,d.maxConcurrentDownloads]),D=e.useCallback(O=>{const _=L.current.get(O);_&&_.abort()},[]),c=e.useCallback(async O=>{const _=await z(O);_&&(_.status==="paused"||_.status==="failed")&&await k(_.url,{type:_.type,name:_.name,metadata:_.metadata,tags:_.tags})},[z,k]),s=e.useCallback(O=>{D(O)},[D]),a=e.useCallback(()=>{for(const[O]of L.current)D(O)},[D]),r=e.useCallback(async()=>{const _=(await Y()).filter(W=>W.status==="paused"||W.status==="failed");await S(_.map(W=>({url:W.url})))},[Y,S]),o=e.useCallback(async O=>{const _=await A(),W=x.current.get(O);W&&(URL.revokeObjectURL(W),x.current.delete(O)),await new Promise((I,H)=>{const M=_.transaction(["media","blobs"],"readwrite");M.objectStore("media").delete(O),M.objectStore("blobs").delete(O),M.onerror=()=>H(M.error),M.oncomplete=()=>I()}),P==null||P(O),await m()},[A,P]),l=e.useCallback(async()=>{const O=await A();for(const[,_]of x.current)URL.revokeObjectURL(_);x.current.clear(),await new Promise((_,W)=>{const I=O.transaction(["media","blobs"],"readwrite");I.objectStore("media").clear(),I.objectStore("blobs").clear(),I.onerror=()=>W(I.error),I.oncomplete=()=>_()}),await m()},[A]),j=e.useCallback(async()=>{const O=await Y(),_=Date.now();let W=0;for(const I of O)I.expiresAt&&I.expiresAt.getTime()<_&&(await o(I.id),W++);return W},[Y,o]),F=e.useCallback(async()=>{const _=(await Y()).filter(H=>H.status==="completed"),W={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 I=0;for(const H of _)I+=H.size,W[H.type].count++,W[H.type].size+=H.size;return{totalSize:I,itemCount:_.length,byType:W}},[Y]),g=e.useCallback(async O=>{await S(O.map(_=>({url:_,options:{priority:-1}})))},[S]),m=e.useCallback(async()=>{const O=await F();y(_=>({..._,cachedCount:O.itemCount,totalCacheSize:O.totalSize}))},[F]);e.useEffect(()=>{const O=()=>{y(W=>({...W,isOnline:!0})),d.autoResumeOnReconnect&&r()},_=()=>{y(W=>({...W,isOnline:!1})),a()};return window.addEventListener("online",O),window.addEventListener("offline",_),()=>{window.removeEventListener("online",O),window.removeEventListener("offline",_)}},[d.autoResumeOnReconnect,r,a]),e.useEffect(()=>{if(!d.autoCleanup)return;const O=setInterval(()=>{j()},d.cleanupInterval);return()=>clearInterval(O)},[d.autoCleanup,d.cleanupInterval,j]),e.useEffect(()=>{A().then(()=>m());const O=x.current;return()=>{for(const[,_]of O)URL.revokeObjectURL(_)}},[A,m]),e.useImperativeHandle(f,()=>({getState:()=>u,download:k,downloadMultiple:S,getCachedMedia:z,getAllCachedMedia:Y,getMediaByType:B,getMediaByTag:G,getBlobUrl:R,isCached:$,pauseDownload:D,resumeDownload:c,cancelDownload:s,pauseAll:a,resumeAll:r,removeMedia:o,clearCache:l,clearExpired:j,getCacheStats:F,preload:g}),[u,k,S,z,Y,B,G,R,$,D,c,s,a,r,o,l,j,F,g]);const w={...u,download:k,downloadMultiple:S,getCachedMedia:z,getAllCachedMedia:Y,getMediaByType:B,getMediaByTag:G,getBlobUrl:R,isCached:$,pauseDownload:D,resumeDownload:c,cancelDownload:s,removeMedia:o,clearCache:l,preload:g};return t.jsx(xt.Provider,{value:w,children:i})});Ne.displayName="NiceOfflineMedia";const kt=Ne;kt.displayName="NiceOfflineMediaProvider";function Qn(n){const f=Ct(),[p,C]=e.useState(),[h,N]=e.useState(),[T,P]=e.useState(!1);return e.useEffect(()=>{n&&(P(!0),Promise.all([f.getCachedMedia(n),f.getBlobUrl(n)]).then(([i,d])=>{C(i),N(d)}).finally(()=>{P(!1)}))},[n,f]),{item:p,blobUrl:h,isLoading:T,isOnline:f.isOnline}}const St=e.createContext(null),Jn=()=>{const n=e.useContext(St);if(!n)throw new Error("useServiceWorker must be used within NiceServiceWorkerProvider");return n},Zn={swPath:"/service-worker.js",scope:"/",updateCheckInterval:6e4,autoUpdate:!1,skipWaiting:!1,reloadOnActivation:!0},Ie=e.forwardRef((n,f)=>{const{config:p,showUpdateNotification:C=!0,showOfflineIndicator:h=!0,renderUpdateNotification:N,renderOfflineIndicator:T,notificationPosition:P="bottom",autoDismissDelay:i=0,onRegistered:d,onUpdateAvailable:b,onActivated:L,onError:x,onOnlineStatusChange:u,children:y,className:A}=n,q={...Zn,...p},{swPath:U,scope:V,updateCheckInterval:z,autoUpdate:Y,reloadOnActivation:B}=q,G=q.skipWaiting,E=e.useMemo(()=>({swPath:U,scope:V,updateCheckInterval:z,autoUpdate:Y,skipWaiting:G,reloadOnActivation:B}),[U,V,z,Y,G,B]),$=e.useRef({onRegistered:d,onUpdateAvailable:b,onActivated:L,onError:x});e.useEffect(()=>{$.current={onRegistered:d,onUpdateAvailable:b,onActivated:L,onError:x}});const[R,k]=e.useState({status:"idle",updateAvailable:!1,waitingWorker:!1,cachedUrls:[],caches:[],isOnline:typeof navigator<"u"?navigator.onLine:!0}),[S,D]=e.useState(!1);e.useEffect(()=>{const I=()=>{k(M=>({...M,isOnline:!0})),u==null||u(!0)},H=()=>{k(M=>({...M,isOnline:!1})),u==null||u(!1)};return window.addEventListener("online",I),window.addEventListener("offline",H),()=>{window.removeEventListener("online",I),window.removeEventListener("offline",H)}},[u]);const c=e.useCallback(async()=>{if(!("caches"in window))return[];const I=await caches.keys(),H=[];for(const M of I){const X=await caches.open(M),v=await X.keys();let J=0;for(const Q of v){const K=await X.match(Q);if(K){const Z=await K.clone().blob();J+=Z.size}}H.push({name:M,size:J,itemCount:v.length})}return k(M=>({...M,caches:H})),H},[]),s=e.useCallback(async I=>{if(!("caches"in window))return!1;const H=await caches.delete(I);return await c(),H},[c]),a=e.useCallback(async()=>{if(!("caches"in window))return;const I=await caches.keys();await Promise.all(I.map(H=>caches.delete(H))),k(H=>({...H,caches:[],cachedUrls:[]}))},[]),r=e.useCallback(async(I,H)=>{if(!("caches"in window))return;await(await caches.open(I)).addAll(H),await c()},[c]),o=e.useCallback(async(I,H)=>{if(!("caches"in window))return!1;const X=await(await caches.open(I)).delete(H);return await c(),X},[c]),l=e.useCallback(async I=>"caches"in window?(await(await caches.open(I)).keys()).map(X=>X.url):[],[]),j=e.useCallback(async()=>{var H,M,X,v,J,Q;if(!("serviceWorker"in navigator)){k(K=>({...K,status:"error",error:"Service Worker not supported"}));return}k(K=>({...K,status:"registering"}));const I=!!navigator.serviceWorker.controller;try{const K=await navigator.serviceWorker.register(E.swPath,{scope:E.scope});k(ee=>({...ee,status:"registered",registration:K})),(M=(H=$.current).onRegistered)==null||M.call(H,K),K.addEventListener("updatefound",()=>{const ee=K.installing;ee&&ee.addEventListener("statechange",()=>{var te,ne,re,ie;switch(ee.state){case"installing":k(se=>({...se,status:"installing"}));break;case"installed":navigator.serviceWorker.controller?(k(se=>({...se,status:"installed",updateAvailable:!0,waitingWorker:!0})),D(!0),(ne=(te=$.current).onUpdateAvailable)==null||ne.call(te)):k(se=>({...se,status:"installed"}));break;case"activating":k(se=>({...se,status:"activating"}));break;case"activated":k(se=>({...se,status:"activated",updateAvailable:!1,waitingWorker:!1})),(ie=(re=$.current).onActivated)==null||ie.call(re),E.reloadOnActivation&&I&&window.location.reload();break;case"redundant":k(se=>({...se,status:"redundant"}));break}})}),K.waiting&&(k(ee=>({...ee,updateAvailable:!0,waitingWorker:!0})),D(!0),(v=(X=$.current).onUpdateAvailable)==null||v.call(X));let Z=!1;return navigator.serviceWorker.addEventListener("controllerchange",()=>{!Z&&E.reloadOnActivation&&(Z=!0,window.location.reload())}),await c(),K}catch(K){const Z=K instanceof Error?K.message:"Registration failed";k(ee=>({...ee,status:"error",error:Z})),(Q=(J=$.current).onError)==null||Q.call(J,K instanceof Error?K:new Error(Z));return}},[E,c]),F=e.useCallback(async()=>{if(!R.registration)return!1;const I=await R.registration.unregister();return I&&k(H=>({...H,status:"idle",registration:void 0,updateAvailable:!1,waitingWorker:!1})),I},[R.registration]),g=e.useCallback(async()=>{R.registration&&await R.registration.update()},[R.registration]),m=e.useCallback(()=>{var I;(I=R.registration)!=null&&I.waiting&&R.registration.waiting.postMessage({type:"SKIP_WAITING"})},[R.registration]),w=e.useCallback(()=>{E.skipWaiting&&m(),D(!1)},[E.skipWaiting,m]),O=e.useCallback(()=>{window.location.reload()},[]);e.useEffect(()=>{j()},[j]),e.useEffect(()=>{if(!E.updateCheckInterval||E.updateCheckInterval<=0)return;const I=setInterval(()=>{g()},E.updateCheckInterval);return()=>clearInterval(I)},[E.updateCheckInterval,g]),e.useEffect(()=>{if(!S||i<=0)return;const I=setTimeout(()=>{D(!1)},i);return()=>clearTimeout(I)},[S,i]),e.useImperativeHandle(f,()=>({getState:()=>R,register:j,unregister:F,checkForUpdates:g,applyUpdate:w,skipWaiting:m,getCachesInfo:c,clearCache:s,clearAllCaches:a,addToCache:r,removeFromCache:o,getCachedUrls:l,forceReload:O}),[R,j,F,g,w,m,c,s,a,r,o,l,O]);const _={...R,register:j,unregister:F,checkForUpdates:g,applyUpdate:w,skipWaiting:m,getCachesInfo:c,clearCache:s,clearAllCaches:a,addToCache:r,removeFromCache:o,getCachedUrls:l},W=`nice-sw-notification--${P}`;return t.jsx(St.Provider,{value:_,children:t.jsxs("div",{className:`nice-service-worker ${A||""}`,children:[y,C&&S&&R.updateAvailable&&t.jsx("div",{className:`nice-sw-notification ${W}`,children:N?N({onUpdate:w,onDismiss:()=>D(!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:w,children:"Update Now"}),t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--secondary",onClick:()=>D(!1),children:"Later"})]})]})}),h&&!R.isOnline&&t.jsx("div",{className:`nice-sw-offline ${W}`,children:T?T({isOnline:R.isOnline}):t.jsx("div",{className:"nice-sw-offline__content",children:t.jsx("span",{children:"You are offline"})})})]})})});Ie.displayName="NiceServiceWorker";const _t=e.forwardRef((n,f)=>t.jsx(Ie,{...n,ref:f}));_t.displayName="NiceServiceWorkerProvider";exports.NiceAutoStart=he;exports.NiceAutoStartProvider=Te;exports.NiceBackgroundSync=xe;exports.NiceBackgroundSyncProvider=ot;exports.NiceBarcodeScanner=tt;exports.NiceBatchScanner=st;exports.NiceBatchScannerProvider=yn;exports.NiceCacheStrategies=Ce;exports.NiceCacheStrategiesProvider=dt;exports.NiceConflictResolution=ke;exports.NiceConflictResolutionProvider=mt;exports.NiceExternalDisplay=ge;exports.NiceExternalDisplayProvider=Be;exports.NiceHardwareBarcodeGenerator=et;exports.NiceHardwareQRGenerator=rt;exports.NiceIndexedDB=Se;exports.NiceIndexedDBProvider=pt;exports.NiceKioskMode=pe;exports.NiceKioskModeProvider=Ue;exports.NiceLowPowerMode=ye;exports.NiceLowPowerModeProvider=We;exports.NiceOfflineForms=_e;exports.NiceOfflineFormsProvider=wt;exports.NiceOfflineIndicator=vt;exports.NiceOfflineMedia=Ne;exports.NiceOfflineMediaProvider=kt;exports.NiceOrientationLock=be;exports.NiceOrientationLockProvider=Ge;exports.NiceQRScanner=at;exports.NiceRemoteManagement=we;exports.NiceRemoteManagementProvider=Xe;exports.NiceScreenBurnPrevention=Ke;exports.NiceScreenSelector=$e;exports.NiceServiceWorker=Ie;exports.NiceServiceWorkerProvider=_t;exports.NiceSymbologyConfig=it;exports.NiceSymbologyProvider=jn;exports.NiceTouchCalibration=Qe;exports.useAutoStart=jt;exports.useBackgroundSync=An;exports.useBatchScanner=fn;exports.useCacheStrategies=ut;exports.useCachedFetch=On;exports.useConflictResolution=Tn;exports.useConnectionStatus=zn;exports.useExternalDisplay=Fe;exports.useIndexedDB=gt;exports.useIndexedDBStore=Un;exports.useKioskMode=Ot;exports.useLowPowerMode=Mt;exports.useOfflineForm=Vn;exports.useOfflineForms=bt;exports.useOfflineMedia=Ct;exports.useOfflineMediaItem=Qn;exports.useOrientationLock=$t;exports.useRemoteManagement=Wt;exports.useServiceWorker=Jn;exports.useSymbology=In;
|