@nice2dev/ui-platform 1.0.11 → 1.0.12

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 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(v=>v.map(U=>U.id===c?{...U,state:"error"}:U)),null;u.current.set(c,h);const w={...y,window:h,state:"open"};g(v=>v.map(U=>U.id===c?w:U));const T=setInterval(()=>{h.closed&&(clearInterval(T),u.current.delete(c),g(v=>v.filter(U=>U.id!==c)),N==null||N(w))},500);return l.fullscreen&&h.addEventListener("load",()=>{var v,U;(U=(v=h.document.documentElement).requestFullscreen)==null||U.call(v)}),p==null||p(w),w}catch(h){return console.error("Failed to open window:",h),g(w=>w.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:5*60*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 w=f.current;if(w)try{w.requestFullscreen?await w.requestFullscreen():w.webkitRequestFullscreen?await w.webkitRequestFullscreen():w.msRequestFullscreen&&await w.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(w){console.warn("Failed to exit fullscreen:",w)}},[]),H=e.useCallback(async()=>{B.isFullscreen?await P():await z()},[B.isFullscreen,z,P]),d=e.useCallback(()=>{L(w=>({...w,mode:"locked",isLocked:!0,isAdminMode:!1})),O==null||O("locked")},[O]),I=e.useCallback(w=>b.exitPin&&w!==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(w=>({...w,isAdminMode:!0})),o==null||o()},[o]),R=e.useCallback(()=>{L(w=>({...w,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(w=>({...w,isScreensaverActive:!1})),S==null||S()),b.inactivityTimeout>0&&(g.current=setTimeout(()=>{L(w=>({...w,isScreensaverActive:!0})),u==null||u()},b.inactivityTimeout))},[b.inactivityTimeout,B.isScreensaverActive,S,u]),n=e.useCallback(()=>{L(w=>({...w,isScreensaverActive:!0}))},[]),s=e.useCallback(()=>{L(w=>({...w,isScreensaverActive:!1})),a()},[a]),r=e.useCallback(()=>{L(w=>({...w,isPinDialogOpen:!0})),W(""),F(!1)},[]),c=e.useCallback(()=>{L(w=>({...w,isPinDialogOpen:!1})),W(""),F(!1)},[]),l=e.useCallback(()=>{I(M)},[M,I]),_=e.useCallback(w=>{w.key==="Enter"&&l()},[l]);e.useEffect(()=>{const w=()=>{const T=!!document.fullscreenElement;L(v=>({...v,mode:v.isLocked?"locked":T?"fullscreen":"windowed",isFullscreen:T})),q==null||q(T)};return document.addEventListener("fullscreenchange",w),document.addEventListener("webkitfullscreenchange",w),()=>{document.removeEventListener("fullscreenchange",w),document.removeEventListener("webkitfullscreenchange",w)}},[q]),e.useEffect(()=>{if(!b.disableContextMenu)return;const w=T=>{B.isAdminMode||T.preventDefault()};return document.addEventListener("contextmenu",w),()=>document.removeEventListener("contextmenu",w)},[b.disableContextMenu,B.isAdminMode]),e.useEffect(()=>{const w=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",w),()=>document.removeEventListener("keydown",w)},[b.disableShortcuts,b.exitShortcut,B.isAdminMode,B.isLocked,P,r,D]),e.useEffect(()=>{if(!b.disableCopyPaste)return;const w=v=>{B.isAdminMode||v.preventDefault()},T=v=>{B.isAdminMode||v.preventDefault()};return document.addEventListener("copy",w),document.addEventListener("paste",T),()=>{document.removeEventListener("copy",w),document.removeEventListener("paste",T)}},[b.disableCopyPaste,B.isAdminMode]),e.useEffect(()=>{const w=["mousedown","mousemove","keydown","touchstart","scroll"],T=()=>{a()};for(const v of w)document.addEventListener(v,T);return a(),()=>{for(const v of w)document.removeEventListener(v,T);g.current&&clearTimeout(g.current)}},[a]),e.useEffect(()=>{if(b.autoFullscreen){const w=setTimeout(()=>{z()},100);return()=>clearTimeout(w)}},[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:w=>W(w.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:2*60*1e3,autoSleepTimeout:10*60*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:5*60*1e3,pixelShift:{maxShift:3,interval:6e4,smooth:!0},colorCycle:{colors:["var(--text-primary, #000000)","#111111","#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,w,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:v}=o.pixelShift,U=Math.floor(Math.random()*(v*2+1))-v,$=Math.floor(Math.random()*(v*2+1))-v;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(v=>({...v,shiftX:0,shiftY:0}))},[]),z=e.useCallback(()=>{!o.colorCycle||b.current||(b.current=setInterval(()=>{B(v=>{var U;return(v+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 v=o.modes;g(U=>({...U,isActive:!0,activeModes:v})),v.includes("pixel-shift")&&X(),v.includes("color-cycling")&&z(),v.includes("dimming")&&g(U=>({...U,isDimmed:!0})),v.includes("screensaver")&&g(U=>({...U,isScreensaverActive:!0})),p==null||p(),O==null||O(v)},[k,f.isActive,o.modes,X,z,p,O]),d=e.useCallback(()=>{f.isActive&&(F(),P(),g(v=>({...v,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(v=>({...v,isScreensaverActive:!0}))},[]),i=e.useCallback(()=>{g(v=>({...v,isScreensaverActive:!1})),E()},[E]),a=e.useCallback(v=>{g(U=>({...U,isDimmed:v>0}))},[]);e.useEffect(()=>{var U;if(!f.isScreensaverActive||((U=o.screensaver)==null?void 0:U.type)!=="bounce")return;const v=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(v)},[f.isScreensaverActive,(l=o.screensaver)==null?void 0:l.type]),e.useEffect(()=>{if(!k)return;const v=["mousedown","mousemove","keydown","touchstart","scroll","wheel"],U=()=>{E()};for(const $ of v)document.addEventListener($,U);return E(),()=>{for(const $ of v)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 v=o.screensaver||{type:"blank"};switch(v.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:v.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:(w=o.colorCycle)==null?void 0:w.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,w=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,w+=Y*Q}const T=y!==0?_/y:1,v=w!==0?h/w:1,U=s-T*c,$=r-v*l;return{scaleX:T,scaleY:v,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:"#ffffff",lineColor:"#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 w=o.textPosition==="top"?R+o.textMargin:c-i-o.textMargin;P.fillText(x,h,w)}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 w=o.textPosition==="top"?d+o.fontSize:s-I-o.textMargin;_=`<text x="${h}" y="${w}" 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}">
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(v=>v.map(U=>U.id===c?{...U,state:"error"}:U)),null;u.current.set(c,h);const w={...y,window:h,state:"open"};g(v=>v.map(U=>U.id===c?w:U));const T=setInterval(()=>{h.closed&&(clearInterval(T),u.current.delete(c),g(v=>v.filter(U=>U.id!==c)),N==null||N(w))},500);return l.fullscreen&&h.addEventListener("load",()=>{var v,U;(U=(v=h.document.documentElement).requestFullscreen)==null||U.call(v)}),p==null||p(w),w}catch(h){return console.error("Failed to open window:",h),g(w=>w.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:5*60*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 w=f.current;if(w)try{w.requestFullscreen?await w.requestFullscreen():w.webkitRequestFullscreen?await w.webkitRequestFullscreen():w.msRequestFullscreen&&await w.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(w){console.warn("Failed to exit fullscreen:",w)}},[]),H=e.useCallback(async()=>{B.isFullscreen?await P():await z()},[B.isFullscreen,z,P]),d=e.useCallback(()=>{L(w=>({...w,mode:"locked",isLocked:!0,isAdminMode:!1})),O==null||O("locked")},[O]),I=e.useCallback(w=>b.exitPin&&w!==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(w=>({...w,isAdminMode:!0})),o==null||o()},[o]),R=e.useCallback(()=>{L(w=>({...w,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(w=>({...w,isScreensaverActive:!1})),S==null||S()),b.inactivityTimeout>0&&(g.current=setTimeout(()=>{L(w=>({...w,isScreensaverActive:!0})),u==null||u()},b.inactivityTimeout))},[b.inactivityTimeout,B.isScreensaverActive,S,u]),n=e.useCallback(()=>{L(w=>({...w,isScreensaverActive:!0}))},[]),s=e.useCallback(()=>{L(w=>({...w,isScreensaverActive:!1})),a()},[a]),r=e.useCallback(()=>{L(w=>({...w,isPinDialogOpen:!0})),W(""),F(!1)},[]),c=e.useCallback(()=>{L(w=>({...w,isPinDialogOpen:!1})),W(""),F(!1)},[]),l=e.useCallback(()=>{I(M)},[M,I]),_=e.useCallback(w=>{w.key==="Enter"&&l()},[l]);e.useEffect(()=>{const w=()=>{const T=!!document.fullscreenElement;L(v=>({...v,mode:v.isLocked?"locked":T?"fullscreen":"windowed",isFullscreen:T})),q==null||q(T)};return document.addEventListener("fullscreenchange",w),document.addEventListener("webkitfullscreenchange",w),()=>{document.removeEventListener("fullscreenchange",w),document.removeEventListener("webkitfullscreenchange",w)}},[q]),e.useEffect(()=>{if(!b.disableContextMenu)return;const w=T=>{B.isAdminMode||T.preventDefault()};return document.addEventListener("contextmenu",w),()=>document.removeEventListener("contextmenu",w)},[b.disableContextMenu,B.isAdminMode]),e.useEffect(()=>{const w=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",w),()=>document.removeEventListener("keydown",w)},[b.disableShortcuts,b.exitShortcut,B.isAdminMode,B.isLocked,P,r,D]),e.useEffect(()=>{if(!b.disableCopyPaste)return;const w=v=>{B.isAdminMode||v.preventDefault()},T=v=>{B.isAdminMode||v.preventDefault()};return document.addEventListener("copy",w),document.addEventListener("paste",T),()=>{document.removeEventListener("copy",w),document.removeEventListener("paste",T)}},[b.disableCopyPaste,B.isAdminMode]),e.useEffect(()=>{const w=["mousedown","mousemove","keydown","touchstart","scroll"],T=()=>{a()};for(const v of w)document.addEventListener(v,T);return a(),()=>{for(const v of w)document.removeEventListener(v,T);g.current&&clearTimeout(g.current)}},[a]),e.useEffect(()=>{if(b.autoFullscreen){const w=setTimeout(()=>{z()},100);return()=>clearTimeout(w)}},[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:w=>W(w.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:2*60*1e3,autoSleepTimeout:10*60*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:5*60*1e3,pixelShift:{maxShift:3,interval:6e4,smooth:!0},colorCycle:{colors:["var(--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,w,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:v}=o.pixelShift,U=Math.floor(Math.random()*(v*2+1))-v,$=Math.floor(Math.random()*(v*2+1))-v;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(v=>({...v,shiftX:0,shiftY:0}))},[]),z=e.useCallback(()=>{!o.colorCycle||b.current||(b.current=setInterval(()=>{B(v=>{var U;return(v+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 v=o.modes;g(U=>({...U,isActive:!0,activeModes:v})),v.includes("pixel-shift")&&X(),v.includes("color-cycling")&&z(),v.includes("dimming")&&g(U=>({...U,isDimmed:!0})),v.includes("screensaver")&&g(U=>({...U,isScreensaverActive:!0})),p==null||p(),O==null||O(v)},[k,f.isActive,o.modes,X,z,p,O]),d=e.useCallback(()=>{f.isActive&&(F(),P(),g(v=>({...v,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(v=>({...v,isScreensaverActive:!0}))},[]),i=e.useCallback(()=>{g(v=>({...v,isScreensaverActive:!1})),E()},[E]),a=e.useCallback(v=>{g(U=>({...U,isDimmed:v>0}))},[]);e.useEffect(()=>{var U;if(!f.isScreensaverActive||((U=o.screensaver)==null?void 0:U.type)!=="bounce")return;const v=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(v)},[f.isScreensaverActive,(l=o.screensaver)==null?void 0:l.type]),e.useEffect(()=>{if(!k)return;const v=["mousedown","mousemove","keydown","touchstart","scroll","wheel"],U=()=>{E()};for(const $ of v)document.addEventListener($,U);return E(),()=>{for(const $ of v)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 v=o.screensaver||{type:"blank"};switch(v.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:v.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:(w=o.colorCycle)==null?void 0:w.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,w=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,w+=Y*Q}const T=y!==0?_/y:1,v=w!==0?h/w:1,U=s-T*c,$=r-v*l;return{scaleX:T,scaleY:v,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 w=o.textPosition==="top"?R+o.textMargin:c-i-o.textMargin;P.fillText(x,h,w)}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 w=o.textPosition==="top"?d+o.fontSize:s-I-o.textMargin;_=`<text x="${h}" y="${w}" 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
2
  <rect width="100%" height="100%" fill="${o.background}"/>
3
3
  ${r.join(`
4
4
  `)}
5
5
  ${_}
6
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]),w=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]),v=e.useCallback(()=>{X(!1),L.current&&(clearInterval(L.current),L.current=null),_()},[_]),U=e.useCallback(async()=>{W?v():await T()},[W,T,v]),$=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(w,b.scanInterval)),()=>{L.current&&(clearInterval(L.current),L.current=null)}),[W,F,b.continuous,b.scanInterval,w]),e.useEffect(()=>(u&&T(),()=>{v()}),[]),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:v,toggle:U,takeSnapshot:$,switchCamera:y,requestPermission:c}),[W,F,P,d,r,E,T,v,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]),w=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(()=>()=>{w()},[w]);const T=e.useCallback(()=>{E.trim()&&(r(E.trim()),R(""))},[E,r]),v=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
- `)},[F]),U=e.useCallback(()=>JSON.stringify(F,null,2),[F]),$=e.useCallback(()=>{w(),O==null||O(F)},[F,w,O]);e.useImperativeHandle(A,()=>({startScanning:h,stopScanning:w,getItems:()=>F,addItem:(C,Q)=>r(C,Q),removeItem:c,updateQuantity:l,clearAll:_,exportCSV:v,exportJSON:U,isScanning:()=>P}),[h,w,F,r,c,l,_,v,U,P]);const G={items:F,isScanning:P,addItem:(C,Q)=>r(C,Q),removeItem:c,updateQuantity:l,clearAll:_,startScanning:h,stopScanning:w},V=F.reduce((C,Q)=>C+Q.quantity,0),Y=["nice-batch-scanner",P&&"nice-batch-scanner--scanning",D].filter(Boolean).join(" ");return t.jsx(Tt.Provider,{value:G,children:t.jsxs("div",{className:Y,children:[t.jsxs("div",{className:"nice-batch-scanner__scanner",children:[t.jsx("video",{ref:g,className:"nice-batch-scanner__video",playsInline:!0,muted:!0,autoPlay:!0}),t.jsx("canvas",{ref:j,className:"nice-batch-scanner__canvas"}),g.current&&i.map((C,Q)=>{const K=g.current,J=K.clientWidth/K.videoWidth,Z=K.clientHeight/K.videoHeight;return t.jsx("div",{className:"nice-batch-scanner__bounding-box",style:{left:C.x*J,top:C.y*Z,width:C.width*J,height:C.height*Z}},Q)}),P&&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"})]}),n&&t.jsx("div",{className:"nice-batch-scanner__error",children:t.jsx("span",{children:n})}),!P&&!n&&t.jsxs("div",{className:"nice-batch-scanner__placeholder",children:[t.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",width:"64",height:"64",children:t.jsx("path",{d:"M4 4h6v6H4zm10 0h6v6h-6zM4 14h6v6H4zm13 0h-3v2h3v3h2v-5zm0 5h-5v2h5zm-5-5h-2v5h2zm8-10v6h-2V6h-4V4h6z"})}),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--${P?"stop":"start"}`,onClick:P?w:h,children:P?"Stop Scanning":"Start Scanning"}),f.allowManualEntry&&t.jsxs("div",{className:"nice-batch-scanner__manual",children:[t.jsx("input",{type:"text",value:E,onChange:C=>R(C.target.value),onKeyDown:C=>C.key==="Enter"&&T(),placeholder:"Enter code manually...",className:"nice-batch-scanner__manual-input"}),t.jsx("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--add",onClick:T,disabled:!E.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:F.length})," unique items"]}),t.jsxs("span",{className:"nice-batch-scanner__total",children:[t.jsx("strong",{children:V})," total quantity"]})]}),t.jsxs("div",{className:"nice-batch-scanner__items",children:[F.map(C=>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:C.value}),t.jsx("span",{className:"nice-batch-scanner__item-format",children:C.format})]}),t.jsxs("div",{className:"nice-batch-scanner__item-quantity",children:[t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>l(C.id,C.quantity-1),children:"−"}),t.jsx("span",{className:"nice-batch-scanner__qty-value",children:C.quantity}),t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>l(C.id,C.quantity+1),children:"+"})]}),t.jsx("button",{className:"nice-batch-scanner__item-remove",onClick:()=>c(C.id),"aria-label":"Remove item",children:"×"})]},C.id)),F.length===0&&t.jsx("div",{className:"nice-batch-scanner__empty",children:"No items scanned yet"})]}),F.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:_,children:"Clear All"}),t.jsxs("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--primary",onClick:$,children:["Complete Batch (",V,")"]})]}),b]})})});Be.displayName="NiceBatchScanner";const $t={errorCorrection:"M",size:200,margin:2,darkColor:"#000000",lightColor:"#ffffff",logoSize:.2,logoMargin:1,cornerRadius:0},qt={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]},Ut=(m,A)=>{const x=m.length,k=qt[A];for(let p=0;p<k.length;p++)if(k[p]>=x)return p+1;return 10},Ie=(m,A)=>{const x=Ut(m,A),k=x*4+17,p=Array(k).fill(null).map(()=>Array(k).fill(!1)),N=Array(k).fill(null).map(()=>Array(k).fill(!1)),O=(u,S)=>{for(let D=-1;D<=7;D++)for(let b=-1;b<=7;b++){const f=u+D,g=S+b;f<0||f>=k||g<0||g>=k||(N[f][g]=!0,D===-1||D===7||b===-1||b===7?p[f][g]=!1:D===0||D===6||b===0||b===6||D>=2&&D<=4&&b>=2&&b<=4?p[f][g]=!0:p[f][g]=!1)}};O(0,0),O(0,k-7),O(k-7,0);for(let u=8;u<k-8;u++)p[6][u]=u%2===0,p[u][6]=u%2===0,N[6][u]=!0,N[u][6]=!0;if(x>=2){const u=[6,k-7];x>=7&&u.splice(1,0,Math.floor(k/2));for(const S of u)for(const D of u)if(!(S<9&&D<9||S<9&&D>k-10||S>k-10&&D<9))for(let b=-2;b<=2;b++)for(let f=-2;f<=2;f++){const g=S+b,j=D+f;g<0||g>=k||j<0||j>=k||(N[g][j]=!0,p[g][j]=b===-2||b===2||f===-2||f===2||b===0&&f===0)}}const q=m.split("").reduce((u,S)=>(u<<5)-u+S.charCodeAt(0),0);let o=0;for(let u=k-1;u>=0;u-=2){u===6&&(u=5);for(let S=0;S<k;S++)for(let D=0;D<=1;D++){const b=u-D;if(N[S][b])continue;const f=o%m.length,g=m.charCodeAt(f)&1<<o%8,j=(q+S*k+b)%256>127;p[S][b]=g!==0!==j,o++}}return p},$e=e.forwardRef((m,A)=>{const{value:x,options:k,onGenerate:p,onError:N,showBorder:O=!1,className:q}=m,o={...$t,...k},u=e.useRef(null),S=e.useRef(null),[D,b]=e.useState(null),[f,g]=e.useState(!(k!=null&&k.logo));e.useEffect(()=>{if(k!=null&&k.logo){const F=new Image;F.crossOrigin="anonymous",F.onload=()=>{S.current=F,g(!0)},F.onerror=()=>{S.current=null,g(!0)},F.src=k.logo}else S.current=null,g(!0)},[k==null?void 0:k.logo]);const j=e.useCallback(()=>{if(!u.current||!x||!f)return;const F=u.current,z=F.getContext("2d");if(z)try{const P=Ie(x,o.errorCorrection),H=P.length,d=Math.floor((o.size-o.margin*2)/H),I=H*d+o.margin*2*d;F.width=I,F.height=I,z.fillStyle=o.lightColor,z.fillRect(0,0,I,I),z.fillStyle=o.darkColor;const E=o.margin*d;for(let i=0;i<H;i++)for(let a=0;a<H;a++)if(P[i][a]){const n=E+a*d,s=E+i*d;if(o.cornerRadius>0){const r=Math.min(o.cornerRadius,d/2);z.beginPath(),z.roundRect(n,s,d,d,r),z.fill()}else z.fillRect(n,s,d,d)}if(S.current){const i=I*o.logoSize,a=(I-i)/2,n=(I-i)/2,s=o.logoMargin*d;z.fillStyle=o.lightColor,z.fillRect(a-s,n-s,i+s*2,i+s*2),z.drawImage(S.current,a,n,i,i)}const R=F.toDataURL("image/png");b(null),p==null||p(R)}catch(P){const H=P instanceof Error?P.message:"Failed to generate QR code";b(H),N==null||N(new Error(H))}},[x,o,f,p,N]);e.useEffect(()=>{j()},[j]);const B=e.useCallback((F="image/png",z=1)=>{var P;return((P=u.current)==null?void 0:P.toDataURL(F,z))||null},[]),L=e.useCallback(()=>{if(!u.current||!x)return null;try{const F=Ie(x,o.errorCorrection),z=F.length,P=Math.floor((o.size-o.margin*2)/z),H=z*P+o.margin*2*P,d=o.margin*P,I=[];for(let E=0;E<z;E++)for(let R=0;R<z;R++)if(F[E][R]){const i=d+R*P,a=d+E*P;if(o.cornerRadius>0){const n=Math.min(o.cornerRadius,P/2);I.push(`<rect x="${i}" y="${a}" width="${P}" height="${P}" rx="${n}" fill="${o.darkColor}"/>`)}else I.push(`<rect x="${i}" y="${a}" width="${P}" height="${P}" fill="${o.darkColor}"/>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${H}" height="${H}" viewBox="0 0 ${H} ${H}">
7
+ `)},[F]),U=e.useCallback(()=>JSON.stringify(F,null,2),[F]),$=e.useCallback(()=>{w(),O==null||O(F)},[F,w,O]);e.useImperativeHandle(A,()=>({startScanning:h,stopScanning:w,getItems:()=>F,addItem:(C,Q)=>r(C,Q),removeItem:c,updateQuantity:l,clearAll:_,exportCSV:v,exportJSON:U,isScanning:()=>P}),[h,w,F,r,c,l,_,v,U,P]);const G={items:F,isScanning:P,addItem:(C,Q)=>r(C,Q),removeItem:c,updateQuantity:l,clearAll:_,startScanning:h,stopScanning:w},V=F.reduce((C,Q)=>C+Q.quantity,0),Y=["nice-batch-scanner",P&&"nice-batch-scanner--scanning",D].filter(Boolean).join(" ");return t.jsx(Tt.Provider,{value:G,children:t.jsxs("div",{className:Y,children:[t.jsxs("div",{className:"nice-batch-scanner__scanner",children:[t.jsx("video",{ref:g,className:"nice-batch-scanner__video",playsInline:!0,muted:!0,autoPlay:!0}),t.jsx("canvas",{ref:j,className:"nice-batch-scanner__canvas"}),g.current&&i.map((C,Q)=>{const K=g.current,J=K.clientWidth/K.videoWidth,Z=K.clientHeight/K.videoHeight;return t.jsx("div",{className:"nice-batch-scanner__bounding-box",style:{left:C.x*J,top:C.y*Z,width:C.width*J,height:C.height*Z}},Q)}),P&&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"})]}),n&&t.jsx("div",{className:"nice-batch-scanner__error",children:t.jsx("span",{children:n})}),!P&&!n&&t.jsxs("div",{className:"nice-batch-scanner__placeholder",children:[t.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",width:"64",height:"64",children:t.jsx("path",{d:"M4 4h6v6H4zm10 0h6v6h-6zM4 14h6v6H4zm13 0h-3v2h3v3h2v-5zm0 5h-5v2h5zm-5-5h-2v5h2zm8-10v6h-2V6h-4V4h6z"})}),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--${P?"stop":"start"}`,onClick:P?w:h,children:P?"Stop Scanning":"Start Scanning"}),f.allowManualEntry&&t.jsxs("div",{className:"nice-batch-scanner__manual",children:[t.jsx("input",{type:"text",value:E,onChange:C=>R(C.target.value),onKeyDown:C=>C.key==="Enter"&&T(),placeholder:"Enter code manually...",className:"nice-batch-scanner__manual-input"}),t.jsx("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--add",onClick:T,disabled:!E.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:F.length})," unique items"]}),t.jsxs("span",{className:"nice-batch-scanner__total",children:[t.jsx("strong",{children:V})," total quantity"]})]}),t.jsxs("div",{className:"nice-batch-scanner__items",children:[F.map(C=>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:C.value}),t.jsx("span",{className:"nice-batch-scanner__item-format",children:C.format})]}),t.jsxs("div",{className:"nice-batch-scanner__item-quantity",children:[t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>l(C.id,C.quantity-1),children:"−"}),t.jsx("span",{className:"nice-batch-scanner__qty-value",children:C.quantity}),t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>l(C.id,C.quantity+1),children:"+"})]}),t.jsx("button",{className:"nice-batch-scanner__item-remove",onClick:()=>c(C.id),"aria-label":"Remove item",children:"×"})]},C.id)),F.length===0&&t.jsx("div",{className:"nice-batch-scanner__empty",children:"No items scanned yet"})]}),F.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:_,children:"Clear All"}),t.jsxs("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--primary",onClick:$,children:["Complete Batch (",V,")"]})]}),b]})})});Be.displayName="NiceBatchScanner";const $t={errorCorrection:"M",size:200,margin:2,darkColor:"var(--nice-text, #000000)",lightColor:"var(--nice-bg, #fff)",logoSize:.2,logoMargin:1,cornerRadius:0},qt={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]},Ut=(m,A)=>{const x=m.length,k=qt[A];for(let p=0;p<k.length;p++)if(k[p]>=x)return p+1;return 10},Ie=(m,A)=>{const x=Ut(m,A),k=x*4+17,p=Array(k).fill(null).map(()=>Array(k).fill(!1)),N=Array(k).fill(null).map(()=>Array(k).fill(!1)),O=(u,S)=>{for(let D=-1;D<=7;D++)for(let b=-1;b<=7;b++){const f=u+D,g=S+b;f<0||f>=k||g<0||g>=k||(N[f][g]=!0,D===-1||D===7||b===-1||b===7?p[f][g]=!1:D===0||D===6||b===0||b===6||D>=2&&D<=4&&b>=2&&b<=4?p[f][g]=!0:p[f][g]=!1)}};O(0,0),O(0,k-7),O(k-7,0);for(let u=8;u<k-8;u++)p[6][u]=u%2===0,p[u][6]=u%2===0,N[6][u]=!0,N[u][6]=!0;if(x>=2){const u=[6,k-7];x>=7&&u.splice(1,0,Math.floor(k/2));for(const S of u)for(const D of u)if(!(S<9&&D<9||S<9&&D>k-10||S>k-10&&D<9))for(let b=-2;b<=2;b++)for(let f=-2;f<=2;f++){const g=S+b,j=D+f;g<0||g>=k||j<0||j>=k||(N[g][j]=!0,p[g][j]=b===-2||b===2||f===-2||f===2||b===0&&f===0)}}const q=m.split("").reduce((u,S)=>(u<<5)-u+S.charCodeAt(0),0);let o=0;for(let u=k-1;u>=0;u-=2){u===6&&(u=5);for(let S=0;S<k;S++)for(let D=0;D<=1;D++){const b=u-D;if(N[S][b])continue;const f=o%m.length,g=m.charCodeAt(f)&1<<o%8,j=(q+S*k+b)%256>127;p[S][b]=g!==0!==j,o++}}return p},$e=e.forwardRef((m,A)=>{const{value:x,options:k,onGenerate:p,onError:N,showBorder:O=!1,className:q}=m,o={...$t,...k},u=e.useRef(null),S=e.useRef(null),[D,b]=e.useState(null),[f,g]=e.useState(!(k!=null&&k.logo));e.useEffect(()=>{if(k!=null&&k.logo){const F=new Image;F.crossOrigin="anonymous",F.onload=()=>{S.current=F,g(!0)},F.onerror=()=>{S.current=null,g(!0)},F.src=k.logo}else S.current=null,g(!0)},[k==null?void 0:k.logo]);const j=e.useCallback(()=>{if(!u.current||!x||!f)return;const F=u.current,z=F.getContext("2d");if(z)try{const P=Ie(x,o.errorCorrection),H=P.length,d=Math.floor((o.size-o.margin*2)/H),I=H*d+o.margin*2*d;F.width=I,F.height=I,z.fillStyle=o.lightColor,z.fillRect(0,0,I,I),z.fillStyle=o.darkColor;const E=o.margin*d;for(let i=0;i<H;i++)for(let a=0;a<H;a++)if(P[i][a]){const n=E+a*d,s=E+i*d;if(o.cornerRadius>0){const r=Math.min(o.cornerRadius,d/2);z.beginPath(),z.roundRect(n,s,d,d,r),z.fill()}else z.fillRect(n,s,d,d)}if(S.current){const i=I*o.logoSize,a=(I-i)/2,n=(I-i)/2,s=o.logoMargin*d;z.fillStyle=o.lightColor,z.fillRect(a-s,n-s,i+s*2,i+s*2),z.drawImage(S.current,a,n,i,i)}const R=F.toDataURL("image/png");b(null),p==null||p(R)}catch(P){const H=P instanceof Error?P.message:"Failed to generate QR code";b(H),N==null||N(new Error(H))}},[x,o,f,p,N]);e.useEffect(()=>{j()},[j]);const B=e.useCallback((F="image/png",z=1)=>{var P;return((P=u.current)==null?void 0:P.toDataURL(F,z))||null},[]),L=e.useCallback(()=>{if(!u.current||!x)return null;try{const F=Ie(x,o.errorCorrection),z=F.length,P=Math.floor((o.size-o.margin*2)/z),H=z*P+o.margin*2*P,d=o.margin*P,I=[];for(let E=0;E<z;E++)for(let R=0;R<z;R++)if(F[E][R]){const i=d+R*P,a=d+E*P;if(o.cornerRadius>0){const n=Math.min(o.cornerRadius,P/2);I.push(`<rect x="${i}" y="${a}" width="${P}" height="${P}" rx="${n}" fill="${o.darkColor}"/>`)}else I.push(`<rect x="${i}" y="${a}" width="${P}" height="${P}" fill="${o.darkColor}"/>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${H}" height="${H}" viewBox="0 0 ${H} ${H}">
8
8
  <rect width="100%" height="100%" fill="${o.lightColor}"/>
9
9
  ${I.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]),w=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]),v=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=v(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,v,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=v(te[0].rawValue,te[0]);J(ne)}else J(null)}catch{J(null)}},Z.onerror=()=>J(null),Z.src=URL.createObjectURL(K)}),[l,v]);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:w,takeSnapshot:Y,scanImage:C}),[L,W,F,P,l,d,i,n,$,G,V,h,w,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 v=l.transaction(S.storeName,"readwrite").objectStore(S.storeName).add(_);v.onerror=()=>h(v.error),v.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 w=Math.min(S.retryDelay*Math.pow(S.backoffFactor,y.attempts-1),S.maxRetryDelay);await Zt(w)}g(w=>({...w,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 w of c)h.delete(w.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 w of c)h.delete(w.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:5*60*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 w=await h.json(),T=h.headers.get("etag")||void 0;await L(r,w,s);const v={data:w,timestamp:new Date,etag:T,key:r,isStale:!1,source:"network",url:i};return f(U=>({...U,isFetching:!1})),N==null||N(v),v}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(w=>({...w,isFetching:!1,hits:w.hits+1})),O==null||O(h),h;throw f(w=>({...w,isFetching:!1,misses:w.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(w=>({...w,isFetching:!1,hits:w.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 w=await B(r);if(w)return f(T=>({...T,isFetching:!1,hits:T.hits+1})),O==null||O(w),w;throw h}case"stale-while-revalidate":default:{const h=await B(r);return h&&!c?(f(w=>({...w,hits:w.hits+1})),O==null||O(h),h.isStale&&y().catch(()=>{}),f(w=>({...w,isFetching:!1})),h):(f(w=>({...w,misses:w.misses+1})),await y())}}}catch(h){throw f(w=>({...w,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(),w=($,G,V)=>{E($,G,V)},T=$=>{s($)},v=$=>D?D({conflict:$,onResolve:(G,V)=>w($.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:()=>w($.id,"client-wins"),disabled:B,children:"Keep Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>w($.id,"server-wins"),disabled:B,children:"Use Server"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--merge",onClick:()=>w($.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:w,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(v)}),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 w=c.createObjectStore(h.name,{keyPath:h.keyPath,autoIncrement:h.autoIncrement});if(h.indexes)for(const T of h.indexes)w.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 w;return c(new Error((w=h.error)==null?void 0:w.message))},h.onsuccess=()=>{let w=h.result;n!=null&&n.offset&&(w=w.slice(n.offset)),r(w)}})},[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 w;return c(new Error((w=h.error)==null?void 0:w.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 w;return l(new Error((w=h.error)==null?void 0:w.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 w;return l(new Error((w=h.error)==null?void 0:w.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),w=(n.index?y.index(n.index):y).openCursor(n.range,n.direction);let T=0,v=0;w.onerror=()=>{var U;return l(new Error((U=w.error)==null?void 0:U.message))},w.onsuccess=()=>{const U=w.result;if(U){if(n.offset&&T<n.offset){T++,U.continue();return}if(n.limit&&v>=n.limit){c(r);return}r.push(U.value),v++,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 w=y.add(h);w.onsuccess=()=>r.push(w.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 w=y.put(h);w.onsuccess=()=>r.push(w.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 w=r.transaction("drafts","readwrite").objectStore("drafts").add(c);w.onerror=()=>_(w.error),w.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(w=>({...w,createdAt:new Date(w.createdAt),modifiedAt:new Date(w.modifiedAt),syncedAt:w.syncedAt?new Date(w.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 w=r.transaction("drafts","readwrite").objectStore("drafts").put(c);w.onerror=()=>_(w.error),w.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}},w=()=>{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 v=["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:v,style:H,children:X(d)});const U=()=>t.jsx("span",{className:"nice-offline-indicator__icon",children:w()}),$=()=>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(--color-success, #22c55e)":d.quality>=50?"var(--color-warning, #eab308)":"var(--color-error, #ef4444)"}})});switch(x){case"icon-only":return t.jsx("div",{className:v,style:H,title:h(),children:U()});case"minimal":return t.jsxs("div",{className:v,style:H,children:[U(),$()]});case"badge":return t.jsxs("div",{className:v,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:v,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:v,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:v,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:7*24*60*60*1e3,autoCleanup:!0,cleanupInterval:60*60*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,v)=>{const U=indexedDB.open(u.dbName,1);U.onerror=()=>v(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 v=await j();return new Promise((U,$)=>{const Y=v.transaction("media","readwrite").objectStore("media").put(T);Y.onerror=()=>$(Y.error),Y.onsuccess=()=>U()})},[j]),L=e.useCallback(async(T,v)=>{const U=await j();return new Promise(($,G)=>{const C=U.transaction("blobs","readwrite").objectStore("blobs").put({id:T,blob:v});C.onerror=()=>G(C.error),C.onsuccess=()=>$()})},[j]),M=e.useCallback(async T=>{const v=await j();return new Promise((U,$)=>{const Y=v.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 v=await j();return new Promise((U,$)=>{const Y=v.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((v,U)=>{const V=T.transaction("media","readonly").objectStore("media").getAll();V.onerror=()=>U(V.error),V.onsuccess=()=>{v(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 v=await j();return new Promise((U,$)=>{const C=v.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 v=await j();return new Promise((U,$)=>{const C=v.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 v=await P(T);return(v==null?void 0:v.status)==="completed"},[P]),d=e.useCallback(async T=>{const v=b.current.get(T);if(v)return v;const U=await M(T);if(!U)return;const $=URL.createObjectURL(U);return b.current.set(T,$),$},[M]),I=e.useCallback(async(T,v)=>{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:(v==null?void 0:v.type)||"other",name:(v==null?void 0:v.name)||kn(T),mimeType:"",size:0,status:"queued",progress:0,downloadedBytes:0,metadata:v==null?void 0:v.metadata,tags:v==null?void 0:v.tags,priority:v==null?void 0:v.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:v==null?void 0:v.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=(v==null?void 0:v.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=v!=null&&v.cacheDuration?new Date(Date.now()+v.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 v=[];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"&&v.push(V.value)}return v},[I,u.maxConcurrentDownloads]),R=e.useCallback(T=>{const v=D.current.get(T);v&&v.abort()},[]),i=e.useCallback(async T=>{const v=await W(T);v&&(v.status==="paused"||v.status==="failed")&&await I(v.url,{type:v.type,name:v.name,metadata:v.metadata,tags:v.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 v=(await X()).filter(U=>U.status==="paused"||U.status==="failed");await E(v.map(U=>({url:U.url})))},[X,E]),r=e.useCallback(async T=>{const v=await j(),U=b.current.get(T);U&&(URL.revokeObjectURL(U),b.current.delete(T)),await new Promise(($,G)=>{const V=v.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[,v]of b.current)URL.revokeObjectURL(v);b.current.clear(),await new Promise((v,U)=>{const $=T.transaction(["media","blobs"],"readwrite");$.objectStore("media").clear(),$.objectStore("blobs").clear(),$.onerror=()=>U($.error),$.oncomplete=()=>v()}),await h()},[j]),l=e.useCallback(async()=>{const T=await X(),v=Date.now();let U=0;for(const $ of T)$.expiresAt&&$.expiresAt.getTime()<v&&(await r($.id),U++);return U},[X,r]),_=e.useCallback(async()=>{const v=(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 v)$+=G.size,U[G.type].count++,U[G.type].size+=G.size;return{totalSize:$,itemCount:v.length,byType:U}},[X]),y=e.useCallback(async T=>{await E(T.map(v=>({url:v,options:{priority:-1}})))},[E]),h=e.useCallback(async()=>{const T=await _();g(v=>({...v,cachedCount:T.itemCount,totalCacheSize:T.totalSize}))},[_]);e.useEffect(()=>{const T=()=>{g(U=>({...U,isOnline:!0})),u.autoResumeOnReconnect&&s()},v=()=>{g(U=>({...U,isOnline:!1})),n()};return window.addEventListener("online",T),window.addEventListener("offline",v),()=>{window.removeEventListener("online",T),window.removeEventListener("offline",v)}},[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()),()=>{for(const[,T]of b.current)URL.revokeObjectURL(T)}),[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 w={...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:w,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),w=await h.keys();let T=0;for(const v of w){const U=await h.match(v);if(U){const $=await U.clone().blob();T+=$.size}}_.push({name:y,size:T,itemCount:w.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}},[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]),w=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]),v=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=v(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,v,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=v(te[0].rawValue,te[0]);J(ne)}else J(null)}catch{J(null)}},Z.onerror=()=>J(null),Z.src=URL.createObjectURL(K)}),[l,v]);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:w,takeSnapshot:Y,scanImage:C}),[L,W,F,P,l,d,i,n,$,G,V,h,w,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 v=l.transaction(S.storeName,"readwrite").objectStore(S.storeName).add(_);v.onerror=()=>h(v.error),v.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 w=Math.min(S.retryDelay*Math.pow(S.backoffFactor,y.attempts-1),S.maxRetryDelay);await Zt(w)}g(w=>({...w,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 w of c)h.delete(w.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 w of c)h.delete(w.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:5*60*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 w=await h.json(),T=h.headers.get("etag")||void 0;await L(r,w,s);const v={data:w,timestamp:new Date,etag:T,key:r,isStale:!1,source:"network",url:i};return f(U=>({...U,isFetching:!1})),N==null||N(v),v}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(w=>({...w,isFetching:!1,hits:w.hits+1})),O==null||O(h),h;throw f(w=>({...w,isFetching:!1,misses:w.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(w=>({...w,isFetching:!1,hits:w.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 w=await B(r);if(w)return f(T=>({...T,isFetching:!1,hits:T.hits+1})),O==null||O(w),w;throw h}case"stale-while-revalidate":default:{const h=await B(r);return h&&!c?(f(w=>({...w,hits:w.hits+1})),O==null||O(h),h.isStale&&y().catch(()=>{}),f(w=>({...w,isFetching:!1})),h):(f(w=>({...w,misses:w.misses+1})),await y())}}}catch(h){throw f(w=>({...w,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(),w=($,G,V)=>{E($,G,V)},T=$=>{s($)},v=$=>D?D({conflict:$,onResolve:(G,V)=>w($.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:()=>w($.id,"client-wins"),disabled:B,children:"Keep Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>w($.id,"server-wins"),disabled:B,children:"Use Server"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--merge",onClick:()=>w($.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:w,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(v)}),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 w=c.createObjectStore(h.name,{keyPath:h.keyPath,autoIncrement:h.autoIncrement});if(h.indexes)for(const T of h.indexes)w.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 w;return c(new Error((w=h.error)==null?void 0:w.message))},h.onsuccess=()=>{let w=h.result;n!=null&&n.offset&&(w=w.slice(n.offset)),r(w)}})},[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 w;return c(new Error((w=h.error)==null?void 0:w.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 w;return l(new Error((w=h.error)==null?void 0:w.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 w;return l(new Error((w=h.error)==null?void 0:w.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),w=(n.index?y.index(n.index):y).openCursor(n.range,n.direction);let T=0,v=0;w.onerror=()=>{var U;return l(new Error((U=w.error)==null?void 0:U.message))},w.onsuccess=()=>{const U=w.result;if(U){if(n.offset&&T<n.offset){T++,U.continue();return}if(n.limit&&v>=n.limit){c(r);return}r.push(U.value),v++,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 w=y.add(h);w.onsuccess=()=>r.push(w.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 w=y.put(h);w.onsuccess=()=>r.push(w.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 w=r.transaction("drafts","readwrite").objectStore("drafts").add(c);w.onerror=()=>_(w.error),w.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(w=>({...w,createdAt:new Date(w.createdAt),modifiedAt:new Date(w.modifiedAt),syncedAt:w.syncedAt?new Date(w.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 w=r.transaction("drafts","readwrite").objectStore("drafts").put(c);w.onerror=()=>_(w.error),w.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}},w=()=>{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 v=["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:v,style:H,children:X(d)});const U=()=>t.jsx("span",{className:"nice-offline-indicator__icon",children:w()}),$=()=>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(--color-success, #22c55e)":d.quality>=50?"var(--color-warning, #eab308)":"var(--color-error, #ef4444)"}})});switch(x){case"icon-only":return t.jsx("div",{className:v,style:H,title:h(),children:U()});case"minimal":return t.jsxs("div",{className:v,style:H,children:[U(),$()]});case"badge":return t.jsxs("div",{className:v,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:v,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:v,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:v,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:7*24*60*60*1e3,autoCleanup:!0,cleanupInterval:60*60*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,v)=>{const U=indexedDB.open(u.dbName,1);U.onerror=()=>v(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 v=await j();return new Promise((U,$)=>{const Y=v.transaction("media","readwrite").objectStore("media").put(T);Y.onerror=()=>$(Y.error),Y.onsuccess=()=>U()})},[j]),L=e.useCallback(async(T,v)=>{const U=await j();return new Promise(($,G)=>{const C=U.transaction("blobs","readwrite").objectStore("blobs").put({id:T,blob:v});C.onerror=()=>G(C.error),C.onsuccess=()=>$()})},[j]),M=e.useCallback(async T=>{const v=await j();return new Promise((U,$)=>{const Y=v.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 v=await j();return new Promise((U,$)=>{const Y=v.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((v,U)=>{const V=T.transaction("media","readonly").objectStore("media").getAll();V.onerror=()=>U(V.error),V.onsuccess=()=>{v(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 v=await j();return new Promise((U,$)=>{const C=v.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 v=await j();return new Promise((U,$)=>{const C=v.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 v=await P(T);return(v==null?void 0:v.status)==="completed"},[P]),d=e.useCallback(async T=>{const v=b.current.get(T);if(v)return v;const U=await M(T);if(!U)return;const $=URL.createObjectURL(U);return b.current.set(T,$),$},[M]),I=e.useCallback(async(T,v)=>{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:(v==null?void 0:v.type)||"other",name:(v==null?void 0:v.name)||kn(T),mimeType:"",size:0,status:"queued",progress:0,downloadedBytes:0,metadata:v==null?void 0:v.metadata,tags:v==null?void 0:v.tags,priority:v==null?void 0:v.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:v==null?void 0:v.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=(v==null?void 0:v.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=v!=null&&v.cacheDuration?new Date(Date.now()+v.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 v=[];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"&&v.push(V.value)}return v},[I,u.maxConcurrentDownloads]),R=e.useCallback(T=>{const v=D.current.get(T);v&&v.abort()},[]),i=e.useCallback(async T=>{const v=await W(T);v&&(v.status==="paused"||v.status==="failed")&&await I(v.url,{type:v.type,name:v.name,metadata:v.metadata,tags:v.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 v=(await X()).filter(U=>U.status==="paused"||U.status==="failed");await E(v.map(U=>({url:U.url})))},[X,E]),r=e.useCallback(async T=>{const v=await j(),U=b.current.get(T);U&&(URL.revokeObjectURL(U),b.current.delete(T)),await new Promise(($,G)=>{const V=v.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[,v]of b.current)URL.revokeObjectURL(v);b.current.clear(),await new Promise((v,U)=>{const $=T.transaction(["media","blobs"],"readwrite");$.objectStore("media").clear(),$.objectStore("blobs").clear(),$.onerror=()=>U($.error),$.oncomplete=()=>v()}),await h()},[j]),l=e.useCallback(async()=>{const T=await X(),v=Date.now();let U=0;for(const $ of T)$.expiresAt&&$.expiresAt.getTime()<v&&(await r($.id),U++);return U},[X,r]),_=e.useCallback(async()=>{const v=(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 v)$+=G.size,U[G.type].count++,U[G.type].size+=G.size;return{totalSize:$,itemCount:v.length,byType:U}},[X]),y=e.useCallback(async T=>{await E(T.map(v=>({url:v,options:{priority:-1}})))},[E]),h=e.useCallback(async()=>{const T=await _();g(v=>({...v,cachedCount:T.itemCount,totalCacheSize:T.totalSize}))},[_]);e.useEffect(()=>{const T=()=>{g(U=>({...U,isOnline:!0})),u.autoResumeOnReconnect&&s()},v=()=>{g(U=>({...U,isOnline:!1})),n()};return window.addEventListener("online",T),window.addEventListener("offline",v),()=>{window.removeEventListener("online",T),window.removeEventListener("offline",v)}},[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()),()=>{for(const[,T]of b.current)URL.revokeObjectURL(T)}),[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 w={...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:w,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),w=await h.keys();let T=0;for(const v of w){const U=await h.match(v);if(U){const $=await U.clone().blob();T+=$.size}}_.push({name:y,size:T,itemCount:w.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;