@nice2dev/ui-platform 1.1.9 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -6
- package/dist/index.cjs +7 -7
- package/dist/index.d.ts +26 -2
- package/dist/index.mjs +4102 -4036
- package/dist/ui-platform.css +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var Nt=Object.defineProperty;var It=(n,f,p)=>f in n?Nt(n,f,{enumerable:!0,configurable:!0,writable:!0,value:p}):n[f]=p;var ce=(n,f,p)=>It(n,typeof f!="symbol"?f+"":f,p);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),le=e.createContext(null),jt=()=>{const n=e.useContext(le);if(!n)throw new Error("useAutoStart must be used within NiceAutoStartProvider");return n},At={showSplash:!0,splashDuration:2e3,autoHideSplash:!0,showProgress:!0,showTaskNames:!0,globalTimeout:6e4,autoRecovery:!0,recoveryAttempts:3,recoveryDelay:2e3,checkUpdates:!1,sendAnalytics:!1},he=e.forwardRef((n,f)=>{const{tasks:p=[],config:C,splash:h,errorScreen:N,onComplete:T,onTaskComplete:P,onError:i,onRecovery:d,children:b}=n,L={...At,...C},x=e.useRef(0),u=e.useRef(p),y=e.useRef(null),[A,q]=e.useState(L.showSplash),[U,V]=e.useState({phase:"initializing",isLoading:!0,isReady:!1,hasError:!1,progress:0,completedTasks:0,totalTasks:p.length,results:[],recoveryAttempt:0,totalDuration:0}),z=e.useCallback(async s=>{const a=Date.now();let r=0;const o=async()=>{try{const l=s.timeout||L.globalTimeout,j=new Promise((F,g)=>{setTimeout(()=>g(new Error("Task timeout")),l)});return await Promise.race([s.execute(),j]),{taskId:s.id,success:!0,duration:Date.now()-a,retriesUsed:r}}catch(l){const j=s.retries??0;return r<j?(r++,await new Promise(F=>setTimeout(F,500)),o()):{taskId:s.id,success:!1,error:l instanceof Error?l:new Error(String(l)),duration:Date.now()-a,retriesUsed:r}}};return o()},[L.globalTimeout]),Y=e.useCallback(s=>{const a=[],r=[...s],o=new Set;for(;r.length>0;){const l=r.filter(F=>F.dependencies?F.dependencies.every(g=>o.has(g)):!0);if(l.length===0){a.push(...r);break}l.sort((F,g)=>(g.priority??0)-(F.priority??0));const j=l[0];a.push(j),o.add(j.id),r.splice(r.indexOf(j),1)}return a},[]),B=e.useCallback(async()=>{x.current=Date.now();const s=new AbortController;y.current=s;const a=Y(u.current),r=[];V(l=>({...l,phase:"loading",isLoading:!0,isReady:!1,hasError:!1,errorMessage:void 0,progress:0,completedTasks:0,totalTasks:a.length,results:[]}));for(let l=0;l<a.length;l++){if(s.signal.aborted)return;const j=a[l];V(g=>({...g,currentTask:j.name,progress:Math.round(l/a.length*100)}));const F=await z(j);if(s.signal.aborted)return;if(r.push(F),V(g=>({...g,completedTasks:l+1,results:[...g.results,F]})),P==null||P(F),!F.success&&j.critical){const g=F.error||new Error("Critical task failed");i==null||i(g,j.id),V(m=>({...m,phase:"error",isLoading:!1,hasError:!0,errorMessage:g.message}));return}}const o=Date.now()-x.current;if(V(l=>({...l,phase:"ready",isLoading:!1,isReady:!0,currentTask:void 0,progress:100,totalDuration:o})),T==null||T(r),L.autoHideSplash){const l=Date.now()-x.current,j=Math.max(0,L.splashDuration-l);setTimeout(()=>{q(!1)},j)}},[Y,z,L.autoHideSplash,L.splashDuration,P,i,T]),G=e.useCallback(async()=>{y.current&&y.current.abort(),V(s=>({...s,recoveryAttempt:0})),q(L.showSplash),await B()},[L.showSplash,B]),E=e.useCallback(()=>{y.current&&y.current.abort(),V(s=>({...s,phase:"ready",isLoading:!1,isReady:!0,progress:100})),q(!1)},[]),$=e.useCallback(()=>{q(!1)},[]),R=e.useCallback(async()=>{const s=U.recoveryAttempt+1;s>L.recoveryAttempts||(V(a=>({...a,phase:"recovery",recoveryAttempt:s})),d==null||d(s),await new Promise(a=>setTimeout(a,L.recoveryDelay)),await B())},[U.recoveryAttempt,L.recoveryAttempts,L.recoveryDelay,d,B]),k=e.useCallback(s=>{u.current=[...u.current,s]},[]),S=e.useCallback(s=>{u.current=u.current.filter(a=>a.id!==s)},[]),D=e.useCallback(s=>U.results.find(a=>a.taskId===s),[U.results]);e.useEffect(()=>{U.hasError&&L.autoRecovery&&U.recoveryAttempt<L.recoveryAttempts&&R()},[U.hasError,L.autoRecovery,L.recoveryAttempts,U.recoveryAttempt,R]),e.useEffect(()=>(B(),()=>{y.current&&y.current.abort()}),[]),e.useImperativeHandle(f,()=>({getState:()=>U,restart:G,skip:E,addTask:k,removeTask:S,getTaskResult:D,hideSplash:$,recover:R}),[U,G,E,k,S,D,$,R]);const c={...U,restart:G,skip:E,hideSplash:$};return U.hasError&&U.recoveryAttempt>=L.recoveryAttempts?t.jsx(le.Provider,{value:c,children:N||t.jsxs("div",{className:"nice-auto-start__error",children:[t.jsx("div",{className:"nice-auto-start__error-icon","aria-hidden":"true",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert"})}),t.jsx("h2",{className:"nice-auto-start__error-title",children:"Startup Failed"}),t.jsx("p",{className:"nice-auto-start__error-message",children:U.errorMessage}),t.jsx("button",{className:"nice-auto-start__error-retry",onClick:G,children:"Retry"})]})}):A&&!U.isReady?t.jsx(le.Provider,{value:c,children:h||t.jsx("div",{className:"nice-auto-start__splash",children:t.jsxs("div",{className:"nice-auto-start__splash-content",children:[t.jsx("div",{className:"nice-auto-start__splash-logo","aria-hidden":"true"}),t.jsx("h1",{className:"nice-auto-start__splash-title",children:"Loading..."}),L.showProgress&&t.jsx("div",{className:"nice-auto-start__splash-progress",children:t.jsx("div",{className:"nice-auto-start__splash-progress-bar",style:{width:`${U.progress}%`}})}),L.showTaskNames&&U.currentTask&&t.jsx("div",{className:"nice-auto-start__splash-task",children:U.currentTask}),U.phase==="recovery"&&t.jsxs("div",{className:"nice-auto-start__splash-recovery",children:["Recovery attempt ",U.recoveryAttempt," of ",L.recoveryAttempts]})]})})}):t.jsx(le.Provider,{value:c,children:b})});he.displayName="NiceAutoStart";const Te=he;Te.displayName="NiceAutoStartProvider";const Me=e.createContext(null),Fe=()=>{const n=e.useContext(Me);if(!n)throw new Error("useExternalDisplay must be used within NiceExternalDisplayProvider");return n},Dt={autoDetect:!0,pollInterval:2e3,defaultFeatures:{resizable:!0,scrollbars:!0},allowMultiWindow:!0,syncContent:!1},Et=()=>typeof window>"u"?!1:"getScreenDetails"in window,Lt=()=>`window-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Pt=n=>{const f=[];return n.width!==void 0&&f.push(`width=${n.width}`),n.height!==void 0&&f.push(`height=${n.height}`),n.left!==void 0&&f.push(`left=${n.left}`),n.top!==void 0&&f.push(`top=${n.top}`),n.menubar!==void 0&&f.push(`menubar=${n.menubar?"yes":"no"}`),n.toolbar!==void 0&&f.push(`toolbar=${n.toolbar?"yes":"no"}`),n.location!==void 0&&f.push(`location=${n.location?"yes":"no"}`),n.status!==void 0&&f.push(`status=${n.status?"yes":"no"}`),n.resizable!==void 0&&f.push(`resizable=${n.resizable?"yes":"no"}`),n.scrollbars!==void 0&&f.push(`scrollbars=${n.scrollbars?"yes":"no"}`),f.join(",")},je=()=>{var f;if(typeof window>"u")return{id:"primary",label:"Primary Display",width:0,height:0,availWidth:0,availHeight:0,left:0,top:0,devicePixelRatio:1,isPrimary:!0,orientation:"landscape-primary",colorDepth:24};const n=window.screen;return{id:"primary",label:"Primary Display",width:n.width,height:n.height,availWidth:n.availWidth,availHeight:n.availHeight,left:n.availLeft||0,top:n.availTop||0,devicePixelRatio:window.devicePixelRatio,isPrimary:!0,orientation:((f=n.orientation)==null?void 0:f.type)||"landscape-primary",colorDepth:n.colorDepth}},Rt=async()=>{try{return(await navigator.permissions.query({name:"window-management"})).state}catch{return"unknown"}},Ae=async()=>(await window.getScreenDetails()).screens.map((f,p)=>{var C;return{id:`screen-${p}`,label:f.label||`Display ${p+1}`,width:f.width,height:f.height,availWidth:f.availWidth,availHeight:f.availHeight,left:f.left,top:f.top,devicePixelRatio:f.devicePixelRatio,isPrimary:f.isPrimary,isInternal:f.isInternal,orientation:((C=f.orientation)==null?void 0:C.type)||"landscape-primary",colorDepth:f.colorDepth}}),De=(n,f)=>JSON.stringify(n)===JSON.stringify(f),ge=e.forwardRef((n,f)=>{const{config:p,onScreensChange:C,onWindowOpen:h,onWindowClose:N,onPermissionChange:T,children:P}=n,i={...Dt,...p},d=e.useRef(new Map),b=e.useRef(null),[L,x]=e.useState([je()]),[u,y]=e.useState([]),[A,q]=e.useState("unknown"),[U]=e.useState(Et),V=e.useRef(C),z=e.useRef(T);e.useEffect(()=>{V.current=C,z.current=T});const Y=e.useRef([]),B=e.useCallback(g=>{var m;x(w=>De(w,g)?w:g),De(Y.current,g)||(Y.current=g,(m=V.current)==null||m.call(V,g))},[]),G=e.useRef("unknown"),E=e.useCallback(g=>{var m;G.current!==g&&(G.current=g,q(g),(m=z.current)==null||m.call(z,g))},[]),$=e.useCallback(async()=>{if(U){const m=await Rt();if(E(m),m==="granted")try{const w=await Ae();return B(w),w}catch{}}const g=[je()];return B(g),g},[U,E,B]),R=e.useCallback(async()=>{if(!U)return E("denied"),!1;try{return B(await Ae()),E("granted"),!0}catch(g){return E(g instanceof DOMException&&g.name==="NotAllowedError"?"denied":"unknown"),!1}},[U,E,B]),k=e.useCallback(async(g,m="about:blank",w={})=>{if(!i.allowMultiWindow&&u.length>0)return console.warn("Multi-window mode is disabled"),null;const O=Lt(),_={...i.defaultFeatures,...w,width:w.width??g.availWidth,height:w.height??g.availHeight,left:w.left??g.left,top:w.top??g.top},W=Pt(_),I={window:null,screen:g,id:O,state:"opening",isFullscreen:!1,features:_};y(H=>[...H,I]);try{const H=window.open(m,O,W);if(!H)return y(v=>v.map(J=>J.id===O?{...J,state:"error"}:J)),null;d.current.set(O,H);const M={...I,window:H,state:"open"};y(v=>v.map(J=>J.id===O?M:J));const X=setInterval(()=>{H.closed&&(clearInterval(X),d.current.delete(O),y(v=>v.filter(J=>J.id!==O)),N==null||N(M))},500);return _.fullscreen&&H.addEventListener("load",()=>{var v,J;(J=(v=H.document.documentElement).requestFullscreen)==null||J.call(v)}),h==null||h(M),M}catch(H){return console.error("Failed to open window:",H),y(M=>M.map(X=>X.id===O?{...X,state:"error"}:X)),null}},[i.allowMultiWindow,i.defaultFeatures,u.length,h,N]),S=e.useCallback(g=>{const m=d.current.get(g);m&&!m.closed&&m.close(),d.current.delete(g),y(w=>w.filter(O=>O.id!==g))},[]),D=e.useCallback(()=>{for(const[g,m]of d.current)m.closed||m.close(),d.current.delete(g);y([])},[]),c=e.useCallback((g,m)=>{const w=d.current.get(g);w&&!w.closed&&(w.moveTo(m.left,m.top),w.resizeTo(m.availWidth,m.availHeight),y(O=>O.map(_=>_.id===g?{..._,screen:m}:_)))},[]),s=e.useCallback(async g=>{const m=d.current.get(g);if(!m||m.closed)return!1;try{const w=!!m.document.fullscreenElement;return w?await m.document.exitFullscreen():await m.document.documentElement.requestFullscreen(),y(O=>O.map(_=>_.id===g?{..._,isFullscreen:!w}:_)),!0}catch{return!1}},[]),a=e.useCallback((g,m)=>{const w=d.current.get(g);w&&!w.closed&&w.postMessage(m,"*")},[]),r=e.useCallback(g=>{for(const m of d.current.values())m.closed||m.postMessage(g,"*")},[]);e.useEffect(()=>{i.autoDetect&&$()},[i.autoDetect,$]),e.useEffect(()=>(i.autoDetect&&i.pollInterval>0&&(b.current=setInterval($,i.pollInterval)),()=>{b.current&&clearInterval(b.current)}),[i.autoDetect,i.pollInterval,$]),e.useEffect(()=>{if(!U)return;const g=()=>{$()};return window.addEventListener("screenschange",g),()=>{window.removeEventListener("screenschange",g)}},[U,$]),e.useEffect(()=>()=>{D()},[D]);const o=L.find(g=>g.isPrimary)||null,l=L.filter(g=>!g.isPrimary),j={screens:L,primaryScreen:o,externalScreens:l,windows:u,isApiAvailable:U,permissionState:A};e.useImperativeHandle(f,()=>({getState:()=>j,requestPermission:R,getScreens:$,openWindow:k,closeWindow:S,closeAllWindows:D,moveWindowToScreen:c,toggleFullscreen:s,sendMessage:a,broadcast:r}),[j,R,$,k,S,D,c,s,a,r]);const F={...j,requestPermission:R,openWindow:k,closeWindow:S,moveWindowToScreen:c};return t.jsx(Me.Provider,{value:F,children:t.jsx("div",{className:"nice-external-display",children:P})})});ge.displayName="NiceExternalDisplay";const Be=ge;Be.displayName="NiceExternalDisplayProvider";const $e=({onSelect:n,selectedId:f,showPreview:p=!0,className:C})=>{const{screens:h,primaryScreen:N}=Fe(),T=b=>{n==null||n(b)},i=(()=>{let b=0,L=0,x=0,u=0;for(const y of h)b=Math.min(b,y.left),L=Math.min(L,y.top),x=Math.max(x,y.left+y.width),u=Math.max(u,y.top+y.height);return{minX:b,minY:L,maxX:x,maxY:u,width:x-b,height:u-L}})(),d=Math.min(280/i.width,160/i.height,1);return t.jsxs("div",{className:`nice-screen-selector ${C||""}`,children:[p&&t.jsx("div",{className:"nice-screen-selector__preview",style:{width:i.width*d,height:i.height*d},children:h.map(b=>t.jsx("button",{className:`nice-screen-selector__screen ${f===b.id?"nice-screen-selector__screen--selected":""} ${b.isPrimary?"nice-screen-selector__screen--primary":""}`,style:{left:(b.left-i.minX)*d,top:(b.top-i.minY)*d,width:b.width*d,height:b.height*d},onClick:()=>T(b),title:b.label,children:t.jsx("span",{className:"nice-screen-selector__screen-label",children:b.isPrimary?"P":h.indexOf(b)+1})},b.id))}),t.jsx("div",{className:"nice-screen-selector__list",children:h.map(b=>t.jsxs("button",{className:`nice-screen-selector__item ${f===b.id?"nice-screen-selector__item--selected":""}`,onClick:()=>T(b),children:[t.jsx("span",{className:"nice-screen-selector__item-name",children:b.label}),t.jsxs("span",{className:"nice-screen-selector__item-resolution",children:[b.width," × ",b.height]}),b.isPrimary&&t.jsx("span",{className:"nice-screen-selector__item-badge",children:"Primary"})]},b.id))})]})};$e.displayName="NiceScreenSelector";const qe=e.createContext(null),Ot=()=>{const n=e.useContext(qe);if(!n)throw new Error("useKioskMode must be used within NiceKioskModeProvider");return n},Tt={autoFullscreen:!0,lockNavigation:!0,disableContextMenu:!0,disableShortcuts:!0,disableSelection:!0,disableCopyPaste:!0,exitPin:"1234",exitShortcut:"ctrl+shift+k",adminTapCount:5,adminTapTimeout:2e3,inactivityTimeout:300*1e3,showCursor:!0,allowScrolling:!0,className:""},pe=e.forwardRef((n,f)=>{const{config:p,children:C,screensaver:h,adminPanel:N,onModeChange:T,onFullscreenChange:P,onAdminAccess:i,onInactivity:d,onActivity:b,onExitRequest:L}=n,x={...Tt,...p},u=e.useRef(null),y=e.useRef(null),A=e.useRef({count:0,timer:null}),[q,U]=e.useState({mode:"windowed",isFullscreen:!1,isLocked:!1,isAdminMode:!1,isScreensaverActive:!1,idleTime:0,isPinDialogOpen:!1}),[V,z]=e.useState(""),[Y,B]=e.useState(!1),G=e.useCallback(async()=>{const w=u.current;if(w)try{w.requestFullscreen?await w.requestFullscreen():w.webkitRequestFullscreen?await w.webkitRequestFullscreen():w.msRequestFullscreen&&await w.msRequestFullscreen()}catch(O){console.warn("Failed to enter fullscreen:",O)}},[]),E=e.useCallback(async()=>{try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen?await document.webkitExitFullscreen():document.msExitFullscreen&&await document.msExitFullscreen()}catch(w){console.warn("Failed to exit fullscreen:",w)}},[]),$=e.useCallback(async()=>{q.isFullscreen?await E():await G()},[q.isFullscreen,G,E]),R=e.useCallback(()=>{U(w=>({...w,mode:"locked",isLocked:!0,isAdminMode:!1})),T==null||T("locked")},[T]),k=e.useCallback(w=>x.exitPin&&w!==x.exitPin?(B(!0),setTimeout(()=>B(!1),1e3),!1):(U(O=>({...O,mode:O.isFullscreen?"fullscreen":"windowed",isLocked:!1,isPinDialogOpen:!1})),z(""),!0),[x.exitPin]),S=e.useCallback(()=>{U(w=>({...w,isAdminMode:!0})),i==null||i()},[i]),D=e.useCallback(()=>{U(w=>({...w,isAdminMode:!1}))},[]),c=e.useCallback(()=>{A.current.timer&&clearTimeout(A.current.timer),A.current.count++,A.current.count>=x.adminTapCount?(A.current.count=0,S()):A.current.timer=setTimeout(()=>{A.current.count=0},x.adminTapTimeout)},[x.adminTapCount,x.adminTapTimeout,S]),s=e.useCallback(()=>{y.current&&clearTimeout(y.current),q.isScreensaverActive&&(U(w=>({...w,isScreensaverActive:!1})),b==null||b()),x.inactivityTimeout>0&&(y.current=setTimeout(()=>{U(w=>({...w,isScreensaverActive:!0})),d==null||d()},x.inactivityTimeout))},[x.inactivityTimeout,q.isScreensaverActive,b,d]),a=e.useCallback(()=>{U(w=>({...w,isScreensaverActive:!0}))},[]),r=e.useCallback(()=>{U(w=>({...w,isScreensaverActive:!1})),s()},[s]),o=e.useCallback(()=>{U(w=>({...w,isPinDialogOpen:!0})),z(""),B(!1)},[]),l=e.useCallback(()=>{U(w=>({...w,isPinDialogOpen:!1})),z(""),B(!1)},[]),j=e.useCallback(()=>{k(V)},[V,k]),F=e.useCallback(w=>{w.key==="Enter"&&j()},[j]);e.useEffect(()=>{const w=()=>{const O=!!document.fullscreenElement;U(_=>({..._,mode:_.isLocked?"locked":O?"fullscreen":"windowed",isFullscreen:O})),P==null||P(O)};return document.addEventListener("fullscreenchange",w),document.addEventListener("webkitfullscreenchange",w),()=>{document.removeEventListener("fullscreenchange",w),document.removeEventListener("webkitfullscreenchange",w)}},[P]),e.useEffect(()=>{if(!x.disableContextMenu)return;const w=O=>{q.isAdminMode||O.preventDefault()};return document.addEventListener("contextmenu",w),()=>document.removeEventListener("contextmenu",w)},[x.disableContextMenu,q.isAdminMode]),e.useEffect(()=>{const w=async O=>{const W=x.exitShortcut.toLowerCase().split("+"),I=W.includes("ctrl")===O.ctrlKey,H=W.includes("shift")===O.shiftKey,M=W.includes("alt")===O.altKey,X=W.some(v=>v===O.key.toLowerCase());if(I&&H&&M&&X){O.preventDefault(),(L?await L("keyboard"):!0)&&(q.isLocked?o():E());return}if(x.disableShortcuts&&!q.isAdminMode){const v=["F5","F11","F12"],J=[{ctrl:!0,key:"r"},{ctrl:!0,key:"w"},{ctrl:!0,key:"n"},{ctrl:!0,key:"t"},{ctrl:!0,shift:!0,key:"i"},{ctrl:!0,shift:!0,key:"j"},{alt:!0,key:"F4"}];if(v.includes(O.key)){O.preventDefault();return}for(const Q of J)if(Q.ctrl===O.ctrlKey&&(Q.shift??!1)===O.shiftKey&&(Q.alt??!1)===O.altKey&&Q.key.toLowerCase()===O.key.toLowerCase()){O.preventDefault();return}}};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[x.disableShortcuts,x.exitShortcut,q.isAdminMode,q.isLocked,E,o,L]),e.useEffect(()=>{if(!x.disableCopyPaste)return;const w=_=>{q.isAdminMode||_.preventDefault()},O=_=>{q.isAdminMode||_.preventDefault()};return document.addEventListener("copy",w),document.addEventListener("paste",O),()=>{document.removeEventListener("copy",w),document.removeEventListener("paste",O)}},[x.disableCopyPaste,q.isAdminMode]),e.useEffect(()=>{const w=["mousedown","mousemove","keydown","touchstart","scroll"],O=()=>{s()};for(const _ of w)document.addEventListener(_,O);return s(),()=>{for(const _ of w)document.removeEventListener(_,O);y.current&&clearTimeout(y.current)}},[s]),e.useEffect(()=>{if(x.autoFullscreen){const w=setTimeout(()=>{G()},100);return()=>clearTimeout(w)}},[x.autoFullscreen,G]),e.useImperativeHandle(f,()=>({getState:()=>q,enterFullscreen:G,exitFullscreen:E,toggleFullscreen:$,lock:R,unlock:k,enterAdminMode:S,exitAdminMode:D,resetIdleTimer:s,showScreensaver:a,hideScreensaver:r,openPinDialog:o,closePinDialog:l}),[q,G,E,$,R,k,S,D,s,a,r,o,l]);const g={...q,enterFullscreen:G,exitFullscreen:E,toggleFullscreen:$,lock:R,unlock:k,enterAdminMode:S,exitAdminMode:D,resetIdleTimer:s},m=["nice-kiosk-mode",`nice-kiosk-mode--${q.mode}`,q.isFullscreen&&"nice-kiosk-mode--fullscreen",!x.showCursor&&"nice-kiosk-mode--no-cursor",x.disableSelection&&"nice-kiosk-mode--no-select",!x.allowScrolling&&"nice-kiosk-mode--no-scroll",x.className].filter(Boolean).join(" ");return t.jsx(qe.Provider,{value:g,children:t.jsxs("div",{ref:u,className:m,onClick:c,children:[t.jsx("div",{className:"nice-kiosk-mode__content",children:C}),q.isAdminMode&&N&&t.jsxs("div",{className:"nice-kiosk-mode__admin",children:[t.jsxs("div",{className:"nice-kiosk-mode__admin-header",children:[t.jsx("h2",{className:"nice-kiosk-mode__admin-title",children:"Admin Mode"}),t.jsx("button",{className:"nice-kiosk-mode__admin-close",onClick:D,"aria-label":"Close admin panel",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-kiosk-mode__admin-content",children:N})]}),q.isScreensaverActive&&t.jsx("div",{className:"nice-kiosk-mode__screensaver",onClick:r,onTouchStart:r,children:h||t.jsx("div",{className:"nice-kiosk-mode__screensaver-default",children:t.jsx("div",{className:"nice-kiosk-mode__screensaver-text",children:"Touch to continue"})})}),q.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__pin-overlay",children:t.jsxs("div",{className:"nice-kiosk-mode__pin-dialog",children:[t.jsx("h3",{className:"nice-kiosk-mode__pin-title",children:"Enter PIN"}),t.jsx("input",{type:"password",className:`nice-kiosk-mode__pin-input ${Y?"nice-kiosk-mode__pin-input--error":""}`,value:V,onChange:w=>z(w.target.value),onKeyPress:F,maxLength:8,autoFocus:!0,placeholder:"••••"}),t.jsxs("div",{className:"nice-kiosk-mode__pin-buttons",children:[t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--cancel",onClick:l,children:"Cancel"}),t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--submit",onClick:j,children:"Unlock"})]}),Y&&t.jsx("div",{className:"nice-kiosk-mode__pin-error",children:"Incorrect PIN"})]})}),q.isLocked&&!q.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__lock-indicator",children:t.jsx("span",{className:"nice-kiosk-mode__lock-text",children:"Kiosk Locked"})})]})})});pe.displayName="NiceKioskMode";const Ue=pe;Ue.displayName="NiceKioskModeProvider";const He=e.createContext(null),Mt=()=>{const n=e.useContext(He);if(!n)throw new Error("useLowPowerMode must be used within NiceLowPowerModeProvider");return n},Ft={normal:{mode:"normal",brightness:1,wakeOnTouch:!0},dim:{mode:"dim",brightness:.6,disableAnimations:!1,wakeOnTouch:!0},low:{mode:"low",brightness:.3,frameRateCap:30,disableAnimations:!0,reduceImageQuality:!0,wakeOnTouch:!0},sleep:{mode:"sleep",brightness:0,frameRateCap:1,disableAnimations:!0,disableBackgroundProcesses:!0,reduceImageQuality:!0,wakeOnTouch:!0,wakeOnMotion:!0}},Bt={initialMode:"normal",autoDimTimeout:120*1e3,autoSleepTimeout:600*1e3,lowBatteryThreshold:20,criticalBatteryThreshold:5,wakeOnTouch:!0,wakeOnMotion:!1,transitionDuration:500},ye=e.forwardRef((n,f)=>{const{config:p,onModeChange:C,onBrightnessChange:h,onSleep:N,onWake:T,onLowBattery:P,children:i}=n,d={...Bt,...p},b={...Ft,...p==null?void 0:p.modes},L=e.useRef(null),x=e.useRef(null),u=e.useRef(Date.now()),y=e.useRef(null),[A,q]=e.useState({currentMode:d.initialMode,brightness:b[d.initialMode].brightness??1,isPowerSaving:d.initialMode!=="normal",isSleeping:d.initialMode==="sleep",idleTime:0,isDisplayOn:!0}),U=e.useCallback(D=>{const c=b[D];document.documentElement.style.setProperty("--lpm-brightness",String(c.brightness)),document.documentElement.style.setProperty("--lpm-transition",`${d.transitionDuration}ms`),c.disableAnimations?document.documentElement.classList.add("lpm-no-animations"):document.documentElement.classList.remove("lpm-no-animations"),c.reduceImageQuality?document.documentElement.classList.add("lpm-reduced-quality"):document.documentElement.classList.remove("lpm-reduced-quality")},[b,d.transitionDuration]),V=e.useCallback(D=>{q(c=>{if(c.currentMode===D)return c;const s=c.currentMode,a=b[D];return U(D),C==null||C(D,s),h==null||h(a.brightness??1),D==="sleep"&&s!=="sleep"?N==null||N():s==="sleep"&&D!=="sleep"&&(T==null||T()),{...c,currentMode:D,brightness:a.brightness??1,isPowerSaving:D!=="normal",isSleeping:D==="sleep",isDisplayOn:D!=="sleep"}})},[b,U,C,h,N,T]),z=e.useCallback(D=>{const c=Math.max(0,Math.min(1,D));document.documentElement.style.setProperty("--lpm-brightness",String(c)),q(s=>({...s,brightness:c})),h==null||h(c)},[h]),Y=e.useCallback(()=>{V("sleep")},[V]),B=e.useCallback(()=>{V("normal"),E()},[V]),G=e.useCallback(()=>{A.currentMode==="normal"?V("low"):V("normal")},[A.currentMode,V]),E=e.useCallback(()=>{if(u.current=Date.now(),L.current&&clearTimeout(L.current),x.current&&clearTimeout(x.current),A.isSleeping){B();return}A.currentMode!=="normal"&&A.currentMode!=="sleep"&&V("normal"),d.autoDimTimeout>0&&(L.current=setTimeout(()=>{A.currentMode==="normal"&&V("dim")},d.autoDimTimeout)),d.autoSleepTimeout>0&&(x.current=setTimeout(()=>{V("sleep")},d.autoSleepTimeout)),q(D=>({...D,idleTime:0}))},[A.isSleeping,A.currentMode,d.autoDimTimeout,d.autoSleepTimeout,V,B]),$=e.useCallback(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const D=await navigator.getBattery();return{level:Math.round(D.level*100),charging:D.charging}}catch{return{}}return{}},[]),R=e.useCallback(async()=>{const D=await $();D.level!==void 0&&(q(c=>({...c,batteryLevel:D.level,isCharging:D.charging})),D.charging||(D.level<=d.criticalBatteryThreshold?(V("sleep"),P==null||P(D.level)):D.level<=d.lowBatteryThreshold&&(A.currentMode==="normal"&&V("low"),P==null||P(D.level))))},[$,d.lowBatteryThreshold,d.criticalBatteryThreshold,A.currentMode,V,P]),k=e.useCallback(()=>{if(!(p!=null&&p.schedule)||p.schedule.length===0)return;const c=new Date().getHours();for(const s of p.schedule){const{startHour:a,endHour:r,mode:o}=s;let l;if(a<=r?l=c>=a&&c<r:l=c>=a||c<r,l){q(j=>({...j,scheduledModeActive:o})),A.currentMode!==o&&V(o);return}}q(s=>({...s,scheduledModeActive:void 0}))},[p==null?void 0:p.schedule,A.currentMode,V]);e.useEffect(()=>{const D=["mousedown","mousemove","keydown","touchstart","scroll"],c=()=>{d.wakeOnTouch&&E()};for(const s of D)document.addEventListener(s,c);return E(),()=>{for(const s of D)document.removeEventListener(s,c);L.current&&clearTimeout(L.current),x.current&&clearTimeout(x.current)}},[d.wakeOnTouch,E]),e.useEffect(()=>{R(),(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const c=await navigator.getBattery();y.current=c,c.addEventListener("levelchange",R),c.addEventListener("chargingchange",R)}catch{}})()},[R]),e.useEffect(()=>{k();const D=setInterval(k,6e4);return()=>clearInterval(D)},[k]),e.useEffect(()=>{U(d.initialMode)},[d.initialMode,U]),e.useImperativeHandle(f,()=>({getState:()=>A,setMode:V,setBrightness:z,sleep:Y,wake:B,togglePowerSaving:G,resetIdleTimer:E,getBatteryInfo:$}),[A,V,z,Y,B,G,E,$]);const S={...A,setMode:V,setBrightness:z,sleep:Y,wake:B,resetIdleTimer:E};return t.jsx(He.Provider,{value:S,children:t.jsxs("div",{className:`nice-lpm nice-lpm--${A.currentMode}`,children:[t.jsx("div",{className:"nice-lpm__overlay",style:{opacity:1-A.brightness}}),t.jsx("div",{className:"nice-lpm__content",children:i}),A.isSleeping&&t.jsx("div",{className:"nice-lpm__sleep-screen",onClick:d.wakeOnTouch?B:void 0,onTouchStart:d.wakeOnTouch?B:void 0,children:t.jsx("div",{className:"nice-lpm__sleep-message",children:"Touch to wake"})})]})})});ye.displayName="NiceLowPowerMode";const We=ye;We.displayName="NiceLowPowerModeProvider";const Ve=e.createContext(null),$t=()=>{const n=e.useContext(Ve);if(!n)throw new Error("useOrientationLock must be used within NiceOrientationLockProvider");return n},qt={preferredOrientation:"any",allowUserChange:!0,showRotationPrompt:!0,lockOnMount:!1,autoRotateContent:!1,supportedOrientations:["any","portrait","portrait-primary","portrait-secondary","landscape","landscape-primary","landscape-secondary","natural"]},ze=()=>{if(typeof window>"u")return"portrait";const n=window.screen;return n.orientation?n.orientation.type:window.innerHeight>window.innerWidth?"portrait":"landscape"},Ut=()=>{if(typeof window>"u")return 0;const n=window.screen;return n.orientation?n.orientation.angle:window.orientation||0},me=()=>{if(typeof window>"u")return{type:"portrait",angle:0,isPortrait:!0,isLandscape:!1,width:0,height:0,aspectRatio:0};const n=ze(),f=Ut(),p=window.screen.width,C=window.screen.height,h=n.includes("portrait")||window.innerHeight>window.innerWidth,N=n.includes("landscape")||window.innerWidth>window.innerHeight;return{type:n,angle:f,isPortrait:h,isLandscape:N,width:p,height:C,aspectRatio:p/C}},Ht=()=>{if(typeof window>"u")return!1;const n=window.screen;return!!(n.orientation&&typeof n.orientation.lock=="function")},be=e.forwardRef((n,f)=>{const{config:p,onOrientationChange:C,onLockChange:h,onUnsupportedOrientation:N,rotationPrompt:T,children:P,className:i}=n,d={...qt,...p},b=e.useRef(!1),[L,x]=e.useState(ze),[u,y]=e.useState(null),[A,q]=e.useState(me),[U]=e.useState(Ht),V=e.useCallback(c=>!!(d.supportedOrientations.includes("any")||d.supportedOrientations.includes(c)||c.includes("portrait")&&d.supportedOrientations.includes("portrait")||c.includes("landscape")&&d.supportedOrientations.includes("landscape")),[d.supportedOrientations]),z=e.useCallback(async c=>{if(!U)return console.warn("Screen Orientation API is not available"),y(c),h==null||h(!0,c),!1;try{return await window.screen.orientation.lock(c),y(c),h==null||h(!0,c),!0}catch(s){return console.warn("Failed to lock orientation:",s),y(c),h==null||h(!0,c),!1}},[U,h]),Y=e.useCallback(async()=>{if(y(null),h==null||h(!1,null),!U)return!1;try{return window.screen.orientation.unlock(),!0}catch(c){return console.warn("Failed to unlock orientation:",c),!1}},[U,h]),B=e.useCallback(async()=>u?Y():z(L),[u,L,z,Y]),G=e.useCallback(()=>me(),[]),E=e.useCallback(()=>{const c=me(),s=c.type;x(s),q(c),C==null||C(c),V(s)||N==null||N(s,d.supportedOrientations)},[d.supportedOrientations,V,C,N]);e.useEffect(()=>{b.current||(b.current=!0,E(),d.lockOnMount&&d.preferredOrientation!=="any"&&z(d.preferredOrientation))},[d.lockOnMount,d.preferredOrientation,E,z]),e.useEffect(()=>{const c=window.screen.orientation;return c&&c.addEventListener("change",E),window.addEventListener("resize",E),window.addEventListener("orientationchange",E),()=>{c&&c.removeEventListener("change",E),window.removeEventListener("resize",E),window.removeEventListener("orientationchange",E)}},[E]);const $={current:L,locked:u,isLocked:u!==null,isSupported:V(L),info:A,isApiAvailable:U};e.useImperativeHandle(f,()=>({getState:()=>$,lock:z,unlock:Y,toggleLock:B,getOrientationInfo:G,isOrientationSupported:V}),[$,z,Y,B,G,V]);const R={...$,lock:z,unlock:Y,getOrientationInfo:G},k=e.useCallback(()=>{if(!d.autoRotateContent||!u||u==="any")return;const c=u.includes("portrait"),s=A.isPortrait;return c===s?void 0:{transform:`rotate(${c?90:-90}deg)`,transformOrigin:"center center",width:c?A.height:A.width,height:c?A.width:A.height}},[d.autoRotateContent,u,A]),S=d.showRotationPrompt&&u!==null&&u!=="any"&&!$.isSupported,D=["nice-orientation",`nice-orientation--${L}`,u&&`nice-orientation--locked-${u}`,!$.isSupported&&"nice-orientation--unsupported",i].filter(Boolean).join(" ");return t.jsx(Ve.Provider,{value:R,children:t.jsxs("div",{className:D,style:k(),"data-orientation":L,"data-locked":u||void 0,children:[P,S&&t.jsx("div",{className:"nice-orientation__prompt",children:T||t.jsxs("div",{className:"nice-orientation__prompt-content",children:[t.jsx("div",{className:"nice-orientation__prompt-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--device","aria-hidden":"true"})}),t.jsxs("p",{className:"nice-orientation__prompt-text",children:["Please rotate your device to"," ",u!=null&&u.includes("portrait")?"portrait":"landscape"," mode"]})]})})]})})});be.displayName="NiceOrientationLock";const Ge=be;Ge.displayName="NiceOrientationLockProvider";const Ye=e.createContext(null),Wt=()=>{const n=e.useContext(Ye);if(!n)throw new Error("useRemoteManagement must be used within NiceRemoteManagementProvider");return n},Vt={heartbeatInterval:3e4,reconnectDelay:5e3,maxReconnectAttempts:10,enableHealthMonitoring:!0,healthReportInterval:6e4,enableScreenshot:!0,enableLogs:!0,logBufferSize:100},we=e.forwardRef((n,f)=>{const{config:p,onConnectionChange:C,onCommandReceived:h,onCustomCommand:N,children:T}=n,P={...Vt,...p},i=e.useRef(null),d=e.useRef(null),b=e.useRef(null),L=e.useRef([]),x=e.useRef(Date.now()),u=e.useRef(0),[y,A]=e.useState({status:"disconnected",isConnected:!1,reconnectAttempts:0,pendingCommands:[],commandHistory:[]}),q=e.useCallback(()=>{const k=typeof navigator<"u"?navigator:null,S=typeof window<"u"?window:null;return{deviceId:P.deviceId,name:P.deviceName||P.deviceId,type:"embedded-display",os:k==null?void 0:k.platform,browser:k==null?void 0:k.userAgent,resolution:S?`${S.screen.width}x${S.screen.height}`:void 0,uptime:Math.floor((Date.now()-x.current)/1e3),metadata:{}}},[P.deviceId,P.deviceName]),U=e.useCallback(async()=>{const k={isOnline:typeof navigator<"u"?navigator.onLine:!0,lastUpdated:new Date};if(typeof performance<"u"&&"memory"in performance){const S=performance.memory;S&&(k.memory=Math.round(S.usedJSHeapSize/S.jsHeapSizeLimit*100))}if(typeof navigator<"u"&&"getBattery"in navigator)try{const S=await navigator.getBattery();k.battery=Math.round(S.level*100)}catch{}if(typeof navigator<"u"&&"storage"in navigator&&"estimate"in navigator.storage)try{const S=await navigator.storage.estimate();S.quota&&S.usage&&(k.storageFree=S.quota-S.usage)}catch{}return k},[]),V=e.useCallback(async()=>{var k;if(((k=i.current)==null?void 0:k.readyState)!==WebSocket.OPEN){A(S=>({...S,status:"connecting"})),C==null||C("connecting");try{const S=new URL(P.serverUrl);S.searchParams.set("deviceId",P.deviceId),P.apiKey&&S.searchParams.set("apiKey",P.apiKey);const D=new WebSocket(S.toString());i.current=D,D.onopen=()=>{u.current=0,A(c=>({...c,status:"connected",isConnected:!0,reconnectAttempts:0,error:void 0})),C==null||C("connected"),D.send(JSON.stringify({type:"register",payload:q()}))},D.onmessage=async c=>{try{const s=JSON.parse(c.data);if(s.type==="command"){const a={id:s.id,type:s.commandType,payload:s.payload,timestamp:new Date,acknowledged:!0,executed:!1};A(l=>({...l,pendingCommands:[...l.pendingCommands,a]})),h==null||h(a);let r,o;try{switch(a.type){case"restart":typeof window<"u"&&window.location.reload();break;case"screenshot":r=await $();break;case"logs":r=L.current;break;case"custom":N&&(r=await N(a));break}a.executed=!0,a.result=r}catch(l){o=l instanceof Error?l.message:String(l),a.error=o}D.send(JSON.stringify({type:"commandResult",commandId:a.id,result:r,error:o})),A(l=>({...l,pendingCommands:l.pendingCommands.filter(j=>j.id!==a.id),commandHistory:[...l.commandHistory.slice(-49),a]}))}}catch{}},D.onerror=()=>{i.current===D&&A(c=>({...c,status:"error",error:"WebSocket error"}))},D.onclose=()=>{i.current===D&&(i.current=null,A(c=>({...c,status:"disconnected",isConnected:!1})),u.current<P.maxReconnectAttempts&&setTimeout(()=>{u.current>=P.maxReconnectAttempts||(u.current+=1,A(c=>({...c,reconnectAttempts:u.current})),V())},P.reconnectDelay),C==null||C("disconnected"))}}catch(S){A(D=>({...D,status:"error",error:S instanceof Error?S.message:"Connection failed"})),C==null||C("error")}}},[P.serverUrl,P.deviceId,P.apiKey,P.maxReconnectAttempts,P.reconnectDelay,q,C,h,N]),z=e.useCallback(()=>{u.current=P.maxReconnectAttempts,i.current&&(i.current.close(),i.current=null),A(k=>({...k,status:"disconnected",isConnected:!1,reconnectAttempts:P.maxReconnectAttempts}))},[P.maxReconnectAttempts]),Y=e.useCallback(async()=>{var k;((k=i.current)==null?void 0:k.readyState)===WebSocket.OPEN&&(i.current.send(JSON.stringify({type:"heartbeat",timestamp:new Date().toISOString(),deviceId:P.deviceId})),A(S=>({...S,lastHeartbeat:new Date})))},[P.deviceId]),B=e.useCallback(async k=>{var D;if(((D=i.current)==null?void 0:D.readyState)!==WebSocket.OPEN)return;const S=k||await U();i.current.send(JSON.stringify({type:"health",metrics:S,deviceId:P.deviceId})),A(c=>({...c,healthMetrics:S}))},[P.deviceId,U]),G=e.useCallback(async(k,S,D)=>{var c;((c=i.current)==null?void 0:c.readyState)===WebSocket.OPEN&&i.current.send(JSON.stringify({type:"commandResult",commandId:k,result:S,error:D}))},[]),E=e.useCallback((k,S,D)=>{var s;const c={level:k,message:S,data:D,timestamp:new Date};L.current=[...L.current.slice(-(P.logBufferSize-1)),c],P.enableLogs&&((s=i.current)==null?void 0:s.readyState)===WebSocket.OPEN&&i.current.send(JSON.stringify({type:"log",...c,deviceId:P.deviceId}))},[P.deviceId,P.enableLogs,P.logBufferSize]),$=e.useCallback(async()=>{if(P.enableScreenshot)try{return"screenshot-not-implemented"}catch{return}},[P.enableScreenshot]);e.useEffect(()=>(u.current=0,V(),()=>{z(),d.current&&clearInterval(d.current),b.current&&clearInterval(b.current)}),[]),e.useEffect(()=>{if(y.isConnected)return d.current=setInterval(Y,P.heartbeatInterval),()=>{d.current&&clearInterval(d.current)}},[y.isConnected,P.heartbeatInterval,Y]),e.useEffect(()=>{if(!(!y.isConnected||!P.enableHealthMonitoring))return b.current=setInterval(()=>{B()},P.healthReportInterval),B(),()=>{b.current&&clearInterval(b.current)}},[y.isConnected,P.enableHealthMonitoring,P.healthReportInterval,B]),e.useImperativeHandle(f,()=>({getState:()=>y,connect:V,disconnect:z,sendHeartbeat:Y,sendHealthMetrics:B,reportCommandResult:G,sendLog:E,captureScreenshot:$,getDeviceInfo:q}),[y,V,z,Y,B,G,E,$,q]);const R={...y,deviceInfo:q(),connect:V,disconnect:z,sendLog:E};return t.jsx(Ye.Provider,{value:R,children:T})});we.displayName="NiceRemoteManagement";const Xe=we;Xe.displayName="NiceRemoteManagementProvider";const zt={modes:["pixel-shift","dimming"],inactivityTimeout:300*1e3,pixelShift:{maxShift:3,interval:6e4,smooth:!0},colorCycle:{colors:["var(--nice-text-primary, #000000)","var(--nice-text, #111111)","var(--nice-bg, #0a0a0a)"],interval:3e4,transitionDuration:1e3},dimming:{level:.3,fadeDuration:2e3},screensaver:{type:"blank"},staticDetectionThreshold:3e4,autoDetectStatic:!1},Ke=e.forwardRef((n,f)=>{var j,F,g,m,w,O;const{config:p,enabled:C=!0,onActivate:h,onDeactivate:N,onModeChange:T,children:P}=n,i={...zt,...p},d=e.useRef(null),b=e.useRef(null),L=e.useRef(null),x=e.useRef(null),[u,y]=e.useState({isActive:!1,activeModes:[],shiftX:0,shiftY:0,isDimmed:!1,isScreensaverActive:!1,idleTime:0}),[A,q]=e.useState(0),[U,V]=e.useState({x:50,y:50,dx:1,dy:1}),z=e.useCallback(()=>{if(!i.pixelShift)return;const{maxShift:_}=i.pixelShift,W=Math.floor(Math.random()*(_*2+1))-_,I=Math.floor(Math.random()*(_*2+1))-_;y(H=>({...H,shiftX:W,shiftY:I}))},[i.pixelShift]),Y=e.useCallback(()=>{!i.pixelShift||L.current||(z(),L.current=setInterval(z,i.pixelShift.interval))},[i.pixelShift,z]),B=e.useCallback(()=>{L.current&&(clearInterval(L.current),L.current=null),y(_=>({..._,shiftX:0,shiftY:0}))},[]),G=e.useCallback(()=>{!i.colorCycle||x.current||(x.current=setInterval(()=>{q(_=>{var W;return(_+1)%(((W=i.colorCycle)==null?void 0:W.colors.length)||1)})},i.colorCycle.interval))},[i.colorCycle]),E=e.useCallback(()=>{x.current&&(clearInterval(x.current),x.current=null),q(0)},[]),$=e.useCallback(()=>{if(!C||u.isActive)return;const _=i.modes;y(W=>({...W,isActive:!0,activeModes:_})),_.includes("pixel-shift")&&Y(),_.includes("color-cycling")&&G(),_.includes("dimming")&&y(W=>({...W,isDimmed:!0})),_.includes("screensaver")&&y(W=>({...W,isScreensaverActive:!0})),h==null||h(),T==null||T(_)},[C,u.isActive,i.modes,Y,G,h,T]),R=e.useCallback(()=>{u.isActive&&(B(),E(),y(_=>({..._,isActive:!1,activeModes:[],isDimmed:!1,isScreensaverActive:!1})),N==null||N(),T==null||T([]))},[u.isActive,B,E,N,T]),k=e.useCallback(()=>{u.isActive?R():$()},[u.isActive,$,R]),S=e.useCallback(()=>{b.current&&clearTimeout(b.current),u.isActive&&R(),C&&i.inactivityTimeout>0&&(b.current=setTimeout(()=>{$()},i.inactivityTimeout))},[C,u.isActive,i.inactivityTimeout,$,R]),D=e.useCallback(()=>{y(_=>({..._,isScreensaverActive:!0}))},[]),c=e.useCallback(()=>{y(_=>({..._,isScreensaverActive:!1})),S()},[S]),s=e.useCallback(_=>{y(W=>({...W,isDimmed:_>0}))},[]);e.useEffect(()=>{var W;if(!u.isScreensaverActive||((W=i.screensaver)==null?void 0:W.type)!=="bounce")return;const _=setInterval(()=>{V(I=>{let{x:H,y:M,dx:X,dy:v}=I;return H+=X*.5,M+=v*.5,(H<=0||H>=90)&&(X=-X),(M<=0||M>=90)&&(v=-v),{x:H,y:M,dx:X,dy:v}})},50);return()=>clearInterval(_)},[u.isScreensaverActive,(j=i.screensaver)==null?void 0:j.type]),e.useEffect(()=>{if(!C)return;const _=["mousedown","mousemove","keydown","touchstart","scroll","wheel"],W=()=>{S()};for(const I of _)document.addEventListener(I,W);return S(),()=>{for(const I of _)document.removeEventListener(I,W);b.current&&clearTimeout(b.current),B(),E()}},[C,S,B,E]),e.useImperativeHandle(f,()=>({getState:()=>u,activate:$,deactivate:R,toggle:k,resetIdleTimer:S,forceShift:z,showScreensaver:D,hideScreensaver:c,setDimLevel:s}),[u,$,R,k,S,z,D,c,s]);const a=()=>{if(!u.isScreensaverActive)return null;const _=i.screensaver||{type:"blank"};switch(_.type){case"blank":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--blank",onClick:c,onTouchStart:c});case"bounce":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--bounce",onClick:c,onTouchStart:c,children:t.jsx("div",{className:"nice-sbp__bounce-logo",style:{left:`${U.x}%`,top:`${U.y}%`},children:t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"1em",height:"1em",background:"currentColor",clipPath:"polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0% 50%)"}})})});case"matrix":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--matrix",onClick:c,onTouchStart:c,children:Array.from({length:20}).map((W,I)=>t.jsx("div",{className:"nice-sbp__matrix-column",style:{left:`${I*5}%`,animationDelay:`${Math.random()*5}s`,animationDuration:`${5+Math.random()*5}s`},children:Array.from({length:20}).map((H,M)=>t.jsx("span",{children:String.fromCharCode(12448+Math.random()*96)},M))},I))});case"noise":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--noise",onClick:c,onTouchStart:c});case"custom":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--custom",onClick:c,onTouchStart:c,children:_.component});default:return null}},r={transform:u.isActive&&i.modes.includes("pixel-shift")?`translate(${u.shiftX}px, ${u.shiftY}px)`:void 0,transition:(F=i.pixelShift)!=null&&F.smooth?"transform 0.5s ease":void 0},o={"--dim-level":u.isDimmed?((g=i.dimming)==null?void 0:g.level)||.3:0,"--dim-duration":`${((m=i.dimming)==null?void 0:m.fadeDuration)||2e3}ms`},l=u.isActive&&i.modes.includes("color-cycling")?{backgroundColor:(w=i.colorCycle)==null?void 0:w.colors[A],transition:`background-color ${((O=i.colorCycle)==null?void 0:O.transitionDuration)||1e3}ms ease`}:{};return t.jsxs("div",{ref:d,className:`nice-sbp ${u.isActive?"nice-sbp--active":""}`,style:{...l},children:[t.jsx("div",{className:"nice-sbp__content",style:r,children:P}),u.isDimmed&&t.jsx("div",{className:"nice-sbp__dim-overlay",style:o,onClick:S,onTouchStart:S}),a(),u.isActive&&i.modes.includes("invert")&&t.jsx("div",{className:"nice-sbp__invert-overlay"})]})});Ke.displayName="NiceScreenBurnPrevention";const Gt={pointCount:5,targetSize:40,accuracyThreshold:20,pointTimeout:1e4,showAccuracy:!0,allowRetry:!0,persistCalibration:!0,storageKey:"nice-touch-calibration"},Yt=n=>({4:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:90,targetY:90},{targetX:10,targetY:90}],5:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:50,targetY:50},{targetX:10,targetY:90},{targetX:90,targetY:90}],9:[{targetX:10,targetY:10},{targetX:50,targetY:10},{targetX:90,targetY:10},{targetX:10,targetY:50},{targetX:50,targetY:50},{targetX:90,targetY:50},{targetX:10,targetY:90},{targetX:50,targetY:90},{targetX:90,targetY:90}]})[n],Qe=e.forwardRef((n,f)=>{const{config:p,autoStart:C=!1,onStart:h,onPointCalibrated:N,onComplete:T,onCancel:P,children:i}=n,d={...Gt,...p},b=e.useRef(null),L=e.useRef(null),[x,u]=e.useState({isActive:!1,currentPointIndex:0,totalPoints:d.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),y=e.useCallback(k=>{const S=k.filter(M=>M.calibrated&&M.actualX!==void 0&&M.actualY!==void 0);if(S.length<3)return{scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};let D=0,c=0,s=0,a=0;const r=S.length;for(const M of S)D+=M.targetX,c+=M.targetY,s+=M.actualX,a+=M.actualY;const o=D/r,l=c/r,j=s/r,F=a/r;let g=0,m=0,w=0,O=0;for(const M of S){const X=M.targetX-o,v=M.targetY-l,J=M.actualX-j,Q=M.actualY-F;g+=X*X,m+=X*J,w+=v*v,O+=v*Q}const _=m!==0?g/m:1,W=O!==0?w/O:1,I=o-_*j,H=l-W*F;return{scaleX:_,scaleY:W,offsetX:I,offsetY:H,rotation:0}},[]),A=e.useCallback((k,S)=>{const D=k.filter(s=>s.calibrated);if(D.length===0)return 0;let c=0;for(const s of D){if(s.actualX===void 0||s.actualY===void 0)continue;const a=S.scaleX*s.actualX+S.offsetX,r=S.scaleY*s.actualY+S.offsetY,o=s.targetX-a,l=s.targetY-r;c+=Math.sqrt(o*o+l*l)}return c/D.length},[]),q=e.useCallback(()=>{const S=Yt(d.pointCount).map(D=>({...D,calibrated:!1}));u({isActive:!0,currentPointIndex:0,totalPoints:d.pointCount,points:S,isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),h==null||h()},[d.pointCount,h]),U=e.useCallback(()=>{L.current&&clearTimeout(L.current),u(k=>({...k,isActive:!1,isCompleted:!1})),P==null||P()},[P]),V=e.useCallback(()=>{u(k=>({...k,isCompleted:!1}))},[]),z=e.useCallback(()=>{if(d.persistCalibration)try{localStorage.removeItem(d.storageKey)}catch{}u({isActive:!1,currentPointIndex:0,totalPoints:d.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0})},[d.persistCalibration,d.storageKey,d.pointCount]),Y=e.useCallback(k=>{const S=y(k),D=A(k,S),c=D<=d.accuracyThreshold;if(d.persistCalibration&&c)try{localStorage.setItem(d.storageKey,JSON.stringify({matrix:S,points:k}))}catch{}u(s=>({...s,points:k,isActive:!1,isCompleted:!0,isSuccessful:c,matrix:S,averageError:D})),T==null||T(S,c)},[d.accuracyThreshold,d.persistCalibration,d.storageKey,y,A,T]),B=e.useCallback(k=>{if(!x.isActive||!b.current)return;k.preventDefault();const S=b.current.getBoundingClientRect();let D,c;"touches"in k?(D=k.touches[0].clientX,c=k.touches[0].clientY):(D=k.clientX,c=k.clientY);const s=(D-S.left)/S.width*100,a=(c-S.top)/S.height*100,r=x.currentPointIndex,o=[...x.points];o[r]={...o[r],actualX:s,actualY:a,calibrated:!0};const l=r+1;N==null||N(o[r],r),l>=x.totalPoints?Y(o):u(j=>({...j,currentPointIndex:l,points:o}))},[x.isActive,x.currentPointIndex,x.points,x.totalPoints,Y,N]),G=e.useCallback((k,S)=>{const D=x.matrix;return D?{x:D.scaleX*k+D.offsetX,y:D.scaleY*S+D.offsetY}:{x:k,y:S}},[x.matrix]),E=e.useCallback(()=>{if(x.matrix)return!0;if(d.persistCalibration)try{return!!localStorage.getItem(d.storageKey)}catch{return!1}return!1},[x.matrix,d.persistCalibration,d.storageKey]),$=e.useCallback(()=>{if(d.persistCalibration)try{localStorage.removeItem(d.storageKey)}catch{}u(k=>({...k,matrix:null}))},[d.persistCalibration,d.storageKey]);if(e.useEffect(()=>{if(d.persistCalibration)try{const k=localStorage.getItem(d.storageKey);if(k){const S=JSON.parse(k);u(D=>({...D,matrix:S.matrix,points:S.points||[],isCompleted:!0,isSuccessful:!0}))}}catch{}},[d.persistCalibration,d.storageKey]),e.useEffect(()=>{if(!x.isActive)return;const k=b.current;if(k)return k.addEventListener("touchstart",B,{passive:!1}),k.addEventListener("mousedown",B),()=>{k.removeEventListener("touchstart",B),k.removeEventListener("mousedown",B)}},[x.isActive,B]),e.useEffect(()=>{if(!(!x.isActive||d.pointTimeout<=0))return L.current=setTimeout(()=>{x.currentPointIndex<x.totalPoints-1?u(k=>({...k,currentPointIndex:k.currentPointIndex+1})):Y(x.points)},d.pointTimeout),()=>{L.current&&clearTimeout(L.current)}},[x.isActive,x.currentPointIndex,x.points,x.totalPoints,d.pointTimeout,Y]),e.useEffect(()=>{C&&!E()&&q()},[C,E,q]),e.useImperativeHandle(f,()=>({getState:()=>x,start:q,cancel:U,reset:z,getMatrix:()=>x.matrix,transformPoint:G,hasCalibration:E,clearCalibration:$}),[x,q,U,z,G,E,$]),!x.isActive&&!x.isCompleted)return t.jsx(t.Fragment,{children:i});const R=x.isActive?x.points[x.currentPointIndex]:void 0;return t.jsxs("div",{ref:b,className:"nice-touch-calibration",children:[t.jsxs("div",{className:"nice-touch-calibration__overlay",children:[t.jsxs("div",{className:"nice-touch-calibration__instructions",children:[t.jsx("h2",{className:"nice-touch-calibration__title",children:"Touch Screen Calibration"}),t.jsx("p",{className:"nice-touch-calibration__text",children:"Touch the center of each target to calibrate your screen."}),t.jsxs("div",{className:"nice-touch-calibration__progress",children:["Point ",x.currentPointIndex+1," of ",x.totalPoints]})]}),R&&t.jsx("div",{className:"nice-touch-calibration__target",style:{left:`${R.targetX}%`,top:`${R.targetY}%`,width:d.targetSize,height:d.targetSize},children:(p==null?void 0:p.targetComponent)||t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"nice-touch-calibration__target-outer"}),t.jsx("div",{className:"nice-touch-calibration__target-inner"}),t.jsx("div",{className:"nice-touch-calibration__target-center"})]})}),x.points.map((k,S)=>k.calibrated&&t.jsx("div",{className:"nice-touch-calibration__calibrated",style:{left:`${k.actualX}%`,top:`${k.actualY}%`}},S)),x.isActive&&t.jsx("button",{className:"nice-touch-calibration__cancel",onClick:U,children:"Cancel"})]}),x.isCompleted&&t.jsxs("div",{className:"nice-touch-calibration__result",children:[t.jsx("div",{className:`nice-touch-calibration__result-icon ${x.isSuccessful?"nice-touch-calibration__result-icon--success":"nice-touch-calibration__result-icon--error"}`,children:t.jsx("span",{className:`nice-platform-mark nice-platform-mark--${x.isSuccessful?"check":"alert"}`,"aria-hidden":"true"})}),t.jsx("h3",{className:"nice-touch-calibration__result-title",children:x.isSuccessful?"Calibration Complete":"Calibration Failed"}),d.showAccuracy&&t.jsxs("p",{className:"nice-touch-calibration__result-accuracy",children:["Average error: ",x.averageError.toFixed(1),"px"]}),!x.isSuccessful&&d.allowRetry&&t.jsx("button",{className:"nice-touch-calibration__retry",onClick:q,children:"Retry Calibration"}),t.jsx("button",{className:"nice-touch-calibration__retry nice-touch-calibration__done",onClick:V,children:"Done"})]})]})});Qe.displayName="NiceTouchCalibration";const Xt={format:"code128",width:2,height:100,displayValue:!0,font:"monospace",fontSize:14,textAlign:"center",textPosition:"bottom",textMargin:2,background:"#ffffff",lineColor:"#000000",margin:10,flat:!1},Ee=104,Kt=106,Qt=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",oe=["11011001100","11001101100","11001100110","10010011000","10010001100","10001001100","10011001000","10011000100","10001100100","11001001000","11001000100","11000100100","10110011100","10011011100","10011001110","10111001100","10011101100","10011100110","11001110010","11001011100","11001001110","11011100100","11001110100","11101101110","11101001100","11100101100","11100100110","11101100100","11100110100","11100110010","11011011000","11011000110","11000110110","10100011000","10001011000","10001000110","10110001000","10001101000","10001100010","11010001000","11000101000","11000100010","10110111000","10110001110","10001101110","10111011000","10111000110","10001110110","11101110110","11010001110","11000101110","11011101000","11011100010","11011101110","11101011000","11101000110","11100010110","11101101000","11101100010","11100011010","11101111010","11001000010","11110001010","10100110000","10100001100","10010110000","10010000110","10000101100","10000100110","10110010000","10110000100","10011010000","10011000010","10000110100","10000110010","11000010010","11001010000","11110111010","11000010100","10001111010","10100111100","10010111100","10010011110","10111100100","10011110100","10011110010","11110100100","11110010100","11110010010","11011011110","11011110110","11110110110","10101111000","10100011110","10001011110","10111101000","10111100010","11110101000","11110100010","10111011110","10111101110","11101011110","11110101110","11010000100","11010010000","11010011100","1100011101011"],Le=n=>{let f=oe[Ee],p=Ee;for(let C=0;C<n.length;C++){const h=n[C],N=Qt.indexOf(h);N!==-1&&(f+=oe[N],p+=N*(C+1))}return p=p%103,f+=oe[p],f+=oe[Kt],f},Je=["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],Jt=["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"],Ze=["1110010","1100110","1101100","1000010","1011100","1001110","1010000","1000100","1001000","1110100"],Zt=["LLLLLL","LLGLGG","LLGGLG","LLGGGL","LGLLGG","LGGLLG","LGGGLL","LGLGLG","LGLGGL","LGGLGL"],en=n=>{let f=0;for(let p=0;p<12;p++)f+=parseInt(n[p])*(p%2===0?1:3);return(10-f%10)%10},tn=n=>{let f=n.replace(/\D/g,"").slice(0,12).padStart(12,"0");const p=en(f);f+=p;const C=parseInt(f[0]),h=Zt[C];let N="101";for(let T=1;T<=6;T++){const P=parseInt(f[T]);N+=h[T-1]==="L"?Je[P]:Jt[P]}N+="01010";for(let T=7;T<=12;T++){const P=parseInt(f[T]);N+=Ze[P]}return N+="101",N},nn=n=>{let f=n.replace(/\D/g,"").slice(0,7).padStart(7,"0"),p=0;for(let N=0;N<7;N++)p+=parseInt(f[N])*(N%2===0?3:1);const C=(10-p%10)%10;f+=C;let h="101";for(let N=0;N<4;N++)h+=Je[parseInt(f[N])];h+="01010";for(let N=4;N<8;N++)h+=Ze[parseInt(f[N])];return h+="101",h},sn={0:"101001101101",1:"110100101011",2:"101100101011",3:"110110010101",4:"101001101011",5:"110100110101",6:"101100110101",7:"101001011011",8:"110100101101",9:"101100101101",A:"110101001011",B:"101101001011",C:"110110100101",D:"101011001011",E:"110101100101",F:"101101100101",G:"101010011011",H:"110101001101",I:"101101001101",J:"101011001101",K:"110101010011",L:"101101010011",M:"110110101001",N:"101011010011",O:"110101101001",P:"101101101001",Q:"101010110011",R:"110101011001",S:"101101011001",T:"101011011001",U:"110010101011",V:"100110101011",W:"110011010101",X:"100101101011",Y:"110010110101",Z:"100110110101","-":"100101011011",".":"110010101101"," ":"100110101101",$:"100100100101","/":"100100101001","+":"100101001001","%":"101001001001","*":"100101101101"},rn=n=>{const f=("*"+n.toUpperCase()+"*").split("");let p="";for(const C of f){const h=sn[C];h&&(p+=h+"0")}return p.slice(0,-1)},Pe=n=>{switch(n){case"code128":return Le;case"code39":case"code93":return rn;case"ean13":return tn;case"ean8":return nn;default:return Le}},et=e.forwardRef((n,f)=>{const{value:p,options:C,onGenerate:h,onError:N,showBorder:T=!1,className:P}=n,i={...Xt,...C},d=e.useRef(null),b=e.useRef(null),[L,x]=e.useState(null),[u,y]=e.useState(null),A=e.useCallback(()=>{if(!d.current||!p)return;const G=d.current,E=G.getContext("2d");if(E)try{const R=Pe(i.format)(p),k=i.width,S=R.length*k,D=i.marginTop??i.margin,c=i.marginBottom??i.margin,s=i.marginLeft??i.margin,a=i.marginRight??i.margin,r=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,o=S+s+a,l=i.height+D+c+r;G.width=o,G.height=l,E.fillStyle=i.background,E.fillRect(0,0,o,l),E.fillStyle=i.lineColor;let j=s;const F=i.textPosition==="top"&&i.displayValue?D+r:D;for(let m=0;m<R.length;m++)R[m]==="1"&&E.fillRect(j,F,k,i.height),j+=k;if(i.displayValue&&!i.flat){E.fillStyle=i.lineColor,E.font=`${i.fontSize}px ${i.font}`,E.textBaseline=i.textPosition==="top"?"top":"bottom";let m=s;i.textAlign==="center"?(m=s+S/2,E.textAlign="center"):i.textAlign==="right"?(m=s+S,E.textAlign="right"):E.textAlign="left";const w=i.textPosition==="top"?D+i.textMargin:l-c-i.textMargin;E.fillText(p,m,w)}const g=G.toDataURL("image/png");y(g),x(null),h==null||h(g)}catch($){const R=$ instanceof Error?$.message:"Failed to generate barcode";x(R),N==null||N(new Error(R))}},[p,i,h,N]);e.useEffect(()=>{A()},[A]);const q=e.useCallback((G="image/png",E=1)=>{var $;return(($=d.current)==null?void 0:$.toDataURL(G,E))||null},[]),U=e.useCallback(()=>{if(!d.current||!p)return null;try{const E=Pe(i.format)(p),$=i.width,R=i.marginTop??i.margin,k=i.marginBottom??i.margin,S=i.marginLeft??i.margin,D=i.marginRight??i.margin,c=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,s=E.length*$,a=s+S+D,r=i.height+R+k+c,o=[];let l=S;const j=i.textPosition==="top"&&i.displayValue?R+c:R;for(let g=0;g<E.length;g++)E[g]==="1"&&o.push(`<rect x="${l}" y="${j}" width="${$}" height="${i.height}" fill="${i.lineColor}"/>`),l+=$;let F="";if(i.displayValue&&!i.flat){const g=i.textAlign==="center"?"middle":i.textAlign==="right"?"end":"start";let m=S;i.textAlign==="center"?m=S+s/2:i.textAlign==="right"&&(m=S+s);const w=i.textPosition==="top"?R+i.fontSize:r-k-i.textMargin;F=`<text x="${m}" y="${w}" font-family="${i.font}" font-size="${i.fontSize}" text-anchor="${g}" fill="${i.lineColor}">${p}</text>`}return`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${r}" viewBox="0 0 ${a} ${r}">
|
|
1
|
+
"use strict";var jt=Object.defineProperty;var At=(n,f,h)=>f in n?jt(n,f,{enumerable:!0,configurable:!0,writable:!0,value:h}):n[f]=h;var oe=(n,f,h)=>At(n,typeof f!="symbol"?f+"":f,h);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),ue=e.createContext(null),Dt=()=>{const n=e.useContext(ue);if(!n)throw new Error("useAutoStart must be used within NiceAutoStartProvider");return n},Et={showSplash:!0,splashDuration:2e3,autoHideSplash:!0,showProgress:!0,showTaskNames:!0,globalTimeout:6e4,autoRecovery:!0,recoveryAttempts:3,recoveryDelay:2e3,checkUpdates:!1,sendAnalytics:!1},ge=e.forwardRef((n,f)=>{const{tasks:h=[],config:k,splash:g,errorScreen:N,onComplete:R,onTaskComplete:G,onError:i,onRecovery:l,children:y}=n,A={...Et,...k},v=e.useRef(0),d=e.useRef(h),p=e.useRef(null),[j,B]=e.useState(A.showSplash),[q,z]=e.useState({phase:"initializing",isLoading:!0,isReady:!1,hasError:!1,progress:0,completedTasks:0,totalTasks:h.length,results:[],recoveryAttempt:0,totalDuration:0}),Y=e.useCallback(async s=>{const r=Date.now();let a=0;const c=async()=>{try{const o=s.timeout||A.globalTimeout,S=new Promise((E,m)=>{setTimeout(()=>m(new Error("Task timeout")),o)});return await Promise.race([s.execute(),S]),{taskId:s.id,success:!0,duration:Date.now()-r,retriesUsed:a}}catch(o){const S=s.retries??0;return a<S?(a++,await new Promise(E=>setTimeout(E,500)),c()):{taskId:s.id,success:!1,error:o instanceof Error?o:new Error(String(o)),duration:Date.now()-r,retriesUsed:a}}};return c()},[A.globalTimeout]),K=e.useCallback(s=>{const r=[],a=[...s],c=new Set;for(;a.length>0;){const o=a.filter(E=>E.dependencies?E.dependencies.every(m=>c.has(m)):!0);if(o.length===0){r.push(...a);break}o.sort((E,m)=>(m.priority??0)-(E.priority??0));const S=o[0];r.push(S),c.add(S.id),a.splice(a.indexOf(S),1)}return r},[]),F=e.useCallback(async()=>{v.current=Date.now();const s=new AbortController;p.current=s;const r=K(d.current),a=[];z(o=>({...o,phase:"loading",isLoading:!0,isReady:!1,hasError:!1,errorMessage:void 0,progress:0,completedTasks:0,totalTasks:r.length,results:[]}));for(let o=0;o<r.length;o++){if(s.signal.aborted)return;const S=r[o];z(m=>({...m,currentTask:S.name,progress:Math.round(o/r.length*100)}));const E=await Y(S);if(s.signal.aborted)return;if(a.push(E),z(m=>({...m,completedTasks:o+1,results:[...m.results,E]})),G==null||G(E),!E.success&&S.critical){const m=E.error||new Error("Critical task failed");i==null||i(m,S.id),z(w=>({...w,phase:"error",isLoading:!1,hasError:!0,errorMessage:m.message}));return}}const c=Date.now()-v.current;if(z(o=>({...o,phase:"ready",isLoading:!1,isReady:!0,currentTask:void 0,progress:100,totalDuration:c})),R==null||R(a),A.autoHideSplash){const o=Date.now()-v.current,S=Math.max(0,A.splashDuration-o);setTimeout(()=>{B(!1)},S)}},[K,Y,A.autoHideSplash,A.splashDuration,G,i,R]),V=e.useCallback(async()=>{p.current&&p.current.abort(),z(s=>({...s,recoveryAttempt:0})),B(A.showSplash),await F()},[A.showSplash,F]),I=e.useCallback(()=>{p.current&&p.current.abort(),z(s=>({...s,phase:"ready",isLoading:!1,isReady:!0,progress:100})),B(!1)},[]),U=e.useCallback(()=>{B(!1)},[]),D=e.useCallback(async()=>{const s=q.recoveryAttempt+1;s>A.recoveryAttempts||(z(r=>({...r,phase:"recovery",recoveryAttempt:s})),l==null||l(s),await new Promise(r=>setTimeout(r,A.recoveryDelay)),await F())},[q.recoveryAttempt,A.recoveryAttempts,A.recoveryDelay,l,F]),P=e.useCallback(s=>{d.current=[...d.current,s]},[]),T=e.useCallback(s=>{d.current=d.current.filter(r=>r.id!==s)},[]),O=e.useCallback(s=>q.results.find(r=>r.taskId===s),[q.results]);e.useEffect(()=>{q.hasError&&A.autoRecovery&&q.recoveryAttempt<A.recoveryAttempts&&D()},[q.hasError,A.autoRecovery,A.recoveryAttempts,q.recoveryAttempt,D]),e.useEffect(()=>(F(),()=>{p.current&&p.current.abort()}),[]),e.useImperativeHandle(f,()=>({getState:()=>q,restart:V,skip:I,addTask:P,removeTask:T,getTaskResult:O,hideSplash:U,recover:D}),[q,V,I,P,T,O,U,D]);const b={...q,restart:V,skip:I,hideSplash:U};return q.hasError&&q.recoveryAttempt>=A.recoveryAttempts?t.jsx(ue.Provider,{value:b,children:N||t.jsxs("div",{className:"nice-auto-start__error",children:[t.jsx("div",{className:"nice-auto-start__error-icon","aria-hidden":"true",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert"})}),t.jsx("h2",{className:"nice-auto-start__error-title",children:"Startup Failed"}),t.jsx("p",{className:"nice-auto-start__error-message",children:q.errorMessage}),t.jsx("button",{className:"nice-auto-start__error-retry",onClick:V,children:"Retry"})]})}):j&&!q.isReady?t.jsx(ue.Provider,{value:b,children:g||t.jsx("div",{className:"nice-auto-start__splash",children:t.jsxs("div",{className:"nice-auto-start__splash-content",children:[t.jsx("div",{className:"nice-auto-start__splash-logo","aria-hidden":"true"}),t.jsx("h1",{className:"nice-auto-start__splash-title",children:"Loading..."}),A.showProgress&&t.jsx("div",{className:"nice-auto-start__splash-progress",children:t.jsx("div",{className:"nice-auto-start__splash-progress-bar",style:{width:`${q.progress}%`}})}),A.showTaskNames&&q.currentTask&&t.jsx("div",{className:"nice-auto-start__splash-task",children:q.currentTask}),q.phase==="recovery"&&t.jsxs("div",{className:"nice-auto-start__splash-recovery",children:["Recovery attempt ",q.recoveryAttempt," of ",A.recoveryAttempts]})]})})}):t.jsx(ue.Provider,{value:b,children:y})});ge.displayName="NiceAutoStart";const Fe=ge;Fe.displayName="NiceAutoStartProvider";const Be=e.createContext(null),$e=()=>{const n=e.useContext(Be);if(!n)throw new Error("useExternalDisplay must be used within NiceExternalDisplayProvider");return n},Pt={autoDetect:!0,pollInterval:2e3,defaultFeatures:{resizable:!0,scrollbars:!0},allowMultiWindow:!0,syncContent:!1},Lt=()=>typeof window>"u"?!1:"getScreenDetails"in window,Rt=()=>`window-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Ot=n=>{const f=[];return n.width!==void 0&&f.push(`width=${n.width}`),n.height!==void 0&&f.push(`height=${n.height}`),n.left!==void 0&&f.push(`left=${n.left}`),n.top!==void 0&&f.push(`top=${n.top}`),n.menubar!==void 0&&f.push(`menubar=${n.menubar?"yes":"no"}`),n.toolbar!==void 0&&f.push(`toolbar=${n.toolbar?"yes":"no"}`),n.location!==void 0&&f.push(`location=${n.location?"yes":"no"}`),n.status!==void 0&&f.push(`status=${n.status?"yes":"no"}`),n.resizable!==void 0&&f.push(`resizable=${n.resizable?"yes":"no"}`),n.scrollbars!==void 0&&f.push(`scrollbars=${n.scrollbars?"yes":"no"}`),f.join(",")},De=()=>{var f;if(typeof window>"u")return{id:"primary",label:"Primary Display",width:0,height:0,availWidth:0,availHeight:0,left:0,top:0,devicePixelRatio:1,isPrimary:!0,orientation:"landscape-primary",colorDepth:24};const n=window.screen;return{id:"primary",label:"Primary Display",width:n.width,height:n.height,availWidth:n.availWidth,availHeight:n.availHeight,left:n.availLeft||0,top:n.availTop||0,devicePixelRatio:window.devicePixelRatio,isPrimary:!0,orientation:((f=n.orientation)==null?void 0:f.type)||"landscape-primary",colorDepth:n.colorDepth}},Tt=async()=>{try{return(await navigator.permissions.query({name:"window-management"})).state}catch{return"unknown"}},Ee=async()=>(await window.getScreenDetails()).screens.map((f,h)=>{var k;return{id:`screen-${h}`,label:f.label||`Display ${h+1}`,width:f.width,height:f.height,availWidth:f.availWidth,availHeight:f.availHeight,left:f.left,top:f.top,devicePixelRatio:f.devicePixelRatio,isPrimary:f.isPrimary,isInternal:f.isInternal,orientation:((k=f.orientation)==null?void 0:k.type)||"landscape-primary",colorDepth:f.colorDepth}}),Pe=(n,f)=>JSON.stringify(n)===JSON.stringify(f),pe=e.forwardRef((n,f)=>{const{config:h,onScreensChange:k,onWindowOpen:g,onWindowClose:N,onPermissionChange:R,children:G}=n,i={...Pt,...h},l=e.useRef(new Map),y=e.useRef(null),[A,v]=e.useState([De()]),[d,p]=e.useState([]),[j,B]=e.useState("unknown"),[q]=e.useState(Lt),z=e.useRef(k),Y=e.useRef(R);e.useEffect(()=>{z.current=k,Y.current=R});const K=e.useRef([]),F=e.useCallback(m=>{var w;v(u=>Pe(u,m)?u:m),Pe(K.current,m)||(K.current=m,(w=z.current)==null||w.call(z,m))},[]),V=e.useRef("unknown"),I=e.useCallback(m=>{var w;V.current!==m&&(V.current=m,B(m),(w=Y.current)==null||w.call(Y,m))},[]),U=e.useCallback(async()=>{if(q){const w=await Tt();if(I(w),w==="granted")try{const u=await Ee();return F(u),u}catch{}}const m=[De()];return F(m),m},[q,I,F]),D=e.useCallback(async()=>{if(!q)return I("denied"),!1;try{return F(await Ee()),I("granted"),!0}catch(m){return I(m instanceof DOMException&&m.name==="NotAllowedError"?"denied":"unknown"),!1}},[q,I,F]),P=e.useCallback(async(m,w="about:blank",u={})=>{if(!i.allowMultiWindow&&d.length>0)return console.warn("Multi-window mode is disabled"),null;const C=Rt(),x={...i.defaultFeatures,...u,width:u.width??m.availWidth,height:u.height??m.availHeight,left:u.left??m.left,top:u.top??m.top},W=Ot(x),_={window:null,screen:m,id:C,state:"opening",isFullscreen:!1,features:x};p(M=>[...M,_]);try{const M=window.open(w,C,W);if(!M)return p($=>$.map(Z=>Z.id===C?{...Z,state:"error"}:Z)),null;l.current.set(C,M);const L={..._,window:M,state:"open"};p($=>$.map(Z=>Z.id===C?L:Z));const X=setInterval(()=>{M.closed&&(clearInterval(X),l.current.delete(C),p($=>$.filter(Z=>Z.id!==C)),N==null||N(L))},500);return x.fullscreen&&M.addEventListener("load",()=>{var $,Z;(Z=($=M.document.documentElement).requestFullscreen)==null||Z.call($)}),g==null||g(L),L}catch(M){return console.error("Failed to open window:",M),p(L=>L.map(X=>X.id===C?{...X,state:"error"}:X)),null}},[i.allowMultiWindow,i.defaultFeatures,d.length,g,N]),T=e.useCallback(m=>{const w=l.current.get(m);w&&!w.closed&&w.close(),l.current.delete(m),p(u=>u.filter(C=>C.id!==m))},[]),O=e.useCallback(()=>{for(const[m,w]of l.current)w.closed||w.close(),l.current.delete(m);p([])},[]),b=e.useCallback((m,w)=>{const u=l.current.get(m);u&&!u.closed&&(u.moveTo(w.left,w.top),u.resizeTo(w.availWidth,w.availHeight),p(C=>C.map(x=>x.id===m?{...x,screen:w}:x)))},[]),s=e.useCallback(async m=>{const w=l.current.get(m);if(!w||w.closed)return!1;try{const u=!!w.document.fullscreenElement;return u?await w.document.exitFullscreen():await w.document.documentElement.requestFullscreen(),p(C=>C.map(x=>x.id===m?{...x,isFullscreen:!u}:x)),!0}catch{return!1}},[]),r=e.useCallback((m,w)=>{const u=l.current.get(m);u&&!u.closed&&u.postMessage(w,"*")},[]),a=e.useCallback(m=>{for(const w of l.current.values())w.closed||w.postMessage(m,"*")},[]);e.useEffect(()=>{i.autoDetect&&U()},[i.autoDetect,U]),e.useEffect(()=>(i.autoDetect&&i.pollInterval>0&&(y.current=setInterval(U,i.pollInterval)),()=>{y.current&&clearInterval(y.current)}),[i.autoDetect,i.pollInterval,U]),e.useEffect(()=>{if(!q)return;const m=()=>{U()};return window.addEventListener("screenschange",m),()=>{window.removeEventListener("screenschange",m)}},[q,U]),e.useEffect(()=>()=>{O()},[O]);const c=A.find(m=>m.isPrimary)||null,o=A.filter(m=>!m.isPrimary),S={screens:A,primaryScreen:c,externalScreens:o,windows:d,isApiAvailable:q,permissionState:j};e.useImperativeHandle(f,()=>({getState:()=>S,requestPermission:D,getScreens:U,openWindow:P,closeWindow:T,closeAllWindows:O,moveWindowToScreen:b,toggleFullscreen:s,sendMessage:r,broadcast:a}),[S,D,U,P,T,O,b,s,r,a]);const E={...S,requestPermission:D,openWindow:P,closeWindow:T,moveWindowToScreen:b};return t.jsx(Be.Provider,{value:E,children:t.jsx("div",{className:"nice-external-display",children:G})})});pe.displayName="NiceExternalDisplay";const qe=pe;qe.displayName="NiceExternalDisplayProvider";const Ue=({onSelect:n,selectedId:f,showPreview:h=!0,className:k})=>{const{screens:g,primaryScreen:N}=$e(),R=y=>{n==null||n(y)},i=(()=>{let y=0,A=0,v=0,d=0;for(const p of g)y=Math.min(y,p.left),A=Math.min(A,p.top),v=Math.max(v,p.left+p.width),d=Math.max(d,p.top+p.height);return{minX:y,minY:A,maxX:v,maxY:d,width:v-y,height:d-A}})(),l=Math.min(280/i.width,160/i.height,1);return t.jsxs("div",{className:`nice-screen-selector ${k||""}`,children:[h&&t.jsx("div",{className:"nice-screen-selector__preview",style:{width:i.width*l,height:i.height*l},children:g.map(y=>t.jsx("button",{className:`nice-screen-selector__screen ${f===y.id?"nice-screen-selector__screen--selected":""} ${y.isPrimary?"nice-screen-selector__screen--primary":""}`,style:{left:(y.left-i.minX)*l,top:(y.top-i.minY)*l,width:y.width*l,height:y.height*l},onClick:()=>R(y),title:y.label,children:t.jsx("span",{className:"nice-screen-selector__screen-label",children:y.isPrimary?"P":g.indexOf(y)+1})},y.id))}),t.jsx("div",{className:"nice-screen-selector__list",children:g.map(y=>t.jsxs("button",{className:`nice-screen-selector__item ${f===y.id?"nice-screen-selector__item--selected":""}`,onClick:()=>R(y),children:[t.jsx("span",{className:"nice-screen-selector__item-name",children:y.label}),t.jsxs("span",{className:"nice-screen-selector__item-resolution",children:[y.width," × ",y.height]}),y.isPrimary&&t.jsx("span",{className:"nice-screen-selector__item-badge",children:"Primary"})]},y.id))})]})};Ue.displayName="NiceScreenSelector";const He=e.createContext(null),Mt=()=>{const n=e.useContext(He);if(!n)throw new Error("useKioskMode must be used within NiceKioskModeProvider");return n},Ft={autoFullscreen:!0,lockNavigation:!0,disableContextMenu:!0,disableShortcuts:!0,disableSelection:!0,disableCopyPaste:!0,exitPin:"1234",exitShortcut:"ctrl+shift+k",adminTapCount:5,adminTapTimeout:2e3,inactivityTimeout:300*1e3,showCursor:!0,allowScrolling:!0,className:""},ye=e.forwardRef((n,f)=>{const{config:h,children:k,screensaver:g,adminPanel:N,onModeChange:R,onFullscreenChange:G,onAdminAccess:i,onInactivity:l,onActivity:y,onExitRequest:A}=n,v={...Ft,...h},d=e.useRef(null),p=e.useRef(null),j=e.useRef({count:0,timer:null}),[B,q]=e.useState({mode:"windowed",isFullscreen:!1,isLocked:!1,isAdminMode:!1,isScreensaverActive:!1,idleTime:0,isPinDialogOpen:!1}),[z,Y]=e.useState(""),[K,F]=e.useState(!1),V=e.useCallback(async()=>{const u=d.current;if(u)try{u.requestFullscreen?await u.requestFullscreen():u.webkitRequestFullscreen?await u.webkitRequestFullscreen():u.msRequestFullscreen&&await u.msRequestFullscreen()}catch(C){console.warn("Failed to enter fullscreen:",C)}},[]),I=e.useCallback(async()=>{try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen?await document.webkitExitFullscreen():document.msExitFullscreen&&await document.msExitFullscreen()}catch(u){console.warn("Failed to exit fullscreen:",u)}},[]),U=e.useCallback(async()=>{B.isFullscreen?await I():await V()},[B.isFullscreen,V,I]),D=e.useCallback(()=>{q(u=>({...u,mode:"locked",isLocked:!0,isAdminMode:!1})),R==null||R("locked")},[R]),P=e.useCallback(u=>v.exitPin&&u!==v.exitPin?(F(!0),setTimeout(()=>F(!1),1e3),!1):(q(C=>({...C,mode:C.isFullscreen?"fullscreen":"windowed",isLocked:!1,isPinDialogOpen:!1})),Y(""),!0),[v.exitPin]),T=e.useCallback(()=>{q(u=>({...u,isAdminMode:!0})),i==null||i()},[i]),O=e.useCallback(()=>{q(u=>({...u,isAdminMode:!1}))},[]),b=e.useCallback(()=>{j.current.timer&&clearTimeout(j.current.timer),j.current.count++,j.current.count>=v.adminTapCount?(j.current.count=0,T()):j.current.timer=setTimeout(()=>{j.current.count=0},v.adminTapTimeout)},[v.adminTapCount,v.adminTapTimeout,T]),s=e.useCallback(()=>{p.current&&clearTimeout(p.current),B.isScreensaverActive&&(q(u=>({...u,isScreensaverActive:!1})),y==null||y()),v.inactivityTimeout>0&&(p.current=setTimeout(()=>{q(u=>({...u,isScreensaverActive:!0})),l==null||l()},v.inactivityTimeout))},[v.inactivityTimeout,B.isScreensaverActive,y,l]),r=e.useCallback(()=>{q(u=>({...u,isScreensaverActive:!0}))},[]),a=e.useCallback(()=>{q(u=>({...u,isScreensaverActive:!1})),s()},[s]),c=e.useCallback(()=>{q(u=>({...u,isPinDialogOpen:!0})),Y(""),F(!1)},[]),o=e.useCallback(()=>{q(u=>({...u,isPinDialogOpen:!1})),Y(""),F(!1)},[]),S=e.useCallback(()=>{P(z)},[z,P]),E=e.useCallback(u=>{u.key==="Enter"&&S()},[S]);e.useEffect(()=>{const u=()=>{const C=!!document.fullscreenElement;q(x=>({...x,mode:x.isLocked?"locked":C?"fullscreen":"windowed",isFullscreen:C})),G==null||G(C)};return document.addEventListener("fullscreenchange",u),document.addEventListener("webkitfullscreenchange",u),()=>{document.removeEventListener("fullscreenchange",u),document.removeEventListener("webkitfullscreenchange",u)}},[G]),e.useEffect(()=>{if(!v.disableContextMenu)return;const u=C=>{B.isAdminMode||C.preventDefault()};return document.addEventListener("contextmenu",u),()=>document.removeEventListener("contextmenu",u)},[v.disableContextMenu,B.isAdminMode]),e.useEffect(()=>{const u=async C=>{const W=v.exitShortcut.toLowerCase().split("+"),_=W.includes("ctrl")===C.ctrlKey,M=W.includes("shift")===C.shiftKey,L=W.includes("alt")===C.altKey,X=W.some($=>$===C.key.toLowerCase());if(_&&M&&L&&X){C.preventDefault(),(A?await A("keyboard"):!0)&&(B.isLocked?c():I());return}if(v.disableShortcuts&&!B.isAdminMode){const $=["F5","F11","F12"],Z=[{ctrl:!0,key:"r"},{ctrl:!0,key:"w"},{ctrl:!0,key:"n"},{ctrl:!0,key:"t"},{ctrl:!0,shift:!0,key:"i"},{ctrl:!0,shift:!0,key:"j"},{alt:!0,key:"F4"}];if($.includes(C.key)){C.preventDefault();return}for(const J of Z)if(J.ctrl===C.ctrlKey&&(J.shift??!1)===C.shiftKey&&(J.alt??!1)===C.altKey&&J.key.toLowerCase()===C.key.toLowerCase()){C.preventDefault();return}}};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[v.disableShortcuts,v.exitShortcut,B.isAdminMode,B.isLocked,I,c,A]),e.useEffect(()=>{if(!v.disableCopyPaste)return;const u=x=>{B.isAdminMode||x.preventDefault()},C=x=>{B.isAdminMode||x.preventDefault()};return document.addEventListener("copy",u),document.addEventListener("paste",C),()=>{document.removeEventListener("copy",u),document.removeEventListener("paste",C)}},[v.disableCopyPaste,B.isAdminMode]),e.useEffect(()=>{const u=["mousedown","mousemove","keydown","touchstart","scroll"],C=()=>{s()};for(const x of u)document.addEventListener(x,C);return s(),()=>{for(const x of u)document.removeEventListener(x,C);p.current&&clearTimeout(p.current)}},[s]),e.useEffect(()=>{if(v.autoFullscreen){const u=setTimeout(()=>{V()},100);return()=>clearTimeout(u)}},[v.autoFullscreen,V]),e.useImperativeHandle(f,()=>({getState:()=>B,enterFullscreen:V,exitFullscreen:I,toggleFullscreen:U,lock:D,unlock:P,enterAdminMode:T,exitAdminMode:O,resetIdleTimer:s,showScreensaver:r,hideScreensaver:a,openPinDialog:c,closePinDialog:o}),[B,V,I,U,D,P,T,O,s,r,a,c,o]);const m={...B,enterFullscreen:V,exitFullscreen:I,toggleFullscreen:U,lock:D,unlock:P,enterAdminMode:T,exitAdminMode:O,resetIdleTimer:s},w=["nice-kiosk-mode",`nice-kiosk-mode--${B.mode}`,B.isFullscreen&&"nice-kiosk-mode--fullscreen",!v.showCursor&&"nice-kiosk-mode--no-cursor",v.disableSelection&&"nice-kiosk-mode--no-select",!v.allowScrolling&&"nice-kiosk-mode--no-scroll",v.className].filter(Boolean).join(" ");return t.jsx(He.Provider,{value:m,children:t.jsxs("div",{ref:d,className:w,onClick:b,children:[t.jsx("div",{className:"nice-kiosk-mode__content",children:k}),B.isAdminMode&&N&&t.jsxs("div",{className:"nice-kiosk-mode__admin",children:[t.jsxs("div",{className:"nice-kiosk-mode__admin-header",children:[t.jsx("h2",{className:"nice-kiosk-mode__admin-title",children:"Admin Mode"}),t.jsx("button",{className:"nice-kiosk-mode__admin-close",onClick:O,"aria-label":"Close admin panel",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-kiosk-mode__admin-content",children:N})]}),B.isScreensaverActive&&t.jsx("div",{className:"nice-kiosk-mode__screensaver",onClick:a,onTouchStart:a,children:g||t.jsx("div",{className:"nice-kiosk-mode__screensaver-default",children:t.jsx("div",{className:"nice-kiosk-mode__screensaver-text",children:"Touch to continue"})})}),B.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__pin-overlay",children:t.jsxs("div",{className:"nice-kiosk-mode__pin-dialog",children:[t.jsx("h3",{className:"nice-kiosk-mode__pin-title",children:"Enter PIN"}),t.jsx("input",{type:"password",className:`nice-kiosk-mode__pin-input ${K?"nice-kiosk-mode__pin-input--error":""}`,value:z,onChange:u=>Y(u.target.value),onKeyPress:E,maxLength:8,autoFocus:!0,placeholder:"••••"}),t.jsxs("div",{className:"nice-kiosk-mode__pin-buttons",children:[t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--cancel",onClick:o,children:"Cancel"}),t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--submit",onClick:S,children:"Unlock"})]}),K&&t.jsx("div",{className:"nice-kiosk-mode__pin-error",children:"Incorrect PIN"})]})}),B.isLocked&&!B.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__lock-indicator",children:t.jsx("span",{className:"nice-kiosk-mode__lock-text",children:"Kiosk Locked"})})]})})});ye.displayName="NiceKioskMode";const We=ye;We.displayName="NiceKioskModeProvider";const Ve=e.createContext(null),Bt=()=>{const n=e.useContext(Ve);if(!n)throw new Error("useLowPowerMode must be used within NiceLowPowerModeProvider");return n},$t={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}},qt={initialMode:"normal",autoDimTimeout:120*1e3,autoSleepTimeout:600*1e3,lowBatteryThreshold:20,criticalBatteryThreshold:5,wakeOnTouch:!0,wakeOnMotion:!1,transitionDuration:500},be=e.forwardRef((n,f)=>{const{config:h,onModeChange:k,onBrightnessChange:g,onSleep:N,onWake:R,onLowBattery:G,children:i}=n,l={...qt,...h},y={...$t,...h==null?void 0:h.modes},A=e.useRef(null),v=e.useRef(null),d=e.useRef(Date.now()),p=e.useRef(null),[j,B]=e.useState({currentMode:l.initialMode,brightness:y[l.initialMode].brightness??1,isPowerSaving:l.initialMode!=="normal",isSleeping:l.initialMode==="sleep",idleTime:0,isDisplayOn:!0}),q=e.useCallback(O=>{const b=y[O];document.documentElement.style.setProperty("--lpm-brightness",String(b.brightness)),document.documentElement.style.setProperty("--lpm-transition",`${l.transitionDuration}ms`),b.disableAnimations?document.documentElement.classList.add("lpm-no-animations"):document.documentElement.classList.remove("lpm-no-animations"),b.reduceImageQuality?document.documentElement.classList.add("lpm-reduced-quality"):document.documentElement.classList.remove("lpm-reduced-quality")},[y,l.transitionDuration]),z=e.useCallback(O=>{B(b=>{if(b.currentMode===O)return b;const s=b.currentMode,r=y[O];return q(O),k==null||k(O,s),g==null||g(r.brightness??1),O==="sleep"&&s!=="sleep"?N==null||N():s==="sleep"&&O!=="sleep"&&(R==null||R()),{...b,currentMode:O,brightness:r.brightness??1,isPowerSaving:O!=="normal",isSleeping:O==="sleep",isDisplayOn:O!=="sleep"}})},[y,q,k,g,N,R]),Y=e.useCallback(O=>{const b=Math.max(0,Math.min(1,O));document.documentElement.style.setProperty("--lpm-brightness",String(b)),B(s=>({...s,brightness:b})),g==null||g(b)},[g]),K=e.useCallback(()=>{z("sleep")},[z]),F=e.useCallback(()=>{z("normal"),I()},[z]),V=e.useCallback(()=>{j.currentMode==="normal"?z("low"):z("normal")},[j.currentMode,z]),I=e.useCallback(()=>{if(d.current=Date.now(),A.current&&clearTimeout(A.current),v.current&&clearTimeout(v.current),j.isSleeping){F();return}j.currentMode!=="normal"&&j.currentMode!=="sleep"&&z("normal"),l.autoDimTimeout>0&&(A.current=setTimeout(()=>{j.currentMode==="normal"&&z("dim")},l.autoDimTimeout)),l.autoSleepTimeout>0&&(v.current=setTimeout(()=>{z("sleep")},l.autoSleepTimeout)),B(O=>({...O,idleTime:0}))},[j.isSleeping,j.currentMode,l.autoDimTimeout,l.autoSleepTimeout,z,F]),U=e.useCallback(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const O=await navigator.getBattery();return{level:Math.round(O.level*100),charging:O.charging}}catch{return{}}return{}},[]),D=e.useCallback(async()=>{const O=await U();O.level!==void 0&&(B(b=>({...b,batteryLevel:O.level,isCharging:O.charging})),O.charging||(O.level<=l.criticalBatteryThreshold?(z("sleep"),G==null||G(O.level)):O.level<=l.lowBatteryThreshold&&(j.currentMode==="normal"&&z("low"),G==null||G(O.level))))},[U,l.lowBatteryThreshold,l.criticalBatteryThreshold,j.currentMode,z,G]),P=e.useCallback(()=>{if(!(h!=null&&h.schedule)||h.schedule.length===0)return;const b=new Date().getHours();for(const s of h.schedule){const{startHour:r,endHour:a,mode:c}=s;let o;if(r<=a?o=b>=r&&b<a:o=b>=r||b<a,o){B(S=>({...S,scheduledModeActive:c})),j.currentMode!==c&&z(c);return}}B(s=>({...s,scheduledModeActive:void 0}))},[h==null?void 0:h.schedule,j.currentMode,z]);e.useEffect(()=>{const O=["mousedown","mousemove","keydown","touchstart","scroll"],b=()=>{l.wakeOnTouch&&I()};for(const s of O)document.addEventListener(s,b);return I(),()=>{for(const s of O)document.removeEventListener(s,b);A.current&&clearTimeout(A.current),v.current&&clearTimeout(v.current)}},[l.wakeOnTouch,I]),e.useEffect(()=>{D(),(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const b=await navigator.getBattery();p.current=b,b.addEventListener("levelchange",D),b.addEventListener("chargingchange",D)}catch{}})()},[D]),e.useEffect(()=>{P();const O=setInterval(P,6e4);return()=>clearInterval(O)},[P]),e.useEffect(()=>{q(l.initialMode)},[l.initialMode,q]),e.useImperativeHandle(f,()=>({getState:()=>j,setMode:z,setBrightness:Y,sleep:K,wake:F,togglePowerSaving:V,resetIdleTimer:I,getBatteryInfo:U}),[j,z,Y,K,F,V,I,U]);const T={...j,setMode:z,setBrightness:Y,sleep:K,wake:F,resetIdleTimer:I};return t.jsx(Ve.Provider,{value:T,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:i}),j.isSleeping&&t.jsx("div",{className:"nice-lpm__sleep-screen",onClick:l.wakeOnTouch?F:void 0,onTouchStart:l.wakeOnTouch?F:void 0,children:t.jsx("div",{className:"nice-lpm__sleep-message",children:"Touch to wake"})})]})})});be.displayName="NiceLowPowerMode";const ze=be;ze.displayName="NiceLowPowerModeProvider";const Ge=e.createContext(null),Ut=()=>{const n=e.useContext(Ge);if(!n)throw new Error("useOrientationLock must be used within NiceOrientationLockProvider");return n},Ht={preferredOrientation:"any",allowUserChange:!0,showRotationPrompt:!0,lockOnMount:!1,autoRotateContent:!1,supportedOrientations:["any","portrait","portrait-primary","portrait-secondary","landscape","landscape-primary","landscape-secondary","natural"]},Ye=()=>{if(typeof window>"u")return"portrait";const n=window.screen;return n.orientation?n.orientation.type:window.innerHeight>window.innerWidth?"portrait":"landscape"},Wt=()=>{if(typeof window>"u")return 0;const n=window.screen;return n.orientation?n.orientation.angle:window.orientation||0},he=()=>{if(typeof window>"u")return{type:"portrait",angle:0,isPortrait:!0,isLandscape:!1,width:0,height:0,aspectRatio:0};const n=Ye(),f=Wt(),h=window.screen.width,k=window.screen.height,g=n.includes("portrait")||window.innerHeight>window.innerWidth,N=n.includes("landscape")||window.innerWidth>window.innerHeight;return{type:n,angle:f,isPortrait:g,isLandscape:N,width:h,height:k,aspectRatio:h/k}},Vt=()=>{if(typeof window>"u")return!1;const n=window.screen;return!!(n.orientation&&typeof n.orientation.lock=="function")},we=e.forwardRef((n,f)=>{const{config:h,onOrientationChange:k,onLockChange:g,onUnsupportedOrientation:N,rotationPrompt:R,children:G,className:i}=n,l={...Ht,...h},y=e.useRef(!1),[A,v]=e.useState(Ye),[d,p]=e.useState(null),[j,B]=e.useState(he),[q]=e.useState(Vt),z=e.useCallback(b=>!!(l.supportedOrientations.includes("any")||l.supportedOrientations.includes(b)||b.includes("portrait")&&l.supportedOrientations.includes("portrait")||b.includes("landscape")&&l.supportedOrientations.includes("landscape")),[l.supportedOrientations]),Y=e.useCallback(async b=>{if(!q)return console.warn("Screen Orientation API is not available"),p(b),g==null||g(!0,b),!1;try{return await window.screen.orientation.lock(b),p(b),g==null||g(!0,b),!0}catch(s){return console.warn("Failed to lock orientation:",s),p(b),g==null||g(!0,b),!1}},[q,g]),K=e.useCallback(async()=>{if(p(null),g==null||g(!1,null),!q)return!1;try{return window.screen.orientation.unlock(),!0}catch(b){return console.warn("Failed to unlock orientation:",b),!1}},[q,g]),F=e.useCallback(async()=>d?K():Y(A),[d,A,Y,K]),V=e.useCallback(()=>he(),[]),I=e.useCallback(()=>{const b=he(),s=b.type;v(s),B(b),k==null||k(b),z(s)||N==null||N(s,l.supportedOrientations)},[l.supportedOrientations,z,k,N]);e.useEffect(()=>{y.current||(y.current=!0,I(),l.lockOnMount&&l.preferredOrientation!=="any"&&Y(l.preferredOrientation))},[l.lockOnMount,l.preferredOrientation,I,Y]),e.useEffect(()=>{const b=window.screen.orientation;return b&&b.addEventListener("change",I),window.addEventListener("resize",I),window.addEventListener("orientationchange",I),()=>{b&&b.removeEventListener("change",I),window.removeEventListener("resize",I),window.removeEventListener("orientationchange",I)}},[I]);const U={current:A,locked:d,isLocked:d!==null,isSupported:z(A),info:j,isApiAvailable:q};e.useImperativeHandle(f,()=>({getState:()=>U,lock:Y,unlock:K,toggleLock:F,getOrientationInfo:V,isOrientationSupported:z}),[U,Y,K,F,V,z]);const D={...U,lock:Y,unlock:K,getOrientationInfo:V},P=e.useCallback(()=>{if(!l.autoRotateContent||!d||d==="any")return;const b=d.includes("portrait"),s=j.isPortrait;return b===s?void 0:{transform:`rotate(${b?90:-90}deg)`,transformOrigin:"center center",width:b?j.height:j.width,height:b?j.width:j.height}},[l.autoRotateContent,d,j]),T=l.showRotationPrompt&&d!==null&&d!=="any"&&!U.isSupported,O=["nice-orientation",`nice-orientation--${A}`,d&&`nice-orientation--locked-${d}`,!U.isSupported&&"nice-orientation--unsupported",i].filter(Boolean).join(" ");return t.jsx(Ge.Provider,{value:D,children:t.jsxs("div",{className:O,style:P(),"data-orientation":A,"data-locked":d||void 0,children:[G,T&&t.jsx("div",{className:"nice-orientation__prompt",children:R||t.jsxs("div",{className:"nice-orientation__prompt-content",children:[t.jsx("div",{className:"nice-orientation__prompt-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--device","aria-hidden":"true"})}),t.jsxs("p",{className:"nice-orientation__prompt-text",children:["Please rotate your device to"," ",d!=null&&d.includes("portrait")?"portrait":"landscape"," mode"]})]})})]})})});we.displayName="NiceOrientationLock";const Xe=we;Xe.displayName="NiceOrientationLockProvider";const Ke=e.createContext(null),zt=()=>{const n=e.useContext(Ke);if(!n)throw new Error("useRemoteManagement must be used within NiceRemoteManagementProvider");return n},Gt={heartbeatInterval:3e4,reconnectDelay:5e3,maxReconnectAttempts:10,enableHealthMonitoring:!0,healthReportInterval:6e4,enableScreenshot:!0,enableLogs:!0,logBufferSize:100},ve=e.forwardRef((n,f)=>{const{config:h,onConnectionChange:k,onCommandReceived:g,onCustomCommand:N,onCaptureScreenshot:R,children:G}=n,i={...Gt,...h},l=e.useRef(null),y=e.useRef(null),A=e.useRef(null),v=e.useRef([]),d=e.useRef(Date.now()),p=e.useRef(0),[j,B]=e.useState({status:"disconnected",isConnected:!1,reconnectAttempts:0,pendingCommands:[],commandHistory:[]}),q=e.useCallback(()=>{const s=typeof navigator<"u"?navigator:null,r=typeof window<"u"?window:null;return{deviceId:i.deviceId,name:i.deviceName||i.deviceId,type:"embedded-display",os:s==null?void 0:s.platform,browser:s==null?void 0:s.userAgent,resolution:r?`${r.screen.width}x${r.screen.height}`:void 0,uptime:Math.floor((Date.now()-d.current)/1e3),metadata:{}}},[i.deviceId,i.deviceName]),z=e.useCallback(async()=>{const s={isOnline:typeof navigator<"u"?navigator.onLine:!0,lastUpdated:new Date};if(typeof performance<"u"&&"memory"in performance){const r=performance.memory;r&&(s.memory=Math.round(r.usedJSHeapSize/r.jsHeapSizeLimit*100))}if(typeof navigator<"u"&&"getBattery"in navigator)try{const r=await navigator.getBattery();s.battery=Math.round(r.level*100)}catch{}if(typeof navigator<"u"&&"storage"in navigator&&"estimate"in navigator.storage)try{const r=await navigator.storage.estimate();r.quota&&r.usage&&(s.storageFree=r.quota-r.usage)}catch{}return s},[]),Y=e.useRef({enabled:i.enableScreenshot,capture:R});e.useEffect(()=>{Y.current={enabled:i.enableScreenshot,capture:R}});const K=e.useCallback(async()=>{const{enabled:s,capture:r}=Y.current;if(!s)throw new Error("Screenshots are disabled on this device (enableScreenshot: false)");if(!r)throw new Error("This device cannot take screenshots: no onCaptureScreenshot handler");const a=await r();if(!a)throw new Error("The screenshot handler returned no image");return a},[]),F=e.useCallback(()=>K().catch(()=>{}),[K]),V=e.useRef({onConnectionChange:k,onCommandReceived:g,onCustomCommand:N});e.useEffect(()=>{V.current={onConnectionChange:k,onCommandReceived:g,onCustomCommand:N}});const I=e.useCallback(async()=>{var s,r,a,c,o;if(((s=l.current)==null?void 0:s.readyState)!==WebSocket.OPEN){B(S=>({...S,status:"connecting"})),(a=(r=V.current).onConnectionChange)==null||a.call(r,"connecting");try{const S=new URL(i.serverUrl);S.searchParams.set("deviceId",i.deviceId),i.apiKey&&S.searchParams.set("apiKey",i.apiKey);const E=new WebSocket(S.toString());l.current=E,E.onopen=()=>{var m,w;p.current=0,B(u=>({...u,status:"connected",isConnected:!0,reconnectAttempts:0,error:void 0})),(w=(m=V.current).onConnectionChange)==null||w.call(m,"connected"),E.send(JSON.stringify({type:"register",payload:q()}))},E.onmessage=async m=>{var w,u;try{const C=JSON.parse(m.data);if(C.type==="command"){const x={id:C.id,type:C.commandType,payload:C.payload,timestamp:new Date,acknowledged:!0,executed:!1};B(M=>({...M,pendingCommands:[...M.pendingCommands,x]})),(u=(w=V.current).onCommandReceived)==null||u.call(w,x);let W,_;try{switch(x.type){case"restart":typeof window<"u"&&window.location.reload();break;case"screenshot":W=await K();break;case"logs":W=v.current;break;case"custom":V.current.onCustomCommand&&(W=await V.current.onCustomCommand(x));break}x.executed=!0,x.result=W}catch(M){_=M instanceof Error?M.message:String(M),x.error=_}E.send(JSON.stringify({type:"commandResult",commandId:x.id,result:W,error:_})),B(M=>({...M,pendingCommands:M.pendingCommands.filter(L=>L.id!==x.id),commandHistory:[...M.commandHistory.slice(-49),x]}))}}catch{}},E.onerror=()=>{l.current===E&&B(m=>({...m,status:"error",error:"WebSocket error"}))},E.onclose=()=>{var m,w;l.current===E&&(l.current=null,B(u=>({...u,status:"disconnected",isConnected:!1})),p.current<i.maxReconnectAttempts&&setTimeout(()=>{p.current>=i.maxReconnectAttempts||(p.current+=1,B(u=>({...u,reconnectAttempts:p.current})),I())},i.reconnectDelay),(w=(m=V.current).onConnectionChange)==null||w.call(m,"disconnected"))}}catch(S){B(E=>({...E,status:"error",error:S instanceof Error?S.message:"Connection failed"})),(o=(c=V.current).onConnectionChange)==null||o.call(c,"error")}}},[i.serverUrl,i.deviceId,i.apiKey,i.maxReconnectAttempts,i.reconnectDelay,q,K]),U=e.useCallback(()=>{p.current=i.maxReconnectAttempts,l.current&&(l.current.close(),l.current=null),B(s=>({...s,status:"disconnected",isConnected:!1,reconnectAttempts:i.maxReconnectAttempts}))},[i.maxReconnectAttempts]),D=e.useCallback(async()=>{var s;((s=l.current)==null?void 0:s.readyState)===WebSocket.OPEN&&(l.current.send(JSON.stringify({type:"heartbeat",timestamp:new Date().toISOString(),deviceId:i.deviceId})),B(r=>({...r,lastHeartbeat:new Date})))},[i.deviceId]),P=e.useCallback(async s=>{var a;if(((a=l.current)==null?void 0:a.readyState)!==WebSocket.OPEN)return;const r=s||await z();l.current.send(JSON.stringify({type:"health",metrics:r,deviceId:i.deviceId})),B(c=>({...c,healthMetrics:r}))},[i.deviceId,z]),T=e.useCallback(async(s,r,a)=>{var c;((c=l.current)==null?void 0:c.readyState)===WebSocket.OPEN&&l.current.send(JSON.stringify({type:"commandResult",commandId:s,result:r,error:a}))},[]),O=e.useCallback((s,r,a)=>{var o;const c={level:s,message:r,data:a,timestamp:new Date};v.current=[...v.current.slice(-(i.logBufferSize-1)),c],i.enableLogs&&((o=l.current)==null?void 0:o.readyState)===WebSocket.OPEN&&l.current.send(JSON.stringify({type:"log",...c,deviceId:i.deviceId}))},[i.deviceId,i.enableLogs,i.logBufferSize]);e.useEffect(()=>(p.current=0,I(),()=>{U(),y.current&&clearInterval(y.current),A.current&&clearInterval(A.current)}),[]),e.useEffect(()=>{if(j.isConnected)return y.current=setInterval(D,i.heartbeatInterval),()=>{y.current&&clearInterval(y.current)}},[j.isConnected,i.heartbeatInterval,D]),e.useEffect(()=>{if(!(!j.isConnected||!i.enableHealthMonitoring))return A.current=setInterval(()=>{P()},i.healthReportInterval),P(),()=>{A.current&&clearInterval(A.current)}},[j.isConnected,i.enableHealthMonitoring,i.healthReportInterval,P]),e.useImperativeHandle(f,()=>({getState:()=>j,connect:I,disconnect:U,sendHeartbeat:D,sendHealthMetrics:P,reportCommandResult:T,sendLog:O,captureScreenshot:F,getDeviceInfo:q}),[j,I,U,D,P,T,O,F,q]);const b={...j,deviceInfo:q(),connect:I,disconnect:U,sendLog:O};return t.jsx(Ke.Provider,{value:b,children:G})});ve.displayName="NiceRemoteManagement";const Qe=ve;Qe.displayName="NiceRemoteManagementProvider";const Yt={modes:["pixel-shift","dimming"],inactivityTimeout:300*1e3,pixelShift:{maxShift:3,interval:6e4,smooth:!0},colorCycle:{colors:["var(--nice-text-primary, #000000)","var(--nice-text, #111111)","var(--nice-bg, #0a0a0a)"],interval:3e4,transitionDuration:1e3},dimming:{level:.3,fadeDuration:2e3},screensaver:{type:"blank"},staticDetectionThreshold:3e4,autoDetectStatic:!1},Je=e.forwardRef((n,f)=>{var S,E,m,w,u,C;const{config:h,enabled:k=!0,onActivate:g,onDeactivate:N,onModeChange:R,children:G}=n,i={...Yt,...h},l=e.useRef(null),y=e.useRef(null),A=e.useRef(null),v=e.useRef(null),[d,p]=e.useState({isActive:!1,activeModes:[],shiftX:0,shiftY:0,isDimmed:!1,isScreensaverActive:!1,idleTime:0}),[j,B]=e.useState(0),[q,z]=e.useState({x:50,y:50,dx:1,dy:1}),Y=e.useCallback(()=>{if(!i.pixelShift)return;const{maxShift:x}=i.pixelShift,W=Math.floor(Math.random()*(x*2+1))-x,_=Math.floor(Math.random()*(x*2+1))-x;p(M=>({...M,shiftX:W,shiftY:_}))},[i.pixelShift]),K=e.useCallback(()=>{!i.pixelShift||A.current||(Y(),A.current=setInterval(Y,i.pixelShift.interval))},[i.pixelShift,Y]),F=e.useCallback(()=>{A.current&&(clearInterval(A.current),A.current=null),p(x=>({...x,shiftX:0,shiftY:0}))},[]),V=e.useCallback(()=>{!i.colorCycle||v.current||(v.current=setInterval(()=>{B(x=>{var W;return(x+1)%(((W=i.colorCycle)==null?void 0:W.colors.length)||1)})},i.colorCycle.interval))},[i.colorCycle]),I=e.useCallback(()=>{v.current&&(clearInterval(v.current),v.current=null),B(0)},[]),U=e.useCallback(()=>{if(!k||d.isActive)return;const x=i.modes;p(W=>({...W,isActive:!0,activeModes:x})),x.includes("pixel-shift")&&K(),x.includes("color-cycling")&&V(),x.includes("dimming")&&p(W=>({...W,isDimmed:!0})),x.includes("screensaver")&&p(W=>({...W,isScreensaverActive:!0})),g==null||g(),R==null||R(x)},[k,d.isActive,i.modes,K,V,g,R]),D=e.useCallback(()=>{d.isActive&&(F(),I(),p(x=>({...x,isActive:!1,activeModes:[],isDimmed:!1,isScreensaverActive:!1})),N==null||N(),R==null||R([]))},[d.isActive,F,I,N,R]),P=e.useCallback(()=>{d.isActive?D():U()},[d.isActive,U,D]),T=e.useCallback(()=>{y.current&&clearTimeout(y.current),d.isActive&&D(),k&&i.inactivityTimeout>0&&(y.current=setTimeout(()=>{U()},i.inactivityTimeout))},[k,d.isActive,i.inactivityTimeout,U,D]),O=e.useCallback(()=>{p(x=>({...x,isScreensaverActive:!0}))},[]),b=e.useCallback(()=>{p(x=>({...x,isScreensaverActive:!1})),T()},[T]),s=e.useCallback(x=>{p(W=>({...W,isDimmed:x>0}))},[]);e.useEffect(()=>{var W;if(!d.isScreensaverActive||((W=i.screensaver)==null?void 0:W.type)!=="bounce")return;const x=setInterval(()=>{z(_=>{let{x:M,y:L,dx:X,dy:$}=_;return M+=X*.5,L+=$*.5,(M<=0||M>=90)&&(X=-X),(L<=0||L>=90)&&($=-$),{x:M,y:L,dx:X,dy:$}})},50);return()=>clearInterval(x)},[d.isScreensaverActive,(S=i.screensaver)==null?void 0:S.type]),e.useEffect(()=>{if(!k)return;const x=["mousedown","mousemove","keydown","touchstart","scroll","wheel"],W=()=>{T()};for(const _ of x)document.addEventListener(_,W);return T(),()=>{for(const _ of x)document.removeEventListener(_,W);y.current&&clearTimeout(y.current),F(),I()}},[k,T,F,I]),e.useImperativeHandle(f,()=>({getState:()=>d,activate:U,deactivate:D,toggle:P,resetIdleTimer:T,forceShift:Y,showScreensaver:O,hideScreensaver:b,setDimLevel:s}),[d,U,D,P,T,Y,O,b,s]);const r=()=>{if(!d.isScreensaverActive)return null;const x=i.screensaver||{type:"blank"};switch(x.type){case"blank":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--blank",onClick:b,onTouchStart:b});case"bounce":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--bounce",onClick:b,onTouchStart:b,children:t.jsx("div",{className:"nice-sbp__bounce-logo",style:{left:`${q.x}%`,top:`${q.y}%`},children:t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"1em",height:"1em",background:"currentColor",clipPath:"polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0% 50%)"}})})});case"matrix":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--matrix",onClick:b,onTouchStart:b,children:Array.from({length:20}).map((W,_)=>t.jsx("div",{className:"nice-sbp__matrix-column",style:{left:`${_*5}%`,animationDelay:`${Math.random()*5}s`,animationDuration:`${5+Math.random()*5}s`},children:Array.from({length:20}).map((M,L)=>t.jsx("span",{children:String.fromCharCode(12448+Math.random()*96)},L))},_))});case"noise":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--noise",onClick:b,onTouchStart:b});case"custom":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--custom",onClick:b,onTouchStart:b,children:x.component});default:return null}},a={transform:d.isActive&&i.modes.includes("pixel-shift")?`translate(${d.shiftX}px, ${d.shiftY}px)`:void 0,transition:(E=i.pixelShift)!=null&&E.smooth?"transform 0.5s ease":void 0},c={"--dim-level":d.isDimmed?((m=i.dimming)==null?void 0:m.level)||.3:0,"--dim-duration":`${((w=i.dimming)==null?void 0:w.fadeDuration)||2e3}ms`},o=d.isActive&&i.modes.includes("color-cycling")?{backgroundColor:(u=i.colorCycle)==null?void 0:u.colors[j],transition:`background-color ${((C=i.colorCycle)==null?void 0:C.transitionDuration)||1e3}ms ease`}:{};return t.jsxs("div",{ref:l,className:`nice-sbp ${d.isActive?"nice-sbp--active":""}`,style:{...o},children:[t.jsx("div",{className:"nice-sbp__content",style:a,children:G}),d.isDimmed&&t.jsx("div",{className:"nice-sbp__dim-overlay",style:c,onClick:T,onTouchStart:T}),r(),d.isActive&&i.modes.includes("invert")&&t.jsx("div",{className:"nice-sbp__invert-overlay"})]})});Je.displayName="NiceScreenBurnPrevention";const Xt={pointCount:5,targetSize:40,accuracyThreshold:20,pointTimeout:1e4,showAccuracy:!0,allowRetry:!0,persistCalibration:!0,storageKey:"nice-touch-calibration"},Kt=n=>({4:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:90,targetY:90},{targetX:10,targetY:90}],5:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:50,targetY:50},{targetX:10,targetY:90},{targetX:90,targetY:90}],9:[{targetX:10,targetY:10},{targetX:50,targetY:10},{targetX:90,targetY:10},{targetX:10,targetY:50},{targetX:50,targetY:50},{targetX:90,targetY:50},{targetX:10,targetY:90},{targetX:50,targetY:90},{targetX:90,targetY:90}]})[n],Ze=e.forwardRef((n,f)=>{const{config:h,autoStart:k=!1,onStart:g,onPointCalibrated:N,onComplete:R,onCancel:G,children:i}=n,l={...Xt,...h},y=e.useRef(null),A=e.useRef(null),[v,d]=e.useState({isActive:!1,currentPointIndex:0,totalPoints:l.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),p=e.useCallback(P=>{const T=P.filter(L=>L.calibrated&&L.actualX!==void 0&&L.actualY!==void 0);if(T.length<3)return{scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};let O=0,b=0,s=0,r=0;const a=T.length;for(const L of T)O+=L.targetX,b+=L.targetY,s+=L.actualX,r+=L.actualY;const c=O/a,o=b/a,S=s/a,E=r/a;let m=0,w=0,u=0,C=0;for(const L of T){const X=L.targetX-c,$=L.targetY-o,Z=L.actualX-S,J=L.actualY-E;m+=X*X,w+=X*Z,u+=$*$,C+=$*J}const x=w!==0?m/w:1,W=C!==0?u/C:1,_=c-x*S,M=o-W*E;return{scaleX:x,scaleY:W,offsetX:_,offsetY:M,rotation:0}},[]),j=e.useCallback((P,T)=>{const O=P.filter(s=>s.calibrated);if(O.length===0)return 0;let b=0;for(const s of O){if(s.actualX===void 0||s.actualY===void 0)continue;const r=T.scaleX*s.actualX+T.offsetX,a=T.scaleY*s.actualY+T.offsetY,c=s.targetX-r,o=s.targetY-a;b+=Math.sqrt(c*c+o*o)}return b/O.length},[]),B=e.useCallback(()=>{const T=Kt(l.pointCount).map(O=>({...O,calibrated:!1}));d({isActive:!0,currentPointIndex:0,totalPoints:l.pointCount,points:T,isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),g==null||g()},[l.pointCount,g]),q=e.useCallback(()=>{A.current&&clearTimeout(A.current),d(P=>({...P,isActive:!1,isCompleted:!1})),G==null||G()},[G]),z=e.useCallback(()=>{d(P=>({...P,isCompleted:!1}))},[]),Y=e.useCallback(()=>{if(l.persistCalibration)try{localStorage.removeItem(l.storageKey)}catch{}d({isActive:!1,currentPointIndex:0,totalPoints:l.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0})},[l.persistCalibration,l.storageKey,l.pointCount]),K=e.useCallback(P=>{const T=p(P),O=j(P,T),b=O<=l.accuracyThreshold;if(l.persistCalibration&&b)try{localStorage.setItem(l.storageKey,JSON.stringify({matrix:T,points:P}))}catch{}d(s=>({...s,points:P,isActive:!1,isCompleted:!0,isSuccessful:b,matrix:T,averageError:O})),R==null||R(T,b)},[l.accuracyThreshold,l.persistCalibration,l.storageKey,p,j,R]),F=e.useCallback(P=>{if(!v.isActive||!y.current)return;P.preventDefault();const T=y.current.getBoundingClientRect();let O,b;"touches"in P?(O=P.touches[0].clientX,b=P.touches[0].clientY):(O=P.clientX,b=P.clientY);const s=(O-T.left)/T.width*100,r=(b-T.top)/T.height*100,a=v.currentPointIndex,c=[...v.points];c[a]={...c[a],actualX:s,actualY:r,calibrated:!0};const o=a+1;N==null||N(c[a],a),o>=v.totalPoints?K(c):d(S=>({...S,currentPointIndex:o,points:c}))},[v.isActive,v.currentPointIndex,v.points,v.totalPoints,K,N]),V=e.useCallback((P,T)=>{const O=v.matrix;return O?{x:O.scaleX*P+O.offsetX,y:O.scaleY*T+O.offsetY}:{x:P,y:T}},[v.matrix]),I=e.useCallback(()=>{if(v.matrix)return!0;if(l.persistCalibration)try{return!!localStorage.getItem(l.storageKey)}catch{return!1}return!1},[v.matrix,l.persistCalibration,l.storageKey]),U=e.useCallback(()=>{if(l.persistCalibration)try{localStorage.removeItem(l.storageKey)}catch{}d(P=>({...P,matrix:null}))},[l.persistCalibration,l.storageKey]);if(e.useEffect(()=>{if(l.persistCalibration)try{const P=localStorage.getItem(l.storageKey);if(P){const T=JSON.parse(P);d(O=>({...O,matrix:T.matrix,points:T.points||[],isCompleted:!0,isSuccessful:!0}))}}catch{}},[l.persistCalibration,l.storageKey]),e.useEffect(()=>{if(!v.isActive)return;const P=y.current;if(P)return P.addEventListener("touchstart",F,{passive:!1}),P.addEventListener("mousedown",F),()=>{P.removeEventListener("touchstart",F),P.removeEventListener("mousedown",F)}},[v.isActive,F]),e.useEffect(()=>{if(!(!v.isActive||l.pointTimeout<=0))return A.current=setTimeout(()=>{v.currentPointIndex<v.totalPoints-1?d(P=>({...P,currentPointIndex:P.currentPointIndex+1})):K(v.points)},l.pointTimeout),()=>{A.current&&clearTimeout(A.current)}},[v.isActive,v.currentPointIndex,v.points,v.totalPoints,l.pointTimeout,K]),e.useEffect(()=>{k&&!I()&&B()},[k,I,B]),e.useImperativeHandle(f,()=>({getState:()=>v,start:B,cancel:q,reset:Y,getMatrix:()=>v.matrix,transformPoint:V,hasCalibration:I,clearCalibration:U}),[v,B,q,Y,V,I,U]),!v.isActive&&!v.isCompleted)return t.jsx(t.Fragment,{children:i});const D=v.isActive?v.points[v.currentPointIndex]:void 0;return t.jsxs("div",{ref:y,className:"nice-touch-calibration",children:[t.jsxs("div",{className:"nice-touch-calibration__overlay",children:[t.jsxs("div",{className:"nice-touch-calibration__instructions",children:[t.jsx("h2",{className:"nice-touch-calibration__title",children:"Touch Screen Calibration"}),t.jsx("p",{className:"nice-touch-calibration__text",children:"Touch the center of each target to calibrate your screen."}),t.jsxs("div",{className:"nice-touch-calibration__progress",children:["Point ",v.currentPointIndex+1," of ",v.totalPoints]})]}),D&&t.jsx("div",{className:"nice-touch-calibration__target",style:{left:`${D.targetX}%`,top:`${D.targetY}%`,width:l.targetSize,height:l.targetSize},children:(h==null?void 0:h.targetComponent)||t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"nice-touch-calibration__target-outer"}),t.jsx("div",{className:"nice-touch-calibration__target-inner"}),t.jsx("div",{className:"nice-touch-calibration__target-center"})]})}),v.points.map((P,T)=>P.calibrated&&t.jsx("div",{className:"nice-touch-calibration__calibrated",style:{left:`${P.actualX}%`,top:`${P.actualY}%`}},T)),v.isActive&&t.jsx("button",{className:"nice-touch-calibration__cancel",onClick:q,children:"Cancel"})]}),v.isCompleted&&t.jsxs("div",{className:"nice-touch-calibration__result",children:[t.jsx("div",{className:`nice-touch-calibration__result-icon ${v.isSuccessful?"nice-touch-calibration__result-icon--success":"nice-touch-calibration__result-icon--error"}`,children:t.jsx("span",{className:`nice-platform-mark nice-platform-mark--${v.isSuccessful?"check":"alert"}`,"aria-hidden":"true"})}),t.jsx("h3",{className:"nice-touch-calibration__result-title",children:v.isSuccessful?"Calibration Complete":"Calibration Failed"}),l.showAccuracy&&t.jsxs("p",{className:"nice-touch-calibration__result-accuracy",children:["Average error: ",v.averageError.toFixed(1),"px"]}),!v.isSuccessful&&l.allowRetry&&t.jsx("button",{className:"nice-touch-calibration__retry",onClick:B,children:"Retry Calibration"}),t.jsx("button",{className:"nice-touch-calibration__retry nice-touch-calibration__done",onClick:z,children:"Done"})]})]})});Ze.displayName="NiceTouchCalibration";const Qt={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},Le=104,Jt=106,Zt=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",le=["11011001100","11001101100","11001100110","10010011000","10010001100","10001001100","10011001000","10011000100","10001100100","11001001000","11001000100","11000100100","10110011100","10011011100","10011001110","10111001100","10011101100","10011100110","11001110010","11001011100","11001001110","11011100100","11001110100","11101101110","11101001100","11100101100","11100100110","11101100100","11100110100","11100110010","11011011000","11011000110","11000110110","10100011000","10001011000","10001000110","10110001000","10001101000","10001100010","11010001000","11000101000","11000100010","10110111000","10110001110","10001101110","10111011000","10111000110","10001110110","11101110110","11010001110","11000101110","11011101000","11011100010","11011101110","11101011000","11101000110","11100010110","11101101000","11101100010","11100011010","11101111010","11001000010","11110001010","10100110000","10100001100","10010110000","10010000110","10000101100","10000100110","10110010000","10110000100","10011010000","10011000010","10000110100","10000110010","11000010010","11001010000","11110111010","11000010100","10001111010","10100111100","10010111100","10010011110","10111100100","10011110100","10011110010","11110100100","11110010100","11110010010","11011011110","11011110110","11110110110","10101111000","10100011110","10001011110","10111101000","10111100010","11110101000","11110100010","10111011110","10111101110","11101011110","11110101110","11010000100","11010010000","11010011100","1100011101011"],Re=n=>{let f=le[Le],h=Le;for(let k=0;k<n.length;k++){const g=n[k],N=Zt.indexOf(g);N!==-1&&(f+=le[N],h+=N*(k+1))}return h=h%103,f+=le[h],f+=le[Jt],f},et=["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],en=["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"],tt=["1110010","1100110","1101100","1000010","1011100","1001110","1010000","1000100","1001000","1110100"],tn=["LLLLLL","LLGLGG","LLGGLG","LLGGGL","LGLLGG","LGGLLG","LGGGLL","LGLGLG","LGLGGL","LGGLGL"],nn=n=>{let f=0;for(let h=0;h<12;h++)f+=parseInt(n[h])*(h%2===0?1:3);return(10-f%10)%10},sn=n=>{let f=n.replace(/\D/g,"").slice(0,12).padStart(12,"0");const h=nn(f);f+=h;const k=parseInt(f[0]),g=tn[k];let N="101";for(let R=1;R<=6;R++){const G=parseInt(f[R]);N+=g[R-1]==="L"?et[G]:en[G]}N+="01010";for(let R=7;R<=12;R++){const G=parseInt(f[R]);N+=tt[G]}return N+="101",N},rn=n=>{let f=n.replace(/\D/g,"").slice(0,7).padStart(7,"0"),h=0;for(let N=0;N<7;N++)h+=parseInt(f[N])*(N%2===0?3:1);const k=(10-h%10)%10;f+=k;let g="101";for(let N=0;N<4;N++)g+=et[parseInt(f[N])];g+="01010";for(let N=4;N<8;N++)g+=tt[parseInt(f[N])];return g+="101",g},an={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"},cn=n=>{const f=("*"+n.toUpperCase()+"*").split("");let h="";for(const k of f){const g=an[k];g&&(h+=g+"0")}return h.slice(0,-1)},Oe=n=>{switch(n){case"code128":return Re;case"code39":case"code93":return cn;case"ean13":return sn;case"ean8":return rn;default:return Re}},nt=e.forwardRef((n,f)=>{const{value:h,options:k,onGenerate:g,onError:N,showBorder:R=!1,className:G}=n,i={...Qt,...k},l=e.useRef(null),y=e.useRef(null),[A,v]=e.useState(null),[d,p]=e.useState(null),j=e.useCallback(()=>{if(!l.current||!h)return;const V=l.current,I=V.getContext("2d");if(I)try{const D=Oe(i.format)(h),P=i.width,T=D.length*P,O=i.marginTop??i.margin,b=i.marginBottom??i.margin,s=i.marginLeft??i.margin,r=i.marginRight??i.margin,a=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,c=T+s+r,o=i.height+O+b+a;V.width=c,V.height=o,I.fillStyle=i.background,I.fillRect(0,0,c,o),I.fillStyle=i.lineColor;let S=s;const E=i.textPosition==="top"&&i.displayValue?O+a:O;for(let w=0;w<D.length;w++)D[w]==="1"&&I.fillRect(S,E,P,i.height),S+=P;if(i.displayValue&&!i.flat){I.fillStyle=i.lineColor,I.font=`${i.fontSize}px ${i.font}`,I.textBaseline=i.textPosition==="top"?"top":"bottom";let w=s;i.textAlign==="center"?(w=s+T/2,I.textAlign="center"):i.textAlign==="right"?(w=s+T,I.textAlign="right"):I.textAlign="left";const u=i.textPosition==="top"?O+i.textMargin:o-b-i.textMargin;I.fillText(h,w,u)}const m=V.toDataURL("image/png");p(m),v(null),g==null||g(m)}catch(U){const D=U instanceof Error?U.message:"Failed to generate barcode";v(D),N==null||N(new Error(D))}},[h,i,g,N]);e.useEffect(()=>{j()},[j]);const B=e.useCallback((V="image/png",I=1)=>{var U;return((U=l.current)==null?void 0:U.toDataURL(V,I))||null},[]),q=e.useCallback(()=>{if(!l.current||!h)return null;try{const I=Oe(i.format)(h),U=i.width,D=i.marginTop??i.margin,P=i.marginBottom??i.margin,T=i.marginLeft??i.margin,O=i.marginRight??i.margin,b=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,s=I.length*U,r=s+T+O,a=i.height+D+P+b,c=[];let o=T;const S=i.textPosition==="top"&&i.displayValue?D+b:D;for(let m=0;m<I.length;m++)I[m]==="1"&&c.push(`<rect x="${o}" y="${S}" width="${U}" height="${i.height}" fill="${i.lineColor}"/>`),o+=U;let E="";if(i.displayValue&&!i.flat){const m=i.textAlign==="center"?"middle":i.textAlign==="right"?"end":"start";let w=T;i.textAlign==="center"?w=T+s/2:i.textAlign==="right"&&(w=T+s);const u=i.textPosition==="top"?D+i.fontSize:a-P-i.textMargin;E=`<text x="${w}" y="${u}" font-family="${i.font}" font-size="${i.fontSize}" text-anchor="${m}" fill="${i.lineColor}">${h}</text>`}return`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${a}" viewBox="0 0 ${r} ${a}">
|
|
2
2
|
<rect width="100%" height="100%" fill="${i.background}"/>
|
|
3
|
-
${
|
|
3
|
+
${c.join(`
|
|
4
4
|
`)}
|
|
5
|
-
${
|
|
6
|
-
</svg>`}catch{return null}},[p,i]),V=e.useCallback(()=>d.current,[]),z=e.useCallback((G="barcode",E="png")=>{const $=document.createElement("a");if(E==="svg"){const R=U();if(!R)return;const k=new Blob([R],{type:"image/svg+xml"});$.href=URL.createObjectURL(k),$.download=`${G}.svg`}else{const R=q();if(!R)return;$.href=R,$.download=`${G}.png`}$.click()},[q,U]),Y=e.useCallback(()=>{A()},[A]);e.useImperativeHandle(f,()=>({toDataURL:q,toSVG:U,getCanvas:V,download:z,regenerate:Y}),[q,U,V,z,Y]);const B=["nice-barcode-generator",T&&"nice-barcode-generator--bordered",L&&"nice-barcode-generator--error",P].filter(Boolean).join(" ");return t.jsxs("div",{className:B,children:[t.jsx("canvas",{ref:d,className:"nice-barcode-generator__canvas"}),t.jsx("svg",{ref:b,style:{display:"none"}}),L&&t.jsx("div",{className:"nice-barcode-generator__error",children:t.jsx("span",{children:L})})]})});et.displayName="NiceBarcodeGenerator";const an={formats:["qr_code","ean_13","ean_8","code_128","code_39","upc_a","upc_e"],continuous:!0,scanInterval:100,showBoundingBox:!0,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd"},cn=n=>({aztec:"aztec",code_128:"code_128",code_39:"code_39",code_93:"code_93",codabar:"codabar",data_matrix:"data_matrix",ean_13:"ean_13",ean_8:"ean_8",itf:"itf",pdf417:"pdf417",qr_code:"qr_code",upc_a:"upc_a",upc_e:"upc_e"})[n.toLowerCase().replace("-","_")]||"unknown",on=()=>typeof window<"u"&&"BarcodeDetector"in window,ln=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],un=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),p=n.createGain();f.connect(p),p.connect(n.destination),f.type="sine",f.frequency.value=1e3,p.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},100)}catch{}},dn=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate(50)},tt=e.forwardRef((n,f)=>{const{config:p,onScan:C,onBatchScan:h,onError:N,onCameraReady:T,customScanFrame:P,showScanFrame:i=!0,autoStart:d=!1,children:b,className:L}=n,x={...an,...p},u=e.useRef(null),y=e.useRef(null),A=e.useRef(null),q=e.useRef(null),U=e.useRef(null),V=e.useRef(null),[z,Y]=e.useState(!1),[B,G]=e.useState(!1),[E,$]=e.useState(null),[R,k]=e.useState(null),[S,D]=e.useState(null),[c,s]=e.useState(x.facingMode),[a,r]=e.useState(null),o=on(),l=e.useCallback(async()=>{try{return(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach(X=>X.stop()),D(!0),!0}catch{return D(!1),!1}},[]),j=e.useCallback(async()=>{if(!u.current)return;const M=ln(x.resolution),X={video:{facingMode:c,width:{ideal:M.width},height:{ideal:M.height}},audio:!1};try{const v=await navigator.mediaDevices.getUserMedia(X);A.current=v,u.current.srcObject=v,await u.current.play(),G(!0),D(!0),k(null),T==null||T()}catch(v){const J=v instanceof Error?v.message:"Failed to access camera";k(J),D(!1),N==null||N(new Error(J))}},[x.resolution,c,T,N]),F=e.useCallback(()=>{A.current&&(A.current.getTracks().forEach(M=>M.stop()),A.current=null),u.current&&(u.current.srcObject=null),G(!1)},[]),g=e.useCallback(async()=>{s(c==="user"?"environment":"user"),z&&F()},[c,z,F]),m=e.useCallback(async()=>{if(o)try{const M=window.BarcodeDetector,X=x.formats.map(v=>v.replace("_","-"));q.current=new M({formats:X})}catch(M){const X=M instanceof Error?M.message:"Failed to initialize barcode detector";k(X),N==null||N(new Error(X))}},[o,x.formats,N]),w=e.useCallback(async()=>{if(!(!u.current||!q.current||!B))try{const X=await q.current.detect(u.current);if(X.length>0){const v=X.map(Q=>({rawValue:Q.rawValue,format:cn(Q.format),boundingBox:Q.boundingBox?{x:Q.boundingBox.x,y:Q.boundingBox.y,width:Q.boundingBox.width,height:Q.boundingBox.height}:void 0,cornerPoints:Q.cornerPoints,timestamp:new Date})),J=v[0];if(x.continuous&&J.rawValue===V.current)return;V.current=J.rawValue,x.showBoundingBox&&J.boundingBox&&(r(J.boundingBox),setTimeout(()=>r(null),500)),x.beepOnScan&&un(),x.vibrateOnScan&&dn(),$(J),C==null||C(J),v.length>1&&(h==null||h(v)),setTimeout(()=>{V.current=null},1e3)}}catch{}},[B,x.continuous,x.showBoundingBox,x.beepOnScan,x.vibrateOnScan,C,h]),O=e.useCallback(async()=>{Y(!0),k(null),await m(),await j()},[m,j]),_=e.useCallback(()=>{Y(!1),U.current&&(clearInterval(U.current),U.current=null),F()},[F]),W=e.useCallback(async()=>{z?_():await O()},[z,O,_]),I=e.useCallback(()=>{if(!u.current||!y.current)return null;const M=y.current,X=u.current;M.width=X.videoWidth,M.height=X.videoHeight;const v=M.getContext("2d");return v?(v.drawImage(X,0,0),M.toDataURL("image/png")):null},[]);e.useEffect(()=>(z&&B&&x.continuous&&(U.current=setInterval(w,x.scanInterval)),()=>{U.current&&(clearInterval(U.current),U.current=null)}),[z,B,x.continuous,x.scanInterval,w]),e.useEffect(()=>(d&&O(),()=>{_()}),[]),e.useEffect(()=>{z&&!B&&j()},[c,z,B,j]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:z,isCameraReady:B,lastResult:E,error:R,isSupported:o,hasPermission:S}),start:O,stop:_,toggle:W,takeSnapshot:I,switchCamera:g,requestPermission:l}),[z,B,E,R,o,S,O,_,W,I,g,l]);const H=["nice-barcode-scanner",z&&"nice-barcode-scanner--scanning",B&&"nice-barcode-scanner--ready",R&&"nice-barcode-scanner--error",L].filter(Boolean).join(" ");return t.jsxs("div",{className:H,children:[t.jsx("video",{ref:u,className:"nice-barcode-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:y,className:"nice-barcode-scanner__canvas"}),i&&z&&t.jsxs("div",{className:"nice-barcode-scanner__frame",children:[t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--br"}),t.jsx("div",{className:"nice-barcode-scanner__scan-line"})]}),a&&u.current&&t.jsx("div",{className:"nice-barcode-scanner__bounding-box",style:{left:`${a.x/u.current.videoWidth*100}%`,top:`${a.y/u.current.videoHeight*100}%`,width:`${a.width/u.current.videoWidth*100}%`,height:`${a.height/u.current.videoHeight*100}%`}}),R&&t.jsxs("div",{className:"nice-barcode-scanner__error",children:[t.jsx("div",{className:"nice-barcode-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-barcode-scanner__error-text",children:R}),t.jsx("button",{className:"nice-barcode-scanner__error-btn",onClick:()=>O(),children:"Try Again"})]}),!o&&t.jsx("div",{className:"nice-barcode-scanner__unsupported",children:t.jsx("p",{children:"Barcode scanning is not supported in this browser."})}),b&&t.jsx("div",{className:"nice-barcode-scanner__overlay",children:b})]})});tt.displayName="NiceBarcodeScanner";const nt=e.createContext(null),fn=()=>{const n=e.useContext(nt);if(!n)throw new Error("useBatchScanner must be used within NiceBatchScannerProvider");return n},mn={autoIncrementDuplicates:!0,maxItems:1e3,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,showBoundingBox:!0,allowManualEntry:!0,minConfidence:0},hn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),p=n.createGain();f.connect(p),p.connect(n.destination),f.frequency.value=1200,f.type="sine",p.gain.setValueAtTime(.3,n.currentTime),p.gain.exponentialRampToValueAtTime(.01,n.currentTime+.1),f.start(),f.stop(n.currentTime+.1)}catch{}},gn=(n=50)=>{"vibrate"in navigator&&navigator.vibrate(n)},pn=()=>`${Date.now()}-${Math.random().toString(36).slice(2,11)}`,st=e.forwardRef((n,f)=>{const{options:p,initialItems:C=[],onScan:h,onRemove:N,onBatchComplete:T,onQuantityChange:P,onError:i,validateScan:d,transformValue:b,className:L,children:x}=n,u={...mn,...p},y=e.useRef(null),A=e.useRef(null),q=e.useRef(null),U=e.useRef(null),V=e.useRef(0),z=e.useRef(""),Y=e.useRef(0),[B,G]=e.useState(C),[E,$]=e.useState(!1),[R,k]=e.useState(!1),[S,D]=e.useState(""),[c,s]=e.useState([]),[a,r]=e.useState(null);e.useEffect(()=>{(async()=>{if("BarcodeDetector"in window)try{const J=await BarcodeDetector.getSupportedFormats();J.length>0&&(U.current=new BarcodeDetector({formats:(p==null?void 0:p.formats)||J}),k(!0))}catch{k(!1)}})()},[p==null?void 0:p.formats]);const o=e.useCallback(async(v,J="unknown",Q)=>{const K=b?b(v,J):v;if(d&&!await d(K,J))return;const Z=B.findIndex(ee=>ee.value===K);if(Z!==-1&&u.autoIncrementDuplicates){const ee=[...B];ee[Z]={...ee[Z],quantity:ee[Z].quantity+1,timestamp:Date.now()},G(ee),P==null||P(ee[Z],ee[Z].quantity)}else if(B.length<u.maxItems){const ee={id:pn(),value:K,format:J,timestamp:Date.now(),rawValue:v,quantity:1,boundingBox:Q};G(te=>[ee,...te]),h==null||h(ee)}u.beepOnScan&&hn(),u.vibrateOnScan&&gn()},[B,u,d,b,h,P]),l=e.useCallback(v=>{const J=B.find(Q=>Q.id===v);J&&(G(Q=>Q.filter(K=>K.id!==v)),N==null||N(J))},[B,N]),j=e.useCallback((v,J)=>{if(J<1){l(v);return}G(K=>K.map(Z=>Z.id===v?{...Z,quantity:J}:Z));const Q=B.find(K=>K.id===v);Q&&(P==null||P(Q,J))},[B,l,P]),F=e.useCallback(()=>{G([])},[]),g=e.useCallback(async()=>{if(!y.current||!U.current||!A.current)return;const v=y.current,J=A.current,Q=J.getContext("2d");if(!Q||v.readyState!==v.HAVE_ENOUGH_DATA){V.current=requestAnimationFrame(g);return}J.width=v.videoWidth,J.height=v.videoHeight,Q.drawImage(v,0,0);try{const K=await U.current.detect(J);if(K.length>0){const Z=Date.now(),ee=[];for(const te of K)ee.push(te.boundingBox),(te.rawValue!==z.current||Z-Y.current>2e3)&&(z.current=te.rawValue,Y.current=Z,o(te.rawValue,te.format,te.boundingBox));u.showBoundingBox&&(s(ee),setTimeout(()=>s([]),500))}}catch(K){console.warn("Scan error:",K)}V.current=requestAnimationFrame(g)},[o,u.showBoundingBox]),m=e.useCallback(async()=>{if(!R||!U.current){r("Camera or BarcodeDetector not available"),i==null||i(new Error("Camera or BarcodeDetector not available"));return}try{const v=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:1280},height:{ideal:720}}});q.current=v,y.current&&(y.current.srcObject=v,await y.current.play()),$(!0),r(null),V.current=requestAnimationFrame(g)}catch(v){const J=v instanceof Error?v.message:"Failed to start camera";r(J),i==null||i(new Error(J))}},[R,g,i]),w=e.useCallback(()=>{V.current&&cancelAnimationFrame(V.current),q.current&&(q.current.getTracks().forEach(v=>v.stop()),q.current=null),y.current&&(y.current.srcObject=null),$(!1),s([])},[]);e.useEffect(()=>()=>{w()},[w]);const O=e.useCallback(()=>{S.trim()&&(o(S.trim()),D(""))},[S,o]),_=e.useCallback(()=>{const v=["Value","Format","Quantity","Timestamp"],J=B.map(Q=>[`"${Q.value.replace(/"/g,'""')}"`,Q.format,Q.quantity.toString(),new Date(Q.timestamp).toISOString()]);return[v.join(","),...J.map(Q=>Q.join(","))].join(`
|
|
7
|
-
`)},[
|
|
5
|
+
${E}
|
|
6
|
+
</svg>`}catch{return null}},[h,i]),z=e.useCallback(()=>l.current,[]),Y=e.useCallback((V="barcode",I="png")=>{const U=document.createElement("a");if(I==="svg"){const D=q();if(!D)return;const P=new Blob([D],{type:"image/svg+xml"});U.href=URL.createObjectURL(P),U.download=`${V}.svg`}else{const D=B();if(!D)return;U.href=D,U.download=`${V}.png`}U.click()},[B,q]),K=e.useCallback(()=>{j()},[j]);e.useImperativeHandle(f,()=>({toDataURL:B,toSVG:q,getCanvas:z,download:Y,regenerate:K}),[B,q,z,Y,K]);const F=["nice-barcode-generator",R&&"nice-barcode-generator--bordered",A&&"nice-barcode-generator--error",G].filter(Boolean).join(" ");return t.jsxs("div",{className:F,children:[t.jsx("canvas",{ref:l,className:"nice-barcode-generator__canvas"}),t.jsx("svg",{ref:y,style:{display:"none"}}),A&&t.jsx("div",{className:"nice-barcode-generator__error",children:t.jsx("span",{children:A})})]})});nt.displayName="NiceBarcodeGenerator";const on={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"},ln=n=>({aztec:"aztec",code_128:"code_128",code_39:"code_39",code_93:"code_93",codabar:"codabar",data_matrix:"data_matrix",ean_13:"ean_13",ean_8:"ean_8",itf:"itf",pdf417:"pdf417",qr_code:"qr_code",upc_a:"upc_a",upc_e:"upc_e"})[n.toLowerCase().replace("-","_")]||"unknown",un=()=>typeof window<"u"&&"BarcodeDetector"in window,dn=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],fn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),h=n.createGain();f.connect(h),h.connect(n.destination),f.type="sine",f.frequency.value=1e3,h.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},100)}catch{}},mn=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate(50)},st=e.forwardRef((n,f)=>{const{config:h,onScan:k,onBatchScan:g,onError:N,onCameraReady:R,customScanFrame:G,showScanFrame:i=!0,autoStart:l=!1,children:y,className:A}=n,v={...on,...h},d=e.useRef(null),p=e.useRef(null),j=e.useRef(null),B=e.useRef(null),q=e.useRef(null),z=e.useRef(null),[Y,K]=e.useState(!1),[F,V]=e.useState(!1),[I,U]=e.useState(null),[D,P]=e.useState(null),[T,O]=e.useState(null),[b,s]=e.useState(v.facingMode),[r,a]=e.useState(null),c=un(),o=e.useCallback(async()=>{try{return(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach(X=>X.stop()),O(!0),!0}catch{return O(!1),!1}},[]),S=e.useCallback(async()=>{if(!d.current)return;const L=dn(v.resolution),X={video:{facingMode:b,width:{ideal:L.width},height:{ideal:L.height}},audio:!1};try{const $=await navigator.mediaDevices.getUserMedia(X);j.current=$,d.current.srcObject=$,await d.current.play(),V(!0),O(!0),P(null),R==null||R()}catch($){const Z=$ instanceof Error?$.message:"Failed to access camera";P(Z),O(!1),N==null||N(new Error(Z))}},[v.resolution,b,R,N]),E=e.useCallback(()=>{j.current&&(j.current.getTracks().forEach(L=>L.stop()),j.current=null),d.current&&(d.current.srcObject=null),V(!1)},[]),m=e.useCallback(async()=>{s(b==="user"?"environment":"user"),Y&&E()},[b,Y,E]),w=e.useCallback(async()=>{if(c)try{const L=window.BarcodeDetector,X=v.formats.map($=>$.replace("_","-"));B.current=new L({formats:X})}catch(L){const X=L instanceof Error?L.message:"Failed to initialize barcode detector";P(X),N==null||N(new Error(X))}},[c,v.formats,N]),u=e.useCallback(async()=>{if(!(!d.current||!B.current||!F))try{const X=await B.current.detect(d.current);if(X.length>0){const $=X.map(J=>({rawValue:J.rawValue,format:ln(J.format),boundingBox:J.boundingBox?{x:J.boundingBox.x,y:J.boundingBox.y,width:J.boundingBox.width,height:J.boundingBox.height}:void 0,cornerPoints:J.cornerPoints,timestamp:new Date})),Z=$[0];if(v.continuous&&Z.rawValue===z.current)return;z.current=Z.rawValue,v.showBoundingBox&&Z.boundingBox&&(a(Z.boundingBox),setTimeout(()=>a(null),500)),v.beepOnScan&&fn(),v.vibrateOnScan&&mn(),U(Z),k==null||k(Z),$.length>1&&(g==null||g($)),setTimeout(()=>{z.current=null},1e3)}}catch{}},[F,v.continuous,v.showBoundingBox,v.beepOnScan,v.vibrateOnScan,k,g]),C=e.useCallback(async()=>{K(!0),P(null),await w(),await S()},[w,S]),x=e.useCallback(()=>{K(!1),q.current&&(clearInterval(q.current),q.current=null),E()},[E]),W=e.useCallback(async()=>{Y?x():await C()},[Y,C,x]),_=e.useCallback(()=>{if(!d.current||!p.current)return null;const L=p.current,X=d.current;L.width=X.videoWidth,L.height=X.videoHeight;const $=L.getContext("2d");return $?($.drawImage(X,0,0),L.toDataURL("image/png")):null},[]);e.useEffect(()=>(Y&&F&&v.continuous&&(q.current=setInterval(u,v.scanInterval)),()=>{q.current&&(clearInterval(q.current),q.current=null)}),[Y,F,v.continuous,v.scanInterval,u]),e.useEffect(()=>(l&&C(),()=>{x()}),[]),e.useEffect(()=>{Y&&!F&&S()},[b,Y,F,S]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:Y,isCameraReady:F,lastResult:I,error:D,isSupported:c,hasPermission:T}),start:C,stop:x,toggle:W,takeSnapshot:_,switchCamera:m,requestPermission:o}),[Y,F,I,D,c,T,C,x,W,_,m,o]);const M=["nice-barcode-scanner",Y&&"nice-barcode-scanner--scanning",F&&"nice-barcode-scanner--ready",D&&"nice-barcode-scanner--error",A].filter(Boolean).join(" ");return t.jsxs("div",{className:M,children:[t.jsx("video",{ref:d,className:"nice-barcode-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:p,className:"nice-barcode-scanner__canvas"}),i&&Y&&t.jsxs("div",{className:"nice-barcode-scanner__frame",children:[t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--br"}),t.jsx("div",{className:"nice-barcode-scanner__scan-line"})]}),r&&d.current&&t.jsx("div",{className:"nice-barcode-scanner__bounding-box",style:{left:`${r.x/d.current.videoWidth*100}%`,top:`${r.y/d.current.videoHeight*100}%`,width:`${r.width/d.current.videoWidth*100}%`,height:`${r.height/d.current.videoHeight*100}%`}}),D&&t.jsxs("div",{className:"nice-barcode-scanner__error",children:[t.jsx("div",{className:"nice-barcode-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-barcode-scanner__error-text",children:D}),t.jsx("button",{className:"nice-barcode-scanner__error-btn",onClick:()=>C(),children:"Try Again"})]}),!c&&t.jsx("div",{className:"nice-barcode-scanner__unsupported",children:t.jsx("p",{children:"Barcode scanning is not supported in this browser."})}),y&&t.jsx("div",{className:"nice-barcode-scanner__overlay",children:y})]})});st.displayName="NiceBarcodeScanner";const xe=e.createContext(null),rt=e.createContext(null),ce=n=>()=>{process.env.NODE_ENV!=="production"&&console.warn(`[NiceBatchScannerProvider] ${n}: no NiceBatchScanner is mounted below it.`)},hn={items:[],isScanning:!1,addItem:ce("addItem"),removeItem:ce("removeItem"),updateQuantity:ce("updateQuantity"),clearAll:ce("clearAll"),startScanning:async()=>ce("startScanning")(),stopScanning:ce("stopScanning")},gn=()=>{const n=e.useContext(xe);if(!n)throw new Error("useBatchScanner must be used inside NiceBatchScanner or below NiceBatchScannerProvider");return n},pn={autoIncrementDuplicates:!0,maxItems:1e3,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,showBoundingBox:!0,allowManualEntry:!0,minConfidence:0},yn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),h=n.createGain();f.connect(h),h.connect(n.destination),f.frequency.value=1200,f.type="sine",h.gain.setValueAtTime(.3,n.currentTime),h.gain.exponentialRampToValueAtTime(.01,n.currentTime+.1),f.start(),f.stop(n.currentTime+.1)}catch{}},bn=(n=50)=>{"vibrate"in navigator&&navigator.vibrate(n)},wn=()=>`${Date.now()}-${Math.random().toString(36).slice(2,11)}`,at=e.forwardRef((n,f)=>{const{options:h,initialItems:k=[],onScan:g,onRemove:N,onBatchComplete:R,onQuantityChange:G,onError:i,validateScan:l,transformValue:y,className:A,children:v}=n,d=e.useMemo(()=>({...pn,...h}),[h]),p=e.useRef(null),j=e.useRef(null),B=e.useRef(null),q=e.useRef(null),z=e.useRef(0),Y=e.useRef(""),K=e.useRef(0),[F,V]=e.useState(k),[I,U]=e.useState(!1),[D,P]=e.useState(!1),[T,O]=e.useState(""),[b,s]=e.useState([]),[r,a]=e.useState(null);e.useEffect(()=>{(async()=>{if("BarcodeDetector"in window)try{const Q=await BarcodeDetector.getSupportedFormats();Q.length>0&&(q.current=new BarcodeDetector({formats:(h==null?void 0:h.formats)||Q}),P(!0))}catch{P(!1)}})()},[h==null?void 0:h.formats]);const c=e.useCallback(async(H,Q="unknown",ee)=>{const te=y?y(H,Q):H;if(l&&!await l(te,Q))return;const ne=F.findIndex(se=>se.value===te);if(ne!==-1&&d.autoIncrementDuplicates){const se=[...F];se[ne]={...se[ne],quantity:se[ne].quantity+1,timestamp:Date.now()},V(se),G==null||G(se[ne],se[ne].quantity)}else if(F.length<d.maxItems){const se={id:wn(),value:te,format:Q,timestamp:Date.now(),rawValue:H,quantity:1,boundingBox:ee};V(re=>[se,...re]),g==null||g(se)}d.beepOnScan&&yn(),d.vibrateOnScan&&bn()},[F,d,l,y,g,G]),o=e.useCallback(H=>{const Q=F.find(ee=>ee.id===H);Q&&(V(ee=>ee.filter(te=>te.id!==H)),N==null||N(Q))},[F,N]),S=e.useCallback((H,Q)=>{if(Q<1){o(H);return}V(te=>te.map(ne=>ne.id===H?{...ne,quantity:Q}:ne));const ee=F.find(te=>te.id===H);ee&&(G==null||G(ee,Q))},[F,o,G]),E=e.useCallback(()=>{V([])},[]),m=e.useCallback(async()=>{if(!p.current||!q.current||!j.current)return;const H=p.current,Q=j.current,ee=Q.getContext("2d");if(!ee||H.readyState!==H.HAVE_ENOUGH_DATA){z.current=requestAnimationFrame(m);return}Q.width=H.videoWidth,Q.height=H.videoHeight,ee.drawImage(H,0,0);try{const te=await q.current.detect(Q);if(te.length>0){const ne=Date.now(),se=[];for(const re of te)se.push(re.boundingBox),(re.rawValue!==Y.current||ne-K.current>2e3)&&(Y.current=re.rawValue,K.current=ne,c(re.rawValue,re.format,re.boundingBox));d.showBoundingBox&&(s(se),setTimeout(()=>s([]),500))}}catch(te){console.warn("Scan error:",te)}z.current=requestAnimationFrame(m)},[c,d.showBoundingBox]),w=e.useCallback(async()=>{if(!D||!q.current){a("Camera or BarcodeDetector not available"),i==null||i(new Error("Camera or BarcodeDetector not available"));return}try{const H=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:1280},height:{ideal:720}}});B.current=H,p.current&&(p.current.srcObject=H,await p.current.play()),U(!0),a(null),z.current=requestAnimationFrame(m)}catch(H){const Q=H instanceof Error?H.message:"Failed to start camera";a(Q),i==null||i(new Error(Q))}},[D,m,i]),u=e.useCallback(()=>{z.current&&cancelAnimationFrame(z.current),B.current&&(B.current.getTracks().forEach(H=>H.stop()),B.current=null),p.current&&(p.current.srcObject=null),U(!1),s([])},[]);e.useEffect(()=>()=>{u()},[u]);const C=e.useCallback(()=>{T.trim()&&(c(T.trim()),O(""))},[T,c]),x=e.useCallback(()=>{const H=["Value","Format","Quantity","Timestamp"],Q=F.map(ee=>[`"${ee.value.replace(/"/g,'""')}"`,ee.format,ee.quantity.toString(),new Date(ee.timestamp).toISOString()]);return[H.join(","),...Q.map(ee=>ee.join(","))].join(`
|
|
7
|
+
`)},[F]),W=e.useCallback(()=>JSON.stringify(F,null,2),[F]),_=e.useCallback(()=>{u(),R==null||R(F)},[F,u,R]);e.useImperativeHandle(f,()=>({startScanning:w,stopScanning:u,getItems:()=>F,addItem:(H,Q)=>c(H,Q),removeItem:o,updateQuantity:S,clearAll:E,exportCSV:x,exportJSON:W,isScanning:()=>I}),[w,u,F,c,o,S,E,x,W,I]);const M={items:F,isScanning:I,addItem:(H,Q)=>c(H,Q),removeItem:o,updateQuantity:S,clearAll:E,startScanning:w,stopScanning:u},L=e.useContext(rt),X=e.useRef(M);e.useEffect(()=>{X.current=M});const $=e.useMemo(()=>({items:F,isScanning:I,addItem:(H,Q)=>X.current.addItem(H,Q),removeItem:H=>X.current.removeItem(H),updateQuantity:(H,Q)=>X.current.updateQuantity(H,Q),clearAll:()=>X.current.clearAll(),startScanning:()=>X.current.startScanning(),stopScanning:()=>X.current.stopScanning()}),[F,I]);e.useEffect(()=>{L==null||L($)},[L,$]),e.useEffect(()=>{if(L)return()=>L(null)},[L]);const Z=F.reduce((H,Q)=>H+Q.quantity,0),J=["nice-batch-scanner",I&&"nice-batch-scanner--scanning",A].filter(Boolean).join(" ");return t.jsx(xe.Provider,{value:M,children:t.jsxs("div",{className:J,children:[t.jsxs("div",{className:"nice-batch-scanner__scanner",children:[t.jsx("video",{ref:p,className:"nice-batch-scanner__video",playsInline:!0,muted:!0,autoPlay:!0}),t.jsx("canvas",{ref:j,className:"nice-batch-scanner__canvas"}),p.current&&b.map((H,Q)=>{const ee=p.current,te=ee.clientWidth/ee.videoWidth,ne=ee.clientHeight/ee.videoHeight;return t.jsx("div",{className:"nice-batch-scanner__bounding-box",style:{left:H.x*te,top:H.y*ne,width:H.width*te,height:H.height*ne}},Q)}),I&&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"})]}),r&&t.jsx("div",{className:"nice-batch-scanner__error",children:t.jsx("span",{children:r})}),!I&&!r&&t.jsxs("div",{className:"nice-batch-scanner__placeholder",children:[t.jsx("span",{className:"nice-platform-mark nice-platform-mark--viewfinder","aria-hidden":"true"}),t.jsx("p",{children:"Tap to start scanning"})]})]}),t.jsxs("div",{className:"nice-batch-scanner__controls",children:[t.jsx("button",{className:`nice-batch-scanner__btn nice-batch-scanner__btn--${I?"stop":"start"}`,onClick:I?u:w,children:I?"Stop Scanning":"Start Scanning"}),d.allowManualEntry&&t.jsxs("div",{className:"nice-batch-scanner__manual",children:[t.jsx("input",{type:"text",value:T,onChange:H=>O(H.target.value),onKeyDown:H=>H.key==="Enter"&&C(),placeholder:"Enter code manually...",className:"nice-batch-scanner__manual-input"}),t.jsx("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--add",onClick:C,disabled:!T.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:Z})," total quantity"]})]}),t.jsxs("div",{className:"nice-batch-scanner__items",children:[F.map(H=>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:H.value}),t.jsx("span",{className:"nice-batch-scanner__item-format",children:H.format})]}),t.jsxs("div",{className:"nice-batch-scanner__item-quantity",children:[t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>S(H.id,H.quantity-1),"aria-label":"Decrease quantity",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--minus","aria-hidden":"true"})}),t.jsx("span",{className:"nice-batch-scanner__qty-value",children:H.quantity}),t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>S(H.id,H.quantity+1),"aria-label":"Increase quantity",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--plus","aria-hidden":"true"})})]}),t.jsx("button",{className:"nice-batch-scanner__item-remove",onClick:()=>o(H.id),"aria-label":"Remove item",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]},H.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:E,children:"Clear All"}),t.jsxs("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--primary",onClick:_,children:["Complete Batch (",Z,")"]})]}),v]})})});at.displayName="NiceBatchScanner";const vn=({children:n})=>{const[f,h]=e.useState(null);return t.jsx(rt.Provider,{value:h,children:t.jsx(xe.Provider,{value:f??hn,children:n})})},xn={errorCorrection:"M",size:200,margin:2,darkColor:"#000000",lightColor:"#ffffff",logoSize:.2,logoMargin:1,cornerRadius:0},Cn={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]},kn=(n,f)=>{const h=n.length,k=Cn[f];for(let g=0;g<k.length;g++)if(k[g]>=h)return g+1;return 10},Te=(n,f)=>{const h=kn(n,f),k=h*4+17,g=Array(k).fill(null).map(()=>Array(k).fill(!1)),N=Array(k).fill(null).map(()=>Array(k).fill(!1)),R=(l,y)=>{for(let A=-1;A<=7;A++)for(let v=-1;v<=7;v++){const d=l+A,p=y+v;d<0||d>=k||p<0||p>=k||(N[d][p]=!0,A===-1||A===7||v===-1||v===7?g[d][p]=!1:A===0||A===6||v===0||v===6||A>=2&&A<=4&&v>=2&&v<=4?g[d][p]=!0:g[d][p]=!1)}};R(0,0),R(0,k-7),R(k-7,0);for(let l=8;l<k-8;l++)g[6][l]=l%2===0,g[l][6]=l%2===0,N[6][l]=!0,N[l][6]=!0;if(h>=2){const l=[6,k-7];h>=7&&l.splice(1,0,Math.floor(k/2));for(const y of l)for(const A of l)if(!(y<9&&A<9||y<9&&A>k-10||y>k-10&&A<9))for(let v=-2;v<=2;v++)for(let d=-2;d<=2;d++){const p=y+v,j=A+d;p<0||p>=k||j<0||j>=k||(N[p][j]=!0,g[p][j]=v===-2||v===2||d===-2||d===2||v===0&&d===0)}}const G=n.split("").reduce((l,y)=>(l<<5)-l+y.charCodeAt(0),0);let i=0;for(let l=k-1;l>=0;l-=2){l===6&&(l=5);for(let y=0;y<k;y++)for(let A=0;A<=1;A++){const v=l-A;if(N[y][v])continue;const d=i%n.length,p=n.charCodeAt(d)&1<<i%8,j=(G+y*k+v)%256>127;g[y][v]=p!==0!==j,i++}}return g},it=e.forwardRef((n,f)=>{const{value:h,options:k,onGenerate:g,onError:N,showBorder:R=!1,className:G}=n,i={...xn,...k},l=e.useRef(null),y=e.useRef(null),[A,v]=e.useState(null),[d,p]=e.useState(!(k!=null&&k.logo));e.useEffect(()=>{if(k!=null&&k.logo){const F=new Image;F.crossOrigin="anonymous",F.onload=()=>{y.current=F,p(!0)},F.onerror=()=>{y.current=null,p(!0)},F.src=k.logo}else y.current=null,p(!0)},[k==null?void 0:k.logo]);const j=e.useCallback(()=>{if(!l.current||!h||!d)return;const F=l.current,V=F.getContext("2d");if(V)try{const I=Te(h,i.errorCorrection),U=I.length,D=Math.floor((i.size-i.margin*2)/U),P=U*D+i.margin*2*D;F.width=P,F.height=P,V.fillStyle=i.lightColor,V.fillRect(0,0,P,P),V.fillStyle=i.darkColor;const T=i.margin*D;for(let b=0;b<U;b++)for(let s=0;s<U;s++)if(I[b][s]){const r=T+s*D,a=T+b*D;if(i.cornerRadius>0){const c=Math.min(i.cornerRadius,D/2);V.beginPath(),V.roundRect(r,a,D,D,c),V.fill()}else V.fillRect(r,a,D,D)}if(y.current){const b=P*i.logoSize,s=(P-b)/2,r=(P-b)/2,a=i.logoMargin*D;V.fillStyle=i.lightColor,V.fillRect(s-a,r-a,b+a*2,b+a*2),V.drawImage(y.current,s,r,b,b)}const O=F.toDataURL("image/png");v(null),g==null||g(O)}catch(I){const U=I instanceof Error?I.message:"Failed to generate QR code";v(U),N==null||N(new Error(U))}},[h,i,d,g,N]);e.useEffect(()=>{j()},[j]);const B=e.useCallback((F="image/png",V=1)=>{var I;return((I=l.current)==null?void 0:I.toDataURL(F,V))||null},[]),q=e.useCallback(()=>{if(!l.current||!h)return null;try{const F=Te(h,i.errorCorrection),V=F.length,I=Math.floor((i.size-i.margin*2)/V),U=V*I+i.margin*2*I,D=i.margin*I,P=[];for(let T=0;T<V;T++)for(let O=0;O<V;O++)if(F[T][O]){const b=D+O*I,s=D+T*I;if(i.cornerRadius>0){const r=Math.min(i.cornerRadius,I/2);P.push(`<rect x="${b}" y="${s}" width="${I}" height="${I}" rx="${r}" fill="${i.darkColor}"/>`)}else P.push(`<rect x="${b}" y="${s}" width="${I}" height="${I}" fill="${i.darkColor}"/>`)}return`<svg xmlns="http://www.w3.org/2000/svg" width="${U}" height="${U}" viewBox="0 0 ${U} ${U}">
|
|
8
8
|
<rect width="100%" height="100%" fill="${i.lightColor}"/>
|
|
9
|
-
${
|
|
9
|
+
${P.join(`
|
|
10
10
|
`)}
|
|
11
|
-
</svg>`}catch{return null}},[p,i]),V=e.useCallback((B="qrcode",G="png")=>{const E=document.createElement("a");if(G==="svg"){const $=U();if(!$)return;const R=new Blob([$],{type:"image/svg+xml"});E.href=URL.createObjectURL(R),E.download=`${B}.svg`}else{const $=q();if(!$)return;E.href=$,E.download=`${B}.png`}E.click()},[q,U]),z=e.useCallback(()=>{A()},[A]);e.useImperativeHandle(f,()=>({toDataURL:q,toSVG:U,download:V,regenerate:z}),[q,U,V,z]);const Y=["nice-qr-generator",T&&"nice-qr-generator--bordered",L&&"nice-qr-generator--error",P].filter(Boolean).join(" ");return t.jsxs("div",{className:Y,children:[t.jsx("canvas",{ref:d,className:"nice-qr-generator__canvas",style:{maxWidth:"100%",height:"auto"}}),L&&t.jsx("div",{className:"nice-qr-generator__error",children:t.jsx("span",{children:L})})]})});rt.displayName="NiceQRGenerator";const xn={continuous:!0,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd",parseDataType:!0,highlightDetected:!0},Cn=n=>{var f,p,C;if(/^https?:\/\//i.test(n))return{type:"url",data:{url:n}};if(/^mailto:/i.test(n)){const h=n.match(/^mailto:([^?]+)(?:\?(.*))?$/i);return{type:"email",data:{email:h==null?void 0:h[1],params:h==null?void 0:h[2]}}}if(/^tel:/i.test(n))return{type:"tel",data:{phone:n.replace(/^tel:/i,"")}};if(/^smsto?:/i.test(n)){const h=n.match(/^smsto?:([^:]+)(?::(.*))?$/i);return{type:"sms",data:{phone:h==null?void 0:h[1],message:h==null?void 0:h[2]}}}if(/^geo:/i.test(n)){const h=n.match(/^geo:(-?\d+\.?\d*),(-?\d+\.?\d*)(?:,(-?\d+\.?\d*))?/i);return{type:"geo",data:{latitude:parseFloat((h==null?void 0:h[1])||"0"),longitude:parseFloat((h==null?void 0:h[2])||"0"),altitude:h!=null&&h[3]?parseFloat(h[3]):void 0}}}if(/^BEGIN:VCARD/i.test(n))return{type:"vcard",data:{raw:n}};if(/^BEGIN:VEVENT/i.test(n))return{type:"vevent",data:{raw:n}};if(/^WIFI:/i.test(n)){const h=(f=n.match(/S:([^;]+)/))==null?void 0:f[1],N=(p=n.match(/P:([^;]+)/))==null?void 0:p[1],T=(C=n.match(/T:([^;]+)/))==null?void 0:C[1],P=n.includes("H:true");return{type:"wifi",data:{ssid:h,password:N,type:T,hidden:P}}}return{type:"text"}},kn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),p=n.createGain();f.connect(p),p.connect(n.destination),f.type="square",f.frequency.value=1200,p.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},80)}catch{}},Sn=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate([50,30,50])},_n=()=>typeof window<"u"&&"BarcodeDetector"in window,Nn=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],at=e.forwardRef((n,f)=>{const{config:p,onScan:C,onError:h,onCameraReady:N,autoStart:T=!1,showScanFrame:P=!0,children:i,className:d}=n,b={...xn,...p},L=e.useRef(null),x=e.useRef(null),u=e.useRef(null),y=e.useRef(null),A=e.useRef(null),q=e.useRef(null),[U,V]=e.useState(!1),[z,Y]=e.useState(!1),[B,G]=e.useState(null),[E,$]=e.useState(null),[R,k]=e.useState(null),[S,D]=e.useState(b.facingMode),[c,s]=e.useState(!1),[a,r]=e.useState(!1),[o,l]=e.useState(null),j=_n(),F=e.useCallback(async()=>{var Z;if(!L.current)return;const Q=Nn(b.resolution),K={video:{facingMode:S,width:{ideal:Q.width},height:{ideal:Q.height}},audio:!1};try{const ee=await navigator.mediaDevices.getUserMedia(K);u.current=ee,L.current.srcObject=ee,await L.current.play();const te=ee.getVideoTracks()[0],ne=(Z=te.getCapabilities)==null?void 0:Z.call(te);s(!!(ne!=null&&ne.torch)),Y(!0),k(!0),$(null),N==null||N()}catch(ee){const te=ee instanceof Error?ee.message:"Failed to access camera";$(te),k(!1),h==null||h(new Error(te))}},[b.resolution,S,N,h]),g=e.useCallback(()=>{u.current&&(u.current.getTracks().forEach(Q=>Q.stop()),u.current=null),L.current&&(L.current.srcObject=null),Y(!1),r(!1)},[]),m=e.useCallback(async()=>{D(S==="user"?"environment":"user"),U&&g()},[S,U,g]),w=e.useCallback(async()=>{if(!u.current||!c)return;const Q=u.current.getVideoTracks()[0],K=!a;try{await Q.applyConstraints({advanced:[{torch:K}]}),r(K)}catch{}},[c,a]),O=e.useCallback(async()=>{if(j)try{const Q=window.BarcodeDetector;y.current=new Q({formats:["qr_code"]})}catch(Q){const K=Q instanceof Error?Q.message:"Failed to initialize QR detector";$(K),h==null||h(new Error(K))}},[j,h]),_=e.useCallback((Q,K)=>{const Z={text:Q,boundingBox:K.boundingBox?{x:K.boundingBox.x,y:K.boundingBox.y,width:K.boundingBox.width,height:K.boundingBox.height}:void 0,cornerPoints:K.cornerPoints,timestamp:new Date};if(b.parseDataType){const ee=Cn(Q);Z.dataType=ee.type,Z.parsedData=ee.data}return Z},[b.parseDataType]),W=e.useCallback(async()=>{if(!(!L.current||!y.current||!z))try{const K=await y.current.detect(L.current);if(K.length>0){const Z=K[0];if(b.continuous&&Z.rawValue===q.current)return;q.current=Z.rawValue;const ee=_(Z.rawValue,Z);b.highlightDetected&&ee.boundingBox&&(l(ee.boundingBox),setTimeout(()=>l(null),500)),b.beepOnScan&&kn(),b.vibrateOnScan&&Sn(),G(ee),C==null||C(ee),setTimeout(()=>{q.current=null},1e3)}}catch{}},[z,b.continuous,b.highlightDetected,b.beepOnScan,b.vibrateOnScan,_,C]),I=e.useCallback(async()=>{V(!0),$(null),await O(),await F()},[O,F]),H=e.useCallback(()=>{V(!1),A.current&&(clearInterval(A.current),A.current=null),g()},[g]),M=e.useCallback(async()=>{U?H():await I()},[U,I,H]),X=e.useCallback(()=>{if(!L.current||!x.current)return null;const Q=x.current,K=L.current;Q.width=K.videoWidth,Q.height=K.videoHeight;const Z=Q.getContext("2d");return Z?(Z.drawImage(K,0,0),Q.toDataURL("image/png")):null},[]),v=e.useCallback(async Q=>!j||!y.current?null:new Promise(K=>{const Z=new Image;Z.onload=async()=>{try{const te=await y.current.detect(Z);if(te.length>0){const ne=_(te[0].rawValue,te[0]);K(ne)}else K(null)}catch{K(null)}},Z.onerror=()=>K(null),Z.src=URL.createObjectURL(Q)}),[j,_]);e.useEffect(()=>(U&&z&&b.continuous&&(A.current=setInterval(W,b.scanInterval)),()=>{A.current&&(clearInterval(A.current),A.current=null)}),[U,z,b.continuous,b.scanInterval,W]),e.useEffect(()=>(T&&I(),()=>{H()}),[]),e.useEffect(()=>{U&&!z&&F()},[S,U,z,F]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:U,isCameraReady:z,lastResult:B,error:E,isSupported:j,hasPermission:R,torchAvailable:c,torchOn:a}),start:I,stop:H,toggle:M,switchCamera:m,toggleTorch:w,takeSnapshot:X,scanImage:v}),[U,z,B,E,j,R,c,a,I,H,M,m,w,X,v]);const J=["nice-qr-scanner",U&&"nice-qr-scanner--scanning",z&&"nice-qr-scanner--ready",E&&"nice-qr-scanner--error",d].filter(Boolean).join(" ");return t.jsxs("div",{className:J,children:[t.jsx("video",{ref:L,className:"nice-qr-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:x,className:"nice-qr-scanner__canvas"}),P&&U&&t.jsxs("div",{className:"nice-qr-scanner__frame",children:[t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--br"})]}),o&&L.current&&t.jsx("div",{className:"nice-qr-scanner__bounding-box",style:{left:`${o.x/L.current.videoWidth*100}%`,top:`${o.y/L.current.videoHeight*100}%`,width:`${o.width/L.current.videoWidth*100}%`,height:`${o.height/L.current.videoHeight*100}%`}}),E&&t.jsxs("div",{className:"nice-qr-scanner__error",children:[t.jsx("div",{className:"nice-qr-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-qr-scanner__error-text",children:E}),t.jsx("button",{className:"nice-qr-scanner__error-btn",onClick:()=>I(),children:"Try Again"})]}),!j&&t.jsx("div",{className:"nice-qr-scanner__unsupported",children:t.jsx("p",{children:"QR scanning is not supported in this browser."})}),i&&t.jsx("div",{className:"nice-qr-scanner__overlay",children:i})]})});at.displayName="NiceQRScanner";const ve=e.createContext(null),In=()=>{const n=e.useContext(ve);if(!n)throw new Error("useSymbology must be used within NiceSymbologyConfigProvider");return n},ae=[{id:"code128",name:"Code 128",category:"linear",description:"High-density barcode for alphanumeric data. Auto-switches between subsets A/B/C.",charset:"ASCII 0-127",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Shipping labels","Inventory","General purpose"],standard:"ISO/IEC 15417",detectorFormat:"code_128"},{id:"code128a",name:"Code 128A",category:"linear",description:"Code 128 subset A: uppercase + control characters.",charset:"ASCII 0-95 (uppercase, digits, control chars)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Systems with control characters","Legacy integration"],standard:"ISO/IEC 15417"},{id:"code128b",name:"Code 128B",category:"linear",description:"Code 128 subset B: uppercase + lowercase.",charset:"ASCII 32-127 (upper/lowercase, digits, symbols)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Alphanumeric data","Mixed case text"],standard:"ISO/IEC 15417"},{id:"code128c",name:"Code 128C",category:"linear",description:"Code 128 subset C: double-density numeric only.",charset:"0-9 (pairs only)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Long numeric values","Compact encoding"],standard:"ISO/IEC 15417"},{id:"code39",name:"Code 39",category:"linear",description:"Self-checking barcode supporting uppercase and digits.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Military (LOGMARS)","Automotive (AIAG)","Healthcare"],standard:"ISO/IEC 16388",detectorFormat:"code_39"},{id:"code93",name:"Code 93",category:"linear",description:"Compact barcode, denser than Code 39.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Canadian postal","General logistics"],standard:"ANSI/AIM BC5",detectorFormat:"code_93"},{id:"codabar",name:"Codabar",category:"linear",description:"Numeric barcode used in libraries and blood banks.",charset:"0-9, -, $, :, /, ., +, A-D (start/stop)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Blood banks","Libraries","FedEx"],standard:"ANSI/AIM BC3",detectorFormat:"codabar"},{id:"ean13",name:"EAN-13",category:"linear",description:"European Article Numbering — worldwide retail standard.",charset:"0-9",minLength:12,maxLength:12,fixedLength:13,hasCheckDigit:!0,useCases:["Retail worldwide","ISBN","ISSN"],standard:"ISO/IEC 15420",detectorFormat:"ean_13"},{id:"ean8",name:"EAN-8",category:"linear",description:"Compact version of EAN-13 for small products.",charset:"0-9",minLength:7,maxLength:7,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Space-constrained packaging"],standard:"ISO/IEC 15420",detectorFormat:"ean_8"},{id:"ean5",name:"EAN-5 Supplement",category:"linear",description:"5-digit addon for periodicals and books.",charset:"0-9",minLength:5,maxLength:5,fixedLength:5,hasCheckDigit:!0,useCases:["Book pricing","Magazine issues"],standard:"ISO/IEC 15420"},{id:"ean2",name:"EAN-2 Supplement",category:"linear",description:"2-digit addon for periodicals.",charset:"0-9",minLength:2,maxLength:2,fixedLength:2,hasCheckDigit:!1,useCases:["Magazine issue numbers"],standard:"ISO/IEC 15420"},{id:"upc_a",name:"UPC-A",category:"linear",description:"Universal Product Code — North American retail standard.",charset:"0-9",minLength:11,maxLength:11,fixedLength:12,hasCheckDigit:!0,useCases:["US/Canada retail","Point of Sale"],standard:"ISO/IEC 15420",detectorFormat:"upc_a"},{id:"upc_e",name:"UPC-E",category:"linear",description:"Compressed UPC for small packages.",charset:"0-9",minLength:6,maxLength:6,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Compact packaging"],standard:"ISO/IEC 15420",detectorFormat:"upc_e"},{id:"itf",name:"Interleaved 2 of 5",category:"linear",description:"Numeric pairs encoded in interleaved format.",charset:"0-9 (even length)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Warehouse distribution","Packaging"],standard:"ISO/IEC 16390",detectorFormat:"itf"},{id:"itf14",name:"ITF-14",category:"linear",description:"GTIN-14 barcode for shipping containers.",charset:"0-9",minLength:13,maxLength:13,fixedLength:14,hasCheckDigit:!0,useCases:["Shipping containers","Outer packaging"],standard:"ISO/IEC 16390"},{id:"msi",name:"MSI (Modified Plessey)",category:"linear",description:"Numeric barcode used in inventory management.",charset:"0-9",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Retail shelves","Inventory"],standard:"Proprietary"},{id:"pharmacode",name:"Pharmacode",category:"linear",description:"Pharmaceutical packaging identification.",charset:"3-131070 (numeric value)",minLength:1,maxLength:6,fixedLength:null,hasCheckDigit:!1,useCases:["Pharmaceutical packaging","Drug identification"],standard:"Laetus"},{id:"plessey",name:"Plessey",category:"linear",description:"Legacy barcode used in UK libraries.",charset:"0-9, A-F",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Legacy systems"],standard:"Proprietary"},{id:"telepen",name:"Telepen",category:"linear",description:"Full ASCII barcode used in UK libraries.",charset:"Full ASCII",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Inventory"],standard:"AIM"},{id:"qr_code",name:"QR Code",category:"2d",description:"Quick Response code — high capacity 2D barcode.",charset:"Full Unicode",minLength:1,maxLength:7089,fixedLength:null,hasCheckDigit:!0,useCases:["Mobile scanning","URLs","vCards","Payments"],standard:"ISO/IEC 18004",detectorFormat:"qr_code"},{id:"data_matrix",name:"Data Matrix",category:"2d",description:"High-density 2D code for small items.",charset:"Full ASCII",minLength:1,maxLength:2335,fixedLength:null,hasCheckDigit:!0,useCases:["Electronics","PCB marking","Medical devices","Aerospace"],standard:"ISO/IEC 16022",detectorFormat:"data_matrix"},{id:"aztec",name:"Aztec Code",category:"2d",description:"Compact 2D code, no quiet zone required.",charset:"Full ASCII",minLength:1,maxLength:3832,fixedLength:null,hasCheckDigit:!0,useCases:["Transport tickets","Boarding passes","Government IDs"],standard:"ISO/IEC 24778",detectorFormat:"aztec"},{id:"pdf417",name:"PDF417",category:"2d",description:"Stacked linear barcode with high capacity.",charset:"Full ASCII",minLength:1,maxLength:1850,fixedLength:null,hasCheckDigit:!0,useCases:["ID cards","Driver's licenses","Airline boarding","Postage"],standard:"ISO/IEC 15438",detectorFormat:"pdf417"},{id:"maxicode",name:"MaxiCode",category:"2d",description:"Fixed-size 2D code used by UPS.",charset:"Full ASCII",minLength:1,maxLength:93,fixedLength:null,hasCheckDigit:!0,useCases:["UPS shipping","High-speed sorting"],standard:"ISO/IEC 16023"},{id:"gs1_128",name:"GS1-128",category:"gs1",description:"Application Identifier-based supply chain barcode.",charset:"Full ASCII (with AI prefixes)",minLength:1,maxLength:48,fixedLength:null,hasCheckDigit:!0,useCases:["Supply chain","Healthcare","Food traceability"],standard:"ISO/IEC 15417 + GS1 General Specifications"},{id:"gs1_databar",name:"GS1 DataBar",category:"gs1",description:"Compact GS1 barcode for fresh food and coupons.",charset:"0-9 (GTIN-based)",minLength:14,maxLength:74,fixedLength:null,hasCheckDigit:!0,useCases:["Fresh food","Pharmacy","Coupons","Variable weight"],standard:"ISO/IEC 24724"}],ue=(n,f)=>{const p=ae.find(i=>i.id===f);if(!p)return{valid:!1,errors:["Unknown symbology"],warnings:[]};const C=[],h=[],N=p.fixedLength&&p.hasCheckDigit?p.fixedLength-1:p.fixedLength,T=!!p.fixedLength&&p.hasCheckDigit&&n.length===p.fixedLength;switch(p.fixedLength?n.length!==N&&!T&&C.push(p.hasCheckDigit?`Expected ${N} digits, or ${p.fixedLength} with the check digit; got ${n.length}`:`Expected ${p.fixedLength} characters, got ${n.length}`):(n.length<p.minLength&&C.push(`Minimum ${p.minLength} characters required`),n.length>p.maxLength&&C.push(`Maximum ${p.maxLength} characters allowed`)),f){case"ean13":case"ean8":case"ean5":case"ean2":case"upc_a":case"upc_e":case"itf":case"itf14":case"msi":case"pharmacode":/^\d+$/.test(n)||C.push("Only numeric digits allowed");break;case"code128c":/^\d+$/.test(n)||C.push("Only numeric digits allowed"),n.length%2!==0&&h.push("Length should be even for optimal encoding");break;case"code39":case"code93":/^[0-9A-Z\-. $/+%]+$/.test(n.toUpperCase())||C.push("Invalid characters for this symbology");break;case"codabar":/^[0-9\-$:/.+ABCD]+$/.test(n.toUpperCase())||C.push("Invalid characters for Codabar");break;case"plessey":/^[0-9A-F]+$/i.test(n)||C.push("Only hex characters (0-9, A-F) allowed");break}let P;if(p.hasCheckDigit&&C.length===0)switch(f){case"ean13":case"ean8":case"upc_a":case"itf14":{const i=(T?n.slice(0,-1):n).split("").map(Number);let d=0;for(let b=0;b<i.length;b++)d+=i[b]*((i.length-1-b)%2===0?3:1);P=String((10-d%10)%10),T&&n[n.length-1]!==P&&C.push(`Check digit should be ${P}, not ${n[n.length-1]}`);break}}return f==="itf"&&n.length%2!==0&&C.push("ITF requires even number of digits"),{valid:C.length===0,errors:C,warnings:h,checkDigit:P,formattedValue:P&&!T?n+P:n}},Oe={linear:"Linear (1D)","2d":"2D Matrix",postal:"Postal",gs1:"GS1 Standards"},it=e.forwardRef((n,f)=>{const{selected:p,onChange:C,category:h="all",multiSelect:N=!0,showDetails:T=!0,showValidation:P=!1,testValue:i="",readOnly:d=!1,className:b}=n,[L,x]=e.useState([]),[u,y]=e.useState(null),A=p??L,q=e.useMemo(()=>h==="all"?ae:ae.filter(c=>c.category===h),[h]),U=e.useMemo(()=>{const c={};for(const s of q)c[s.category]||(c[s.category]=[]),c[s.category].push(s);return c},[q]),V=e.useCallback(c=>{p||x(c),C==null||C(c)},[p,C]),z=e.useCallback(c=>{N?A.includes(c)||V([...A,c]):V([c])},[A,N,V]),Y=e.useCallback(c=>{V(A.filter(s=>s!==c))},[A,V]),B=e.useCallback(c=>{d||(A.includes(c)?Y(c):z(c))},[A,d,z,Y]),G=e.useCallback(()=>{V(q.map(c=>c.id))},[q,V]),E=e.useCallback(()=>{V([])},[V]),$=e.useCallback(c=>ae.find(s=>s.id===c),[]),R=e.useMemo(()=>!P||!i||!u?null:ue(i,u),[P,i,u]);e.useImperativeHandle(f,()=>({getSelected:()=>A,select:z,deselect:Y,selectAll:G,clearSelection:E,validate:ue,getInfo:$,getAll:()=>ae}),[A,z,Y,G,E,$]);const k=e.useMemo(()=>({symbologies:ae,selected:A,validate:ue,getInfo:$}),[A,$]),S=u?$(u):null,D=["nice-symbology-config",d&&"nice-symbology-config--readonly",b].filter(Boolean).join(" ");return t.jsx(ve.Provider,{value:k,children:t.jsxs("div",{className:D,children:[N&&!d&&t.jsxs("div",{className:"nice-symbology-config__toolbar",children:[t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:G,children:"Select All"}),t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:E,children:"Clear"}),t.jsxs("span",{className:"nice-symbology-config__count",children:[A.length," / ",q.length," selected"]})]}),t.jsxs("div",{className:"nice-symbology-config__content",children:[t.jsx("div",{className:"nice-symbology-config__list",children:Object.entries(U).map(([c,s])=>t.jsxs("div",{className:"nice-symbology-config__group",children:[t.jsx("h3",{className:"nice-symbology-config__group-title",children:Oe[c]||c}),t.jsx("div",{className:"nice-symbology-config__grid",children:s.map(a=>{const r=A.includes(a.id),o=u===a.id;return t.jsxs("div",{className:["nice-symbology-config__item",r&&"nice-symbology-config__item--selected",o&&"nice-symbology-config__item--active"].filter(Boolean).join(" "),onClick:()=>{B(a.id),y(a.id)},role:"option","aria-selected":r,tabIndex:0,onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),B(a.id),y(a.id))},children:[N&&t.jsx("span",{className:`nice-symbology-config__checkbox ${r?"nice-symbology-config__checkbox--checked":""}`,children:r&&t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"0.3em",height:"0.6em",marginBottom:"0.15em",borderRight:"0.12em solid currentColor",borderBottom:"0.12em solid currentColor",transform:"rotate(45deg)"}})}),t.jsxs("div",{className:"nice-symbology-config__item-info",children:[t.jsx("span",{className:"nice-symbology-config__item-name",children:a.name}),t.jsx("span",{className:"nice-symbology-config__item-desc",children:a.fixedLength?`${a.fixedLength} digits`:`${a.minLength}-${a.maxLength} chars`})]})]},a.id)})})]},c))}),T&&S&&t.jsxs("div",{className:"nice-symbology-config__details",children:[t.jsx("h3",{className:"nice-symbology-config__details-title",children:S.name}),t.jsx("p",{className:"nice-symbology-config__details-desc",children:S.description}),t.jsxs("div",{className:"nice-symbology-config__details-props",children:[t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Category"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:Oe[S.category]})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Character Set"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:S.charset})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Length"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:S.fixedLength?`Fixed: ${S.fixedLength}`:`${S.minLength} – ${S.maxLength}`})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Check Digit"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:S.hasCheckDigit?"Yes":"No"})]}),S.standard&&t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Standard"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:S.standard})]})]}),t.jsxs("div",{className:"nice-symbology-config__use-cases",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Use Cases"}),t.jsx("div",{className:"nice-symbology-config__tags",children:S.useCases.map(c=>t.jsx("span",{className:"nice-symbology-config__tag",children:c},c))})]}),P&&R&&t.jsxs("div",{className:"nice-symbology-config__validation",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Validation"}),t.jsxs("div",{className:`nice-symbology-config__validation-result ${R.valid?"nice-symbology-config__validation-result--valid":"nice-symbology-config__validation-result--invalid"}`,children:[t.jsx("span",{children:R.valid?"Valid":"Invalid"}),R.checkDigit&&t.jsxs("span",{children:["Check digit: ",R.checkDigit]})]}),R.errors.map((c,s)=>t.jsx("div",{className:"nice-symbology-config__validation-error",children:c},s)),R.warnings.map((c,s)=>t.jsx("div",{className:"nice-symbology-config__validation-warning",children:c},s))]})]})]})]})})});it.displayName="NiceSymbologyConfig";const jn=({children:n})=>{const f=e.useCallback(C=>ae.find(h=>h.id===C),[]),p={symbologies:ae,selected:[],validate:ue,getInfo:f};return t.jsx(ve.Provider,{value:p,children:n})},ct=e.createContext(null),An=()=>{const n=e.useContext(ct);if(!n)throw new Error("useBackgroundSync must be used within NiceBackgroundSyncProvider");return n},Dn={dbName:"nice-background-sync",storeName:"sync-queue",defaultMaxAttempts:5,retryDelay:1e3,backoffFactor:2,maxRetryDelay:6e4,autoSyncOnConnect:!0,periodicSyncInterval:0},En=()=>`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Ln=n=>new Promise(f=>setTimeout(f,n)),xe=e.forwardRef((n,f)=>{const{config:p,handlers:C,onSyncStart:h,onSyncComplete:N,onTaskSuccess:T,onTaskFailed:P,onOnlineChange:i,children:d}=n,b={...Dn,...p},L=e.useRef(null),x=e.useRef(!1),[u,y]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,pendingCount:0,failedCount:0,syncProgress:0}),A=e.useCallback(async()=>L.current?L.current:new Promise((r,o)=>{const l=indexedDB.open(b.dbName,1);l.onerror=()=>o(l.error),l.onupgradeneeded=()=>{const j=l.result;if(!j.objectStoreNames.contains(b.storeName)){const F=j.createObjectStore(b.storeName,{keyPath:"id"});F.createIndex("tag","tag",{unique:!1}),F.createIndex("status","status",{unique:!1}),F.createIndex("priority","priority",{unique:!1})}},l.onsuccess=()=>{L.current=l.result,r(l.result)}}),[b.dbName,b.storeName]),q=e.useCallback(async(r,o,l)=>{const j=await A(),F={id:En(),tag:r,data:o,status:"pending",createdAt:new Date,attempts:0,maxAttempts:(l==null?void 0:l.maxAttempts)??b.defaultMaxAttempts,priority:(l==null?void 0:l.priority)??0};return new Promise((g,m)=>{const _=j.transaction(b.storeName,"readwrite").objectStore(b.storeName).add(F);_.onerror=()=>m(_.error),_.onsuccess=()=>{y(W=>({...W,pendingCount:W.pendingCount+1})),g(F.id)}})},[A,b.storeName,b.defaultMaxAttempts]),U=e.useCallback(async r=>{const o=await A();return new Promise((l,j)=>{const m=o.transaction(b.storeName,"readwrite").objectStore(b.storeName).delete(r);m.onerror=()=>j(m.error),m.onsuccess=()=>l(!0)})},[A,b.storeName]),V=e.useCallback(async r=>{const o=await A();return new Promise((l,j)=>{const g=o.transaction(b.storeName,"readonly").objectStore(b.storeName),m=r?g.index("tag").getAll(r):g.getAll();m.onerror=()=>j(m.error),m.onsuccess=()=>l(m.result)})},[A,b.storeName]),z=e.useCallback(async r=>(await V(r)).filter(l=>l.status==="pending"),[V]),Y=e.useCallback(async r=>(await V(r)).filter(l=>l.status==="failed"),[V]),B=e.useCallback(async r=>{const o=await A();return new Promise((l,j)=>{const m=o.transaction(b.storeName,"readwrite").objectStore(b.storeName).put(r);m.onerror=()=>j(m.error),m.onsuccess=()=>l()})},[A,b.storeName]),G=e.useCallback(async()=>{const r=await V(),o=r.filter(j=>j.status==="pending").length,l=r.filter(j=>j.status==="failed").length;y(j=>({...j,pendingCount:o,failedCount:l}))},[V]),E=e.useCallback(async r=>{const o=C[r.tag];if(!o)return console.warn(`No handler registered for tag: ${r.tag}`),!1;r.status="syncing",r.lastAttemptAt=new Date,r.attempts++,await B(r);try{return await o.handler(r),r.status="success",await B(r),T==null||T(r),await U(r.id),!0}catch(l){const j=l instanceof Error?l.message:"Unknown error";return r.error=j,r.attempts>=r.maxAttempts?(r.status="failed",P==null||P(r,l instanceof Error?l:new Error(j))):r.status="pending",await B(r),!1}},[C,B,U,T,P]),$=e.useCallback(async r=>{if(u.isSyncing)return{success:0,failed:0};x.current=!1,y(l=>({...l,isSyncing:!0,syncProgress:0,error:void 0})),h==null||h();const o={success:0,failed:0};try{const l=await z(r);l.sort((F,g)=>g.priority-F.priority);const j=l.length;for(let F=0;F<l.length&&!x.current;F++){const g=l[F],m=await E(g);if(m?o.success++:g.attempts>=g.maxAttempts&&o.failed++,!m&&g.attempts<g.maxAttempts){const w=Math.min(b.retryDelay*Math.pow(b.backoffFactor,g.attempts-1),b.maxRetryDelay);await Ln(w)}y(w=>({...w,syncProgress:Math.round((F+1)/j*100)}))}}catch(l){const j=l instanceof Error?l.message:"Sync failed";y(F=>({...F,error:j}))}return await G(),y(l=>({...l,isSyncing:!1,lastSyncAt:new Date,syncProgress:100})),N==null||N(o),o},[u.isSyncing,z,E,b.retryDelay,b.backoffFactor,b.maxRetryDelay,G,h,N]),R=e.useCallback(()=>{x.current=!0},[]),k=e.useCallback(async r=>{const l=(await V()).find(j=>j.id===r);l&&l.status==="failed"&&(l.status="pending",l.attempts=0,l.error=void 0,await B(l),await G())},[V,B,G]),S=e.useCallback(async r=>{const o=await Y(r);for(const l of o)l.status="pending",l.attempts=0,l.error=void 0,await B(l);await G()},[Y,B,G]),D=e.useCallback(async r=>{const o=await A(),l=await V(r);return new Promise((j,F)=>{const g=o.transaction(b.storeName,"readwrite"),m=g.objectStore(b.storeName);g.onerror=()=>F(g.error),g.oncomplete=async()=>{await G(),j()};for(const w of l)m.delete(w.id)})},[A,V,b.storeName,G]),c=e.useCallback(async r=>{const o=await A(),l=await Y(r);return new Promise((j,F)=>{const g=o.transaction(b.storeName,"readwrite"),m=g.objectStore(b.storeName);g.onerror=()=>F(g.error),g.oncomplete=async()=>{await G(),j()};for(const w of l)m.delete(w.id)})},[A,Y,b.storeName,G]),s=e.useCallback(async r=>{if(!("serviceWorker"in navigator))return!1;try{const o=await navigator.serviceWorker.ready;if("sync"in o)return await o.sync.register(r),!0}catch(o){console.warn("Background Sync registration failed:",o)}return!1},[]);e.useEffect(()=>{const r=()=>{y(l=>({...l,isOnline:!0})),i==null||i(!0),b.autoSyncOnConnect&&$()},o=()=>{y(l=>({...l,isOnline:!1})),i==null||i(!1)};return window.addEventListener("online",r),window.addEventListener("offline",o),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",o)}},[b.autoSyncOnConnect,$,i]),e.useEffect(()=>{if(b.periodicSyncInterval<=0)return;const r=setInterval(()=>{u.isOnline&&!u.isSyncing&&$()},b.periodicSyncInterval);return()=>clearInterval(r)},[b.periodicSyncInterval,u.isOnline,u.isSyncing,$]),e.useEffect(()=>{G()},[G]),e.useImperativeHandle(f,()=>({getState:()=>u,addTask:q,removeTask:U,getTasks:V,getPendingTasks:z,getFailedTasks:Y,retryTask:k,retryAllFailed:S,clearTasks:D,clearFailed:c,syncNow:$,cancelSync:R,registerBackgroundSync:s}),[u,q,U,V,z,Y,k,S,D,c,$,R,s]);const a={...u,addTask:q,removeTask:U,getTasks:V,getPendingTasks:z,getFailedTasks:Y,retryTask:k,retryAllFailed:S,clearTasks:D,clearFailed:c,syncNow:$,cancelSync:R};return t.jsx(ct.Provider,{value:a,children:d})});xe.displayName="NiceBackgroundSync";const ot=xe;ot.displayName="NiceBackgroundSyncProvider";const lt=e.createContext(null),ut=()=>{const n=e.useContext(lt);if(!n)throw new Error("useCacheStrategies must be used within NiceCacheStrategiesProvider");return n},Pn={cacheName:"nice-cache-strategies",defaultTTL:300*1e3,maxEntries:500,defaultStrategy:"stale-while-revalidate",networkTimeout:5e3,serveStale:!0,staleThreshold:60*1e3};class Rn{constructor(){ce(this,"dbName","nice-cache-db");ce(this,"storeName","cache-entries");ce(this,"db",null)}async init(){if(!this.db)return new Promise((f,p)=>{const C=indexedDB.open(this.dbName,1);C.onerror=()=>p(C.error),C.onupgradeneeded=()=>{const h=C.result;h.objectStoreNames.contains(this.storeName)||h.createObjectStore(this.storeName,{keyPath:"key"})},C.onsuccess=()=>{this.db=C.result,f()}})}async get(f){if(await this.init(),!!this.db)return new Promise((p,C)=>{const T=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(f);T.onerror=()=>C(T.error),T.onsuccess=()=>{const P=T.result;p(P?P.value:void 0)}})}async set(f,p){if(await this.init(),!!this.db)return new Promise((C,h)=>{const P=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:f,value:p});P.onerror=()=>h(P.error),P.onsuccess=()=>C()})}async delete(f){return await this.init(),this.db?new Promise((p,C)=>{const T=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(f);T.onerror=()=>C(T.error),T.onsuccess=()=>p(!0)}):!1}async keys(){return await this.init(),this.db?new Promise((f,p)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();N.onerror=()=>p(N.error),N.onsuccess=()=>f(N.result)}):[]}async clear(){if(await this.init(),!!this.db)return new Promise((f,p)=>{const N=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();N.onerror=()=>p(N.error),N.onsuccess=()=>f()})}async getAll(){return await this.init(),this.db?new Promise((f,p)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();N.onerror=()=>p(N.error),N.onsuccess=()=>f(N.result)}):[]}}const Ce=e.forwardRef((n,f)=>{const{config:p,routeStrategies:C={},precacheUrls:h=[],onFetch:N,onCacheHit:T,onCacheMiss:P,onNetworkError:i,children:d}=n,b={...Pn,...p},L=e.useRef(new Rn),[x,u]=e.useState({isFetching:!1,totalSize:0,entryCount:0,hits:0,misses:0,strategy:b.defaultStrategy}),y=e.useCallback(c=>{for(const[s,a]of Object.entries(C))if(new RegExp(s).test(c))return a;return x.strategy},[C,x.strategy]),A=e.useCallback(c=>{u(s=>({...s,strategy:c}))},[]),q=e.useCallback(async c=>{const s=await L.current.get(c);if(!s)return;const a=Date.now(),r=s.expiresAt&&s.expiresAt<a,o=s.timestamp+b.staleThreshold<a;if(r&&!b.serveStale){await L.current.delete(c);return}return{data:s.data,timestamp:new Date(s.timestamp),expiresAt:s.expiresAt?new Date(s.expiresAt):void 0,etag:s.etag,key:c,isStale:o||!!r,source:"cache",url:s.url}},[b.staleThreshold,b.serveStale]),U=e.useCallback(async(c,s,a)=>{const r=Date.now(),o={data:s,timestamp:r,expiresAt:a?r+a:r+b.defaultTTL};await L.current.set(c,o);const l=await L.current.keys();if(u(j=>({...j,entryCount:l.length})),l.length>b.maxEntries){const j=await L.current.getAll();j.sort((g,m)=>g.value.timestamp-m.value.timestamp);const F=j.slice(0,j.length-b.maxEntries);for(const g of F)await L.current.delete(g.key)}},[b.defaultTTL,b.maxEntries]),V=e.useCallback(async c=>{const s=await L.current.delete(c),a=await L.current.keys();return u(r=>({...r,entryCount:a.length})),s},[]),z=e.useCallback(async()=>{await L.current.clear(),u(c=>({...c,entryCount:0,totalSize:0}))},[]),Y=e.useCallback(async()=>L.current.keys(),[]),B=e.useCallback(async c=>await q(c)!==void 0,[q]),G=e.useCallback(async c=>{const s=await L.current.keys();let a=0;for(const o of s)c.test(o)&&(await L.current.delete(o),a++);const r=await L.current.keys();return u(o=>({...o,entryCount:r.length})),a},[]),E=e.useCallback(async(c,s,a)=>{const r=new AbortController,o=setTimeout(()=>r.abort(),a);try{const l=await fetch(c,{...s,signal:r.signal});return clearTimeout(o),l}catch(l){throw clearTimeout(o),l}},[]),$=e.useCallback(async(c,s={})=>{const{strategy:a=y(c),ttl:r,cacheKey:o=c,forceRefresh:l=!1,timeout:j=b.networkTimeout,...F}=s;u(m=>({...m,isFetching:!0}));const g=async()=>{try{const m=await E(c,F,j);if(!m.ok)throw new Error(`HTTP ${m.status}`);const w=await m.json(),O=m.headers.get("etag")||void 0;await U(o,w,r);const _={data:w,timestamp:new Date,etag:O,key:o,isStale:!1,source:"network",url:c};return u(W=>({...W,isFetching:!1})),N==null||N(_),_}catch(m){throw i==null||i(m instanceof Error?m:new Error(String(m)),c),m}};try{switch(a){case"cache-only":{const m=await q(o);if(m)return u(w=>({...w,isFetching:!1,hits:w.hits+1})),T==null||T(m),m;throw u(w=>({...w,isFetching:!1,misses:w.misses+1})),P==null||P(c),new Error("No cache entry found")}case"network-only":return u(m=>({...m,misses:m.misses+1})),await g();case"cache-first":{if(!l){const m=await q(o);if(m&&!m.isStale)return u(w=>({...w,isFetching:!1,hits:w.hits+1})),T==null||T(m),m}return u(m=>({...m,misses:m.misses+1})),await g()}case"network-first":try{return u(m=>({...m,misses:m.misses+1})),await g()}catch(m){const w=await q(o);if(w)return u(O=>({...O,isFetching:!1,hits:O.hits+1})),T==null||T(w),w;throw m}case"stale-while-revalidate":default:{const m=await q(o);return m&&!l?(u(w=>({...w,hits:w.hits+1})),T==null||T(m),m.isStale&&g().catch(()=>{}),u(w=>({...w,isFetching:!1})),m):(u(w=>({...w,misses:w.misses+1})),await g())}}}catch(m){throw u(w=>({...w,isFetching:!1})),m}},[y,b.networkTimeout,E,q,U,N,T,P,i]),R=e.useCallback(async(c,s)=>(await $(c,s)).data,[$]),k=e.useCallback(async(c,s)=>{await Promise.all(c.map(a=>$(a,{...s,strategy:"network-first"}).catch(()=>{})))},[$]),S=e.useCallback(async()=>{const c=await L.current.getAll();let s=0,a,r;for(const o of c){const l=JSON.stringify(o.value.data).length;s+=l,(!a||o.value.timestamp<a)&&(a=o.value.timestamp),(!r||o.value.timestamp>r)&&(r=o.value.timestamp)}return{size:s,entryCount:c.length,oldestEntry:a?new Date(a):void 0,newestEntry:r?new Date(r):void 0}},[]);e.useEffect(()=>{h.length>0&&k(h)},[h,k]),e.useEffect(()=>{(async()=>{await L.current.init();const s=await S();u(a=>({...a,totalSize:s.size,entryCount:s.entryCount}))})()},[S]),e.useImperativeHandle(f,()=>({getState:()=>x,fetch:$,fetchJSON:R,getFromCache:q,addToCache:U,removeFromCache:V,clearCache:z,getCacheKeys:Y,getCacheStats:S,prefetch:k,isCached:B,invalidateByPattern:G,setStrategy:A,getStrategyForUrl:y}),[x,$,R,q,U,V,z,Y,S,k,B,G,A,y]);const D={...x,fetch:$,fetchJSON:R,getFromCache:q,addToCache:U,removeFromCache:V,clearCache:z,getCacheKeys:Y,prefetch:k,isCached:B,setStrategy:A,getStrategyForUrl:y};return t.jsx(lt.Provider,{value:D,children:d})});Ce.displayName="NiceCacheStrategies";const dt=Ce;dt.displayName="NiceCacheStrategiesProvider";function On(n,f){const p=ut(),[C,h]=e.useState(void 0),[N,T]=e.useState(!1),[P,i]=e.useState(void 0),d=e.useCallback(async()=>{if(n){T(!0),i(void 0);try{const b=await p.fetchJSON(n,f);h(b)}catch(b){i(b instanceof Error?b:new Error(String(b)))}finally{T(!1)}}},[n,f,p]);return e.useEffect(()=>{d()},[d]),{data:C,isLoading:N,error:P,refetch:d}}const ft=e.createContext(null),Tn=()=>{const n=e.useContext(ft);if(!n)throw new Error("useConflictResolution must be used within NiceConflictResolutionProvider");return n},Mn={defaultStrategy:"manual",autoResolve:!1,maxPendingConflicts:100,persistConflicts:!0,storageKey:"nice-conflict-resolution"},Fn=()=>`conflict-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Bn=n=>JSON.stringify(n),$n=(n,f)=>JSON.stringify(n)===JSON.stringify(f),qn=(n,f,p)=>({...n,...f}),ke=e.forwardRef((n,f)=>{const{config:p,handlers:C={},showConflictUI:h=!0,uiPosition:N="modal",autoOpenUI:T=!0,onConflictDetected:P,onConflictResolved:i,onResolutionFailed:d,renderConflictList:b,renderConflictItem:L,children:x}=n,u={...Mn,...p},[y,A]=e.useState([]),[q,U]=e.useState(!1),[V,z]=e.useState(!1),Y=e.useCallback(I=>C[I]||{},[C]),B=e.useCallback(I=>({pending:I.filter(H=>H.status==="pending").length,resolving:I.filter(H=>H.status==="resolving").length,resolved:I.filter(H=>H.status==="resolved").length,failed:I.filter(H=>H.status==="failed").length}),[]),G={conflicts:y,isResolving:q,counts:B(y)},E=e.useCallback(()=>{if(u.persistConflicts)try{const I=localStorage.getItem(u.storageKey);if(I){const M=JSON.parse(I).map(X=>({...X,createdAt:new Date(X.createdAt),resolvedAt:X.resolvedAt?new Date(X.resolvedAt):void 0,clientVersion:{...X.clientVersion,timestamp:new Date(X.clientVersion.timestamp)},serverVersion:{...X.serverVersion,timestamp:new Date(X.serverVersion.timestamp)},baseVersion:X.baseVersion?{...X.baseVersion,timestamp:new Date(X.baseVersion.timestamp)}:void 0}));A(M)}}catch(I){console.warn("Failed to load persisted conflicts:",I)}},[u.persistConflicts,u.storageKey]),$=e.useCallback(I=>{if(u.persistConflicts)try{const H=I.filter(M=>M.status==="pending"||M.status==="failed");localStorage.setItem(u.storageKey,JSON.stringify(H))}catch(H){console.warn("Failed to persist conflicts:",H)}},[u.persistConflicts,u.storageKey]);e.useEffect(()=>{E()},[E]),e.useEffect(()=>{$(y)},[y,$]);const R=e.useCallback((I,H,M,X,v)=>{const J=Y(I),Q=J.compare||$n,K=J.hash||Bn,Z=J.getConflictingFields;if(Q(M.data,X.data)||M.timestamp<X.timestamp&&v&&Q(M.data,v.data))return null;const ee={id:Fn(),entityType:I,entityId:H,clientVersion:{...M,hash:K(M.data)},serverVersion:{...X,hash:K(X.data)},baseVersion:v?{...v,hash:K(v.data)}:void 0,status:"pending",createdAt:new Date,conflictingFields:Z?Z(M.data,X.data):void 0};return k(ee),ee},[Y]),k=e.useCallback(I=>{A(H=>{const M=H.findIndex(v=>v.entityType===I.entityType&&v.entityId===I.entityId);let X;return M>=0?(X=[...H],X[M]=I):X=[...H,I],X.length>u.maxPendingConflicts&&(X=X.slice(-u.maxPendingConflicts)),X}),P==null||P(I),T&&h&&z(!0),u.autoResolve&&u.defaultStrategy!=="manual"&&S(I.id,u.defaultStrategy)},[u.maxPendingConflicts,u.autoResolve,u.defaultStrategy,T,h,P]),S=e.useCallback(async(I,H,M)=>{var Q;const X=y.findIndex(K=>K.id===I);if(X===-1)return;const v=y[X],J=Y(v.entityType);U(!0),A(K=>{const Z=[...K];return Z[X]={...v,status:"resolving"},Z});try{let K;switch(H){case"client-wins":K=v.clientVersion.data;break;case"server-wins":K=v.serverVersion.data;break;case"latest-wins":K=v.clientVersion.timestamp>v.serverVersion.timestamp?v.clientVersion.data:v.serverVersion.data;break;case"merge":{K=await(J.merge||qn)(v.clientVersion.data,v.serverVersion.data,(Q=v.baseVersion)==null?void 0:Q.data);break}case"manual":if(M===void 0)throw new Error("Manual resolution requires merged data");K=M;break}const Z={...v,status:"resolved",resolvedVersion:{data:K,timestamp:new Date,source:H==="client-wins"?"client":"server"},resolvedWith:H,resolvedAt:new Date};A(ee=>{const te=[...ee];return te[X]=Z,te}),i==null||i(Z)}catch(K){const Z=K instanceof Error?K.message:"Resolution failed";A(ee=>{const te=[...ee];return te[X]={...v,status:"failed",error:Z},te}),d==null||d(v,K instanceof Error?K:new Error(Z))}finally{U(!1)}},[y,Y,i,d]),D=e.useCallback(async I=>{const H=y.filter(M=>M.status==="pending");for(const M of H)await S(M.id,I)},[y,S]),c=e.useCallback(I=>y.find(H=>H.id===I),[y]),s=e.useCallback((I,H)=>y.filter(M=>M.entityType===I&&(H===void 0||M.entityId===H)),[y]),a=e.useCallback(()=>y.filter(I=>I.status==="pending"),[y]),r=e.useCallback(I=>{A(H=>H.filter(M=>M.id!==I))},[]),o=e.useCallback(()=>{A(I=>I.filter(H=>H.status!=="resolved"))},[]),l=e.useCallback(()=>{A([])},[]),j=e.useCallback(()=>z(!0),[]),F=e.useCallback(()=>z(!1),[]);e.useImperativeHandle(f,()=>({getState:()=>G,detectConflict:R,addConflict:k,resolveConflict:S,resolveAll:D,getConflict:c,getConflictsByEntity:s,getPendingConflicts:a,dismissConflict:r,clearResolved:o,clearAll:l,openUI:j,closeUI:F}),[G,R,k,S,D,c,s,a,r,o,l,j,F]);const g={...G,detectConflict:R,addConflict:k,resolveConflict:S,resolveAll:D,getConflict:c,getConflictsByEntity:s,getPendingConflicts:a,dismissConflict:r,clearResolved:o,clearAll:l},m=a(),w=(I,H,M)=>{S(I,H,M)},O=I=>{r(I)},_=I=>L?L({conflict:I,onResolve:(H,M)=>w(I.id,H,M),onDismiss:()=>O(I.id)}):t.jsxs("div",{className:"nice-conflict-item",children:[t.jsxs("div",{className:"nice-conflict-item__header",children:[t.jsx("span",{className:"nice-conflict-item__type",children:I.entityType}),t.jsxs("span",{className:"nice-conflict-item__id",children:["ID: ",I.entityId]})]}),t.jsxs("div",{className:"nice-conflict-item__versions",children:[t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--client",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:"Your changes"}),t.jsx("span",{className:"nice-conflict-item__version-time",children:I.clientVersion.timestamp.toLocaleString()})]}),t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--server",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:"Server version"}),t.jsx("span",{className:"nice-conflict-item__version-time",children:I.serverVersion.timestamp.toLocaleString()})]})]}),I.conflictingFields&&I.conflictingFields.length>0&&t.jsxs("div",{className:"nice-conflict-item__fields",children:[t.jsx("span",{children:"Conflicting fields:"}),I.conflictingFields.map(H=>t.jsx("code",{children:H},H))]}),t.jsxs("div",{className:"nice-conflict-item__actions",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>w(I.id,"client-wins"),disabled:q,children:"Keep Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>w(I.id,"server-wins"),disabled:q,children:"Use Server"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--merge",onClick:()=>w(I.id,"merge"),disabled:q,children:"Merge"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--dismiss",onClick:()=>O(I.id),disabled:q,children:"Dismiss"})]})]},I.id),W=()=>{if(!h||!V||m.length===0)return null;if(b)return b({conflicts:m,onResolve:w,onDismiss:O});const I=t.jsxs("div",{className:"nice-conflict-list",children:[t.jsxs("div",{className:"nice-conflict-list__header",children:[t.jsxs("h3",{children:["Sync Conflicts (",m.length,")"]}),t.jsx("button",{className:"nice-conflict-list__close",onClick:F,"aria-label":"Close",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-conflict-list__items",children:m.map(_)}),m.length>1&&t.jsxs("div",{className:"nice-conflict-list__bulk",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>D("client-wins"),disabled:q,children:"Keep All Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>D("server-wins"),disabled:q,children:"Use All Server"})]})]});switch(N){case"modal":return t.jsx("div",{className:"nice-conflict-overlay",children:t.jsx("div",{className:"nice-conflict-modal",children:I})});case"drawer":return t.jsx("div",{className:"nice-conflict-drawer nice-conflict-drawer--open",children:I});case"toast":return t.jsx("div",{className:"nice-conflict-toast",children:I});case"inline":default:return I}};return t.jsxs(ft.Provider,{value:g,children:[x,W()]})});ke.displayName="NiceConflictResolution";const mt=ke;mt.displayName="NiceConflictResolutionProvider";const ht=e.createContext(null),gt=()=>{const n=e.useContext(ht);if(!n)throw new Error("useIndexedDB must be used within NiceIndexedDBProvider");return n};function Un(n){const f=gt(),p=e.useCallback(u=>f.get(n,u),[f,n]),C=e.useCallback(u=>f.getAll(n,u),[f,n]),h=e.useCallback((u,y)=>f.add(n,u,y),[f,n]),N=e.useCallback((u,y)=>f.put(n,u,y),[f,n]),T=e.useCallback(u=>f.delete(n,u),[f,n]),P=e.useCallback(()=>f.clear(n),[f,n]),i=e.useCallback(u=>f.count(n,u),[f,n]),d=e.useCallback(u=>f.query(n,u),[f,n]),b=e.useCallback(u=>f.bulkAdd(n,u),[f,n]),L=e.useCallback(u=>f.bulkPut(n,u),[f,n]),x=e.useCallback(u=>f.bulkDelete(n,u),[f,n]);return{isOpen:f.isOpen,isLoading:f.isLoading,error:f.error,get:p,getAll:C,add:h,put:N,remove:T,clear:P,count:i,query:d,bulkAdd:b,bulkPut:L,bulkDelete:x}}const Se=e.forwardRef((n,f)=>{const{config:p,autoOpen:C=!0,onOpen:h,onError:N,onClose:T,children:P}=n,i=e.useRef(null),[d,b]=e.useState({isOpen:!1,isLoading:!1,storeNames:[]}),L=e.useCallback(async()=>{if(i.current)return i.current;if(!("indexedDB"in window))throw new Error("IndexedDB is not supported in this browser");return b(s=>({...s,isLoading:!0,error:void 0})),new Promise((s,a)=>{const r=indexedDB.open(p.dbName,p.version);r.onerror=()=>{var l;const o=new Error(((l=r.error)==null?void 0:l.message)||"Failed to open database");b(j=>({...j,isLoading:!1,error:o.message})),N==null||N(o),a(o)},r.onblocked=()=>{var o;(o=p.onBlocked)==null||o.call(p)},r.onupgradeneeded=o=>{var g;const l=r.result,j=o.oldVersion,F=o.newVersion;for(const m of p.stores)if(!l.objectStoreNames.contains(m.name)){const w=l.createObjectStore(m.name,{keyPath:m.keyPath,autoIncrement:m.autoIncrement});if(m.indexes)for(const O of m.indexes)w.createIndex(O.name,O.keyPath,O.options)}(g=p.onUpgrade)==null||g.call(p,l,j,F)},r.onsuccess=()=>{const o=r.result;i.current=o,o.onclose=()=>{i.current=null,b(l=>({...l,isOpen:!1,db:void 0})),T==null||T()},o.onerror=l=>{var F;const j=l.target;N==null||N(new Error(((F=j.error)==null?void 0:F.message)||"Database error"))},b({db:o,isOpen:!0,isLoading:!1,version:o.version,storeNames:Array.from(o.objectStoreNames)}),h==null||h(o),s(o)}})},[p,h,N,T]),x=e.useCallback(()=>{i.current&&(i.current.close(),i.current=null,b(s=>({...s,isOpen:!1,db:void 0})),T==null||T())},[T]),u=e.useCallback(async()=>(x(),new Promise((s,a)=>{const r=indexedDB.deleteDatabase(p.dbName);r.onerror=()=>{var o;a(new Error(((o=r.error)==null?void 0:o.message)||"Failed to delete database"))},r.onsuccess=()=>{b({isOpen:!1,isLoading:!1,storeNames:[]}),s()}})),[p.dbName,x]),y=e.useCallback(async()=>i.current?i.current:L(),[L]),A=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const g=r.transaction(s,"readonly").objectStore(s).get(a);g.onerror=()=>{var m;return l(new Error((m=g.error)==null?void 0:m.message))},g.onsuccess=()=>o(g.result)})},[y]),q=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const F=r.transaction(s,"readonly").objectStore(s),m=(a!=null&&a.index?F.index(a.index):F).getAll(a==null?void 0:a.range,a==null?void 0:a.limit);m.onerror=()=>{var w;return l(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>{let w=m.result;a!=null&&a.offset&&(w=w.slice(a.offset)),o(w)}})},[y]),U=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const F=r.transaction(s,"readonly").objectStore(s),m=(a!=null&&a.index?F.index(a.index):F).getAllKeys(a==null?void 0:a.range,a==null?void 0:a.limit);m.onerror=()=>{var w;return l(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>o(m.result)})},[y]),V=e.useCallback(async(s,a,r)=>{const o=await y();return new Promise((l,j)=>{const m=o.transaction(s,"readwrite").objectStore(s).add(a,r);m.onerror=()=>{var w;return j(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>l(m.result)})},[y]),z=e.useCallback(async(s,a,r)=>{const o=await y();return new Promise((l,j)=>{const m=o.transaction(s,"readwrite").objectStore(s).put(a,r);m.onerror=()=>{var w;return j(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>l(m.result)})},[y]),Y=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const g=r.transaction(s,"readwrite").objectStore(s).delete(a);g.onerror=()=>{var m;return l(new Error((m=g.error)==null?void 0:m.message))},g.onsuccess=()=>o()})},[y]),B=e.useCallback(async s=>{const a=await y();return new Promise((r,o)=>{const F=a.transaction(s,"readwrite").objectStore(s).clear();F.onerror=()=>{var g;return o(new Error((g=F.error)==null?void 0:g.message))},F.onsuccess=()=>r()})},[y]),G=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const g=r.transaction(s,"readonly").objectStore(s).count(a);g.onerror=()=>{var m;return l(new Error((m=g.error)==null?void 0:m.message))},g.onsuccess=()=>o(g.result)})},[y]),E=e.useCallback(async(s,a)=>{const r=await y(),o=[];return new Promise((l,j)=>{const g=r.transaction(s,"readonly").objectStore(s),w=(a.index?g.index(a.index):g).openCursor(a.range,a.direction);let O=0,_=0;w.onerror=()=>{var W;return j(new Error((W=w.error)==null?void 0:W.message))},w.onsuccess=()=>{const W=w.result;if(W){if(a.offset&&O<a.offset){O++,W.continue();return}if(a.limit&&_>=a.limit){l(o);return}o.push(W.value),_++,W.continue()}else l(o)}})},[y]),$=e.useCallback(async(s,a)=>{const o=(await y()).transaction(s.stores,s.mode||"readwrite");return new Promise((l,j)=>{o.onerror=()=>{var F;return j(new Error((F=o.error)==null?void 0:F.message))},o.onabort=()=>j(new Error("Transaction aborted")),a(o).then(F=>{o.oncomplete=()=>l(F)}).catch(j)})},[y]),R=e.useCallback(async(s,a)=>{const r=await y(),o=[];return new Promise((l,j)=>{const F=r.transaction(s,"readwrite"),g=F.objectStore(s);F.onerror=()=>{var m;return j(new Error((m=F.error)==null?void 0:m.message))},F.oncomplete=()=>l(o);for(const m of a){const w=g.add(m);w.onsuccess=()=>o.push(w.result)}})},[y]),k=e.useCallback(async(s,a)=>{const r=await y(),o=[];return new Promise((l,j)=>{const F=r.transaction(s,"readwrite"),g=F.objectStore(s);F.onerror=()=>{var m;return j(new Error((m=F.error)==null?void 0:m.message))},F.oncomplete=()=>l(o);for(const m of a){const w=g.put(m);w.onsuccess=()=>o.push(w.result)}})},[y]),S=e.useCallback(async(s,a)=>{const r=await y();return new Promise((o,l)=>{const j=r.transaction(s,"readwrite"),F=j.objectStore(s);j.onerror=()=>{var g;return l(new Error((g=j.error)==null?void 0:g.message))},j.oncomplete=()=>o();for(const g of a)F.delete(g)})},[y]),D=e.useCallback(async()=>{const s=await y(),a=[];for(const r of s.objectStoreNames){const l=s.transaction(r,"readonly").objectStore(r);a.push({name:l.name,keyPath:l.keyPath,autoIncrement:l.autoIncrement,indexNames:Array.from(l.indexNames)})}return{name:s.name,version:s.version,stores:a}},[y]);e.useEffect(()=>(C&&L().catch(()=>{}),()=>{x()}),[C,L,x]),e.useImperativeHandle(f,()=>({getState:()=>d,open:L,close:x,deleteDatabase:u,get:A,getAll:q,getAllKeys:U,add:V,put:z,delete:Y,clear:B,count:G,query:E,transaction:$,bulkAdd:R,bulkPut:k,bulkDelete:S,getInfo:D}),[d,L,x,u,A,q,U,V,z,Y,B,G,E,$,R,k,S,D]);const c={...d,open:L,close:x,deleteDatabase:u,get:A,getAll:q,getAllKeys:U,add:V,put:z,delete:Y,clear:B,count:G,query:E,transaction:$,bulkAdd:R,bulkPut:k,bulkDelete:S};return t.jsx(ht.Provider,{value:c,children:P})});Se.displayName="NiceIndexedDB";const pt=Se;pt.displayName="NiceIndexedDBProvider";const yt=e.createContext(null),bt=()=>{const n=e.useContext(yt);if(!n)throw new Error("useOfflineForms must be used within NiceOfflineFormsProvider");return n},Hn={dbName:"nice-offline-forms",autoSaveInterval:5e3,maxDraftsPerForm:50,autoSubmitOnline:!0,retryFailed:!0,maxRetryAttempts:3,retryDelay:5e3},Wn=()=>`draft-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,_e=e.forwardRef((n,f)=>{const{config:p,submitHandlers:C={},onDraftSaved:h,onFormSubmitted:N,onSubmissionFailed:T,onSyncComplete:P,children:i}=n,d={...Hn,...p},b=e.useRef(null),L=e.useRef(C),[x,u]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,draftCounts:{},pendingCount:0,failedCount:0}),y=e.useCallback(async()=>b.current?b.current:new Promise((s,a)=>{const r=indexedDB.open(d.dbName,1);r.onerror=()=>a(r.error),r.onupgradeneeded=()=>{const o=r.result;if(!o.objectStoreNames.contains("drafts")){const l=o.createObjectStore("drafts",{keyPath:"id"});l.createIndex("formId","formId",{unique:!1}),l.createIndex("status","status",{unique:!1})}},r.onsuccess=()=>{b.current=r.result,s(r.result)}}),[d.dbName]),A=e.useCallback(async(s,a,r)=>{const o=await y(),l={id:Wn(),formId:s,data:a,status:"draft",createdAt:new Date,modifiedAt:new Date,attempts:0,version:1,submittedOffline:!1,metadata:r};return new Promise((j,F)=>{const w=o.transaction("drafts","readwrite").objectStore("drafts").add(l);w.onerror=()=>F(w.error),w.onsuccess=()=>{h==null||h(l),D(),j(l.id)}})},[y,h]),q=e.useCallback(async s=>{const a=await y();return new Promise((r,o)=>{const F=a.transaction("drafts","readonly").objectStore("drafts").get(s);F.onerror=()=>o(F.error),F.onsuccess=()=>{const g=F.result;g&&(g.createdAt=new Date(g.createdAt),g.modifiedAt=new Date(g.modifiedAt),g.syncedAt&&(g.syncedAt=new Date(g.syncedAt))),r(g)}})},[y]),U=e.useCallback(async s=>{const a=await y();return new Promise((r,o)=>{const g=a.transaction("drafts","readonly").objectStore("drafts").index("formId").getAll(s);g.onerror=()=>o(g.error),g.onsuccess=()=>{const m=g.result.map(w=>({...w,createdAt:new Date(w.createdAt),modifiedAt:new Date(w.modifiedAt),syncedAt:w.syncedAt?new Date(w.syncedAt):void 0}));r(m)}})},[y]),V=e.useCallback(async()=>{const s=await y();return new Promise((a,r)=>{const j=s.transaction("drafts","readonly").objectStore("drafts").getAll();j.onerror=()=>r(j.error),j.onsuccess=()=>{const F=j.result.filter(g=>g.status==="pending"||g.status==="failed").map(g=>({...g,createdAt:new Date(g.createdAt),modifiedAt:new Date(g.modifiedAt),syncedAt:g.syncedAt?new Date(g.syncedAt):void 0}));a(F)}})},[y]),z=e.useCallback(async(s,a)=>{const r=await q(s);if(!r)return;const o=await y(),l={...r,data:{...r.data,...a},modifiedAt:new Date,version:r.version+1};return new Promise((j,F)=>{const w=o.transaction("drafts","readwrite").objectStore("drafts").put(l);w.onerror=()=>F(w.error),w.onsuccess=()=>{h==null||h(l),j()}})},[y,q,h]),Y=e.useCallback(async(s,a,r)=>{const o=await q(s);if(!o)return;const l=await y(),j={...o,status:a,error:r,attempts:a==="syncing"?o.attempts+1:o.attempts,syncedAt:a==="synced"?new Date:o.syncedAt};return new Promise((F,g)=>{const O=l.transaction("drafts","readwrite").objectStore("drafts").put(j);O.onerror=()=>g(O.error),O.onsuccess=()=>{D(),F()}})},[y,q]),B=e.useCallback(async s=>{const a=await y();return new Promise((r,o)=>{const F=a.transaction("drafts","readwrite").objectStore("drafts").delete(s);F.onerror=()=>o(F.error),F.onsuccess=()=>{D(),r()}})},[y]),G=e.useCallback(async s=>{const a=await U(s),r=await y();return new Promise((o,l)=>{const j=r.transaction("drafts","readwrite"),F=j.objectStore("drafts");j.onerror=()=>l(j.error),j.oncomplete=()=>{D(),o()};for(const g of a)F.delete(g.id)})},[y,U]),E=e.useCallback(async s=>{const a=await q(s);if(!a)throw new Error("Draft not found");const r=L.current[a.formId];if(!r)throw new Error(`No handler registered for form: ${a.formId}`);if(!x.isOnline){await Y(s,"pending");return}await Y(s,"syncing"),u(o=>({...o,isSyncing:!0}));try{await r(a.data,a),await Y(s,"synced"),N==null||N(a),await B(s)}catch(o){const l=o instanceof Error?o.message:"Submission failed";await Y(s,"failed",l),T==null||T(a,o instanceof Error?o:new Error(l))}finally{u(o=>({...o,isSyncing:!1}))}},[q,x.isOnline,Y,B,N,T]),$=e.useCallback(async(s,a)=>{const r=await A(s,a);await Y(r,"pending"),await E(r)},[A,Y,E]),R=e.useCallback(async()=>{const s=await V(),a={synced:0,failed:0};u(r=>({...r,isSyncing:!0}));for(const r of s)if(!(r.status==="failed"&&r.attempts>=d.maxRetryAttempts))try{await E(r.id),a.synced++}catch{a.failed++}return u(r=>({...r,isSyncing:!1,lastSyncAt:new Date})),P==null||P(a),a},[V,E,d.maxRetryAttempts,P]),k=e.useCallback(async()=>{const a=(await V()).filter(r=>r.status==="failed");for(const r of a)r.attempts<d.maxRetryAttempts&&await Y(r.id,"pending");await R()},[V,d.maxRetryAttempts,Y,R]),S=e.useCallback((s,a)=>{L.current[s]=a},[]),D=e.useCallback(async()=>{try{const o=(await y()).transaction("drafts","readonly").objectStore("drafts").getAll();o.onsuccess=()=>{const l=o.result,j={};for(const m of l)j[m.formId]=(j[m.formId]||0)+1;const F=l.filter(m=>m.status==="pending").length,g=l.filter(m=>m.status==="failed").length;u(m=>({...m,draftCounts:j,pendingCount:F,failedCount:g}))}}catch{}},[y]);e.useEffect(()=>{const s=()=>{u(r=>({...r,isOnline:!0})),d.autoSubmitOnline&&R()},a=()=>{u(r=>({...r,isOnline:!1}))};return window.addEventListener("online",s),window.addEventListener("offline",a),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",a)}},[d.autoSubmitOnline,R]),e.useEffect(()=>{y().then(()=>D())},[y,D]),e.useImperativeHandle(f,()=>({getState:()=>x,saveDraft:A,getDraft:q,getDrafts:U,getPendingDrafts:V,updateDraft:z,deleteDraft:B,submitDraft:E,submitForm:$,syncPending:R,retryFailed:k,clearDrafts:G,registerHandler:S}),[x,A,q,U,V,z,B,E,$,R,k,G,S]);const c={...x,saveDraft:A,getDraft:q,getDrafts:U,getPendingDrafts:V,updateDraft:z,deleteDraft:B,submitDraft:E,submitForm:$,syncPending:R,retryFailed:k,clearDrafts:G,registerHandler:S};return t.jsx(yt.Provider,{value:c,children:i})});_e.displayName="NiceOfflineForms";const wt=_e;wt.displayName="NiceOfflineFormsProvider";function Vn(n){const{formId:f,initialData:p={},autoSave:C=!0,autoSaveInterval:h=5e3,onSubmit:N}=n,T=bt(),[P,i]=e.useState(p),[d,b]=e.useState(),[L,x]=e.useState(!1),[u,y]=e.useState();e.useEffect(()=>{T.registerHandler(f,N)},[T,f,N]),e.useEffect(()=>{if(!C)return;const z=setInterval(async()=>{if(Object.keys(P).length>0)if(d)await T.updateDraft(d,P);else{const Y=await T.saveDraft(f,P);b(Y)}},h);return()=>clearInterval(z)},[C,h,P,d,f,T]);const A=e.useCallback(z=>{const{name:Y,value:B,type:G}=z.target;i(E=>({...E,[Y]:G==="checkbox"?z.target.checked:B}))},[]),q=e.useCallback(async z=>{z==null||z.preventDefault(),x(!0),y(void 0);try{await T.submitForm(f,P),i(p),b(void 0)}catch(Y){y(Y instanceof Error?Y.message:"Submission failed")}finally{x(!1)}},[T,f,P,p]),U=e.useCallback(()=>{i(p),y(void 0),d&&(T.deleteDraft(d),b(void 0))},[p,d,T]),V=e.useCallback(async z=>{const Y=await T.getDraft(z);Y&&(i(Y.data),b(z))},[T]);return{data:P,setData:i,draftId:d,isSubmitting:L,error:u,isOnline:T.isOnline,isSyncing:T.isSyncing,pendingCount:T.pendingCount,handleChange:A,handleSubmit:q,reset:U,loadDraft:V}}const de=()=>{const n=navigator;return n.connection?{type:n.connection.type,effectiveType:n.connection.effectiveType,downlink:n.connection.downlink,rtt:n.connection.rtt,saveData:n.connection.saveData}:{}},fe=n=>{if(!n.effectiveType)return n.downlink?Math.min(100,n.downlink*10):50;switch(n.effectiveType){case"4g":return 100;case"3g":return 75;case"2g":return 50;case"slow-2g":return 25;default:return 50}},vt=e.forwardRef((n,f)=>{const{mode:p="banner",position:C="top",showWhenOnline:h=!1,autoHideOnlineDelay:N=3e3,showSlowConnectionWarning:T=!0,slowConnectionThreshold:P=1,showReconnecting:i=!0,reconnectCheckInterval:d=5e3,offlineMessage:b="You're offline",onlineMessage:L="Back online",slowConnectionMessage:x="Slow connection",reconnectingMessage:u="Reconnecting...",showDetails:y=!1,animated:A=!0,pulseWhenOffline:q=!0,offlineIcon:U,onlineIcon:V,slowIcon:z,renderContent:Y,onStatusChange:B,onReconnect:G,className:E,style:$}=n,[R,k]=e.useState(()=>{const v=de();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...v,quality:fe(v)}}),[S,D]=e.useState(!R.isOnline||h),[c,s]=e.useState(!1),[a,r]=e.useState(null),o=e.useCallback(()=>{const v=de(),J=navigator.onLine;k(Q=>{const K={isOnline:J,...v,quality:J?fe(v):0,lastOnlineAt:J?new Date:Q.lastOnlineAt,offlineDuration:!J&&a?Date.now()-a.getTime():void 0};return(Q.isOnline!==K.isOnline||Q.quality!==K.quality)&&(B==null||B(K)),K})},[a,B]),l=e.useCallback(async()=>{try{return(await fetch("/favicon.ico",{method:"HEAD",cache:"no-store"})).ok}catch{return!1}},[]);e.useEffect(()=>{const v=()=>{s(!1),r(null),o(),D(!0),G==null||G(),N>0&&setTimeout(()=>{D(h)},N)},J=()=>{r(new Date),o(),D(!0),s(i)};window.addEventListener("online",v),window.addEventListener("offline",J);const Q=navigator;return Q.connection&&Q.connection.addEventListener("change",o),()=>{window.removeEventListener("online",v),window.removeEventListener("offline",J),Q.connection&&Q.connection.removeEventListener("change",o)}},[o,N,h,i,G]),e.useEffect(()=>{if(!c||R.isOnline)return;const v=setInterval(async()=>{await l()&&window.dispatchEvent(new Event("online"))},d);return()=>clearInterval(v)},[c,R.isOnline,d,l]),e.useEffect(()=>{if(R.isOnline||!a)return;const v=setInterval(()=>{k(J=>({...J,offlineDuration:Date.now()-a.getTime()}))},1e3);return()=>clearInterval(v)},[R.isOnline,a]),e.useImperativeHandle(f,()=>({getConnectionInfo:()=>R,checkConnection:l,show:()=>D(!0),hide:()=>D(!1),toggle:()=>D(v=>!v)}),[R,l]);const j=R.isOnline&&T&&R.downlink!==void 0&&R.downlink<P,g=R.isOnline?j?"slow":"online":c?"reconnecting":"offline",m=()=>{switch(g){case"offline":return b;case"reconnecting":return u;case"slow":return x;case"online":return L}},w=v=>({display:"inline-block",width:10,height:10,borderRadius:"50%",background:v}),O=()=>{switch(g){case"offline":case"reconnecting":return U||t.jsx("span",{style:w("var(--nice-color-error, #ef4444)")});case"slow":return z||t.jsx("span",{style:w("var(--nice-color-warning, #f59e0b)")});case"online":return V||t.jsx("span",{style:w("var(--nice-color-success, #22c55e)")})}},_=v=>{const J=Math.floor(v/1e3);if(J<60)return`${J}s`;const Q=Math.floor(J/60);return Q<60?`${Q}m ${J%60}s`:`${Math.floor(Q/60)}h ${Q%60}m`};if(!S||R.isOnline&&!h&&!j)return null;const W=["nice-offline-indicator",`nice-offline-indicator--${p}`,`nice-offline-indicator--${C}`,`nice-offline-indicator--${g}`,A&&"nice-offline-indicator--animated",q&&g==="offline"&&"nice-offline-indicator--pulse",E].filter(Boolean).join(" ");if(Y)return t.jsx("div",{className:W,style:$,children:Y(R)});const I=()=>t.jsx("span",{className:"nice-offline-indicator__icon",children:O()}),H=()=>t.jsx("span",{className:"nice-offline-indicator__message",children:m()}),M=()=>y?t.jsxs("div",{className:"nice-offline-indicator__details",children:[R.offlineDuration!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__duration",children:["Offline for ",_(R.offlineDuration)]}),R.effectiveType&&t.jsx("span",{className:"nice-offline-indicator__type",children:R.effectiveType.toUpperCase()}),R.downlink!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__speed",children:[R.downlink.toFixed(1)," Mbps"]}),R.rtt!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__latency",children:[R.rtt,"ms"]})]}):null,X=()=>!y||!R.isOnline?null:t.jsx("div",{className:"nice-offline-indicator__quality",children:t.jsx("div",{className:"nice-offline-indicator__quality-bar",style:{width:`${R.quality}%`,backgroundColor:R.quality>=75?"var(--nice-color-success, #22c55e)":R.quality>=50?"var(--nice-color-warning, #eab308)":"var(--nice-color-error, #ef4444)"}})});switch(p){case"icon-only":return t.jsx("div",{className:W,style:$,title:m(),children:I()});case"minimal":return t.jsxs("div",{className:W,style:$,children:[I(),H()]});case"badge":return t.jsxs("div",{className:W,style:$,children:[t.jsx("div",{className:"nice-offline-indicator__badge-dot"}),t.jsx("span",{className:"nice-offline-indicator__badge-text",children:m()})]});case"toast":return t.jsx("div",{className:W,style:$,children:t.jsxs("div",{className:"nice-offline-indicator__toast",children:[I(),t.jsxs("div",{className:"nice-offline-indicator__toast-content",children:[H(),M()]})]})});case"detailed":return t.jsx("div",{className:W,style:$,children:t.jsxs("div",{className:"nice-offline-indicator__detailed",children:[I(),t.jsxs("div",{className:"nice-offline-indicator__detailed-content",children:[H(),M(),X()]})]})});case"banner":default:return t.jsx("div",{className:W,style:$,children:t.jsxs("div",{className:"nice-offline-indicator__banner",children:[I(),H(),y&&t.jsxs(t.Fragment,{children:[M(),c&&t.jsx("span",{className:"nice-offline-indicator__spinner"})]})]})})}});vt.displayName="NiceOfflineIndicator";function zn(){const[n,f]=e.useState(()=>{const p=de();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...p,quality:fe(p)}});return e.useEffect(()=>{const p=()=>{const h=de();f(N=>({...N,isOnline:navigator.onLine,...h,quality:navigator.onLine?fe(h):0,lastOnlineAt:navigator.onLine?new Date:N.lastOnlineAt}))};window.addEventListener("online",p),window.addEventListener("offline",p);const C=navigator;return C.connection&&C.connection.addEventListener("change",p),()=>{window.removeEventListener("online",p),window.removeEventListener("offline",p),C.connection&&C.connection.removeEventListener("change",p)}},[]),n}const xt=e.createContext(null),Ct=()=>{const n=e.useContext(xt);if(!n)throw new Error("useOfflineMedia must be used within NiceOfflineMediaProvider");return n},Gn={dbName:"nice-offline-media",maxCacheSize:500*1024*1024,maxConcurrentDownloads:3,autoResumeOnReconnect:!0,defaultCacheDuration:10080*60*1e3,autoCleanup:!0,cleanupInterval:3600*1e3},Yn=()=>`media-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Xn=(n,f)=>{var h;const p=((h=n.split(".").pop())==null?void 0:h.toLowerCase())||"",C=(f==null?void 0:f.toLowerCase())||"";return C.startsWith("image/")||["jpg","jpeg","png","gif","webp","svg"].includes(p)?"image":C.startsWith("video/")||["mp4","webm","ogg","mov","avi"].includes(p)?"video":C.startsWith("audio/")||["mp3","wav","ogg","flac","m4a"].includes(p)?"audio":["pdf","doc","docx","xls","xlsx","ppt","pptx"].includes(p)?"document":"other"},Kn=n=>{try{return new URL(n).pathname.split("/").pop()||"unknown"}catch{return n.split("/").pop()||"unknown"}},Ne=e.forwardRef((n,f)=>{const{config:p,onDownloadStart:C,onDownloadProgress:h,onDownloadComplete:N,onDownloadFailed:T,onMediaRemoved:P,children:i}=n,d={...Gn,...p},b=e.useRef(null),L=e.useRef(new Map),x=e.useRef(new Map),[u,y]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,activeDownloads:0,queuedDownloads:0,cachedCount:0,totalCacheSize:0,isDownloading:!1}),A=e.useCallback(async()=>b.current?b.current:new Promise((O,_)=>{const W=indexedDB.open(d.dbName,1);W.onerror=()=>_(W.error),W.onupgradeneeded=()=>{const I=W.result;if(!I.objectStoreNames.contains("media")){const H=I.createObjectStore("media",{keyPath:"id"});H.createIndex("url","url",{unique:!0}),H.createIndex("type","type",{unique:!1}),H.createIndex("status","status",{unique:!1})}I.objectStoreNames.contains("blobs")||I.createObjectStore("blobs",{keyPath:"id"})},W.onsuccess=()=>{b.current=W.result,O(W.result)}}),[d.dbName]),q=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const X=_.transaction("media","readwrite").objectStore("media").put(O);X.onerror=()=>I(X.error),X.onsuccess=()=>W()})},[A]),U=e.useCallback(async(O,_)=>{const W=await A();return new Promise((I,H)=>{const v=W.transaction("blobs","readwrite").objectStore("blobs").put({id:O,blob:_});v.onerror=()=>H(v.error),v.onsuccess=()=>I()})},[A]),V=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const X=_.transaction("blobs","readonly").objectStore("blobs").get(O);X.onerror=()=>I(X.error),X.onsuccess=()=>{var v;return W((v=X.result)==null?void 0:v.blob)}})},[A]),z=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const X=_.transaction("media","readonly").objectStore("media").get(O);X.onerror=()=>I(X.error),X.onsuccess=()=>{const v=X.result;v&&(v.cachedAt=v.cachedAt?new Date(v.cachedAt):void 0,v.expiresAt=v.expiresAt?new Date(v.expiresAt):void 0),W(v)}})},[A]),Y=e.useCallback(async()=>{const O=await A();return new Promise((_,W)=>{const M=O.transaction("media","readonly").objectStore("media").getAll();M.onerror=()=>W(M.error),M.onsuccess=()=>{_(M.result.map(X=>({...X,cachedAt:X.cachedAt?new Date(X.cachedAt):void 0,expiresAt:X.expiresAt?new Date(X.expiresAt):void 0})))}})},[A]),B=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const v=_.transaction("media","readonly").objectStore("media").index("type").getAll(O);v.onerror=()=>I(v.error),v.onsuccess=()=>W(v.result)})},[A]),G=e.useCallback(async O=>(await Y()).filter(W=>{var I;return(I=W.tags)==null?void 0:I.includes(O)}),[Y]),E=e.useCallback(async O=>{const _=await A();return new Promise((W,I)=>{const v=_.transaction("media","readonly").objectStore("media").index("url").get(O);v.onerror=()=>I(v.error),v.onsuccess=()=>W(v.result)})},[A]),$=e.useCallback(async O=>{const _=await E(O);return(_==null?void 0:_.status)==="completed"},[E]),R=e.useCallback(async O=>{const _=x.current.get(O);if(_)return _;const W=await V(O);if(!W)return;const I=URL.createObjectURL(W);return x.current.set(O,I),I},[V]),k=e.useCallback(async(O,_)=>{var X;const W=await E(O);if((W==null?void 0:W.status)==="completed")return W.id;const I=new AbortController,H=(W==null?void 0:W.id)||Yn(),M={id:H,url:O,type:(_==null?void 0:_.type)||"other",name:(_==null?void 0:_.name)||Kn(O),mimeType:"",size:0,status:"queued",progress:0,downloadedBytes:0,metadata:_==null?void 0:_.metadata,tags:_==null?void 0:_.tags,priority:_==null?void 0:_.priority};L.current.set(H,I),await q(M),C==null||C(M),y(v=>({...v,queuedDownloads:v.queuedDownloads+1,isDownloading:!0}));try{M.status="downloading",await q(M),y(re=>({...re,activeDownloads:re.activeDownloads+1,queuedDownloads:re.queuedDownloads-1}));const v=await fetch(O,{signal:I.signal,headers:_==null?void 0:_.headers});if(!v.ok)throw new Error(`HTTP ${v.status}`);const J=v.headers.get("content-length"),Q=v.headers.get("content-type")||"",K=J?parseInt(J,10):0;M.size=K,M.mimeType=Q,M.type=(_==null?void 0:_.type)||Xn(O,Q);const Z=(X=v.body)==null?void 0:X.getReader();if(!Z)throw new Error("No response body");const ee=[];let te=0;for(;;){const{done:re,value:ie}=await Z.read();if(re)break;ee.push(ie),te+=ie.length,M.downloadedBytes=te,M.progress=K>0?Math.round(te/K*100):0,await q(M),h==null||h(M)}const ne=new Blob(ee,{type:Q});return await U(H,ne),M.status="completed",M.progress=100,M.size=ne.size,M.cachedAt=new Date,M.expiresAt=_!=null&&_.cacheDuration?new Date(Date.now()+_.cacheDuration):new Date(Date.now()+d.defaultCacheDuration),await q(M),N==null||N(M),H}catch(v){throw v.name==="AbortError"?M.status="cancelled":(M.status="failed",M.error=v instanceof Error?v.message:"Download failed",T==null||T(M,v instanceof Error?v:new Error(String(v)))),await q(M),v}finally{L.current.delete(H),y(v=>({...v,activeDownloads:Math.max(0,v.activeDownloads-1),isDownloading:v.activeDownloads>1})),await m()}},[E,q,U,d.defaultCacheDuration,C,h,N,T]),S=e.useCallback(async O=>{const _=[];for(let W=0;W<O.length;W+=d.maxConcurrentDownloads){const I=O.slice(W,W+d.maxConcurrentDownloads),H=await Promise.allSettled(I.map(M=>k(M.url,M.options)));for(const M of H)M.status==="fulfilled"&&_.push(M.value)}return _},[k,d.maxConcurrentDownloads]),D=e.useCallback(O=>{const _=L.current.get(O);_&&_.abort()},[]),c=e.useCallback(async O=>{const _=await z(O);_&&(_.status==="paused"||_.status==="failed")&&await k(_.url,{type:_.type,name:_.name,metadata:_.metadata,tags:_.tags})},[z,k]),s=e.useCallback(O=>{D(O)},[D]),a=e.useCallback(()=>{for(const[O]of L.current)D(O)},[D]),r=e.useCallback(async()=>{const _=(await Y()).filter(W=>W.status==="paused"||W.status==="failed");await S(_.map(W=>({url:W.url})))},[Y,S]),o=e.useCallback(async O=>{const _=await A(),W=x.current.get(O);W&&(URL.revokeObjectURL(W),x.current.delete(O)),await new Promise((I,H)=>{const M=_.transaction(["media","blobs"],"readwrite");M.objectStore("media").delete(O),M.objectStore("blobs").delete(O),M.onerror=()=>H(M.error),M.oncomplete=()=>I()}),P==null||P(O),await m()},[A,P]),l=e.useCallback(async()=>{const O=await A();for(const[,_]of x.current)URL.revokeObjectURL(_);x.current.clear(),await new Promise((_,W)=>{const I=O.transaction(["media","blobs"],"readwrite");I.objectStore("media").clear(),I.objectStore("blobs").clear(),I.onerror=()=>W(I.error),I.oncomplete=()=>_()}),await m()},[A]),j=e.useCallback(async()=>{const O=await Y(),_=Date.now();let W=0;for(const I of O)I.expiresAt&&I.expiresAt.getTime()<_&&(await o(I.id),W++);return W},[Y,o]),F=e.useCallback(async()=>{const _=(await Y()).filter(H=>H.status==="completed"),W={image:{count:0,size:0},video:{count:0,size:0},audio:{count:0,size:0},document:{count:0,size:0},other:{count:0,size:0}};let I=0;for(const H of _)I+=H.size,W[H.type].count++,W[H.type].size+=H.size;return{totalSize:I,itemCount:_.length,byType:W}},[Y]),g=e.useCallback(async O=>{await S(O.map(_=>({url:_,options:{priority:-1}})))},[S]),m=e.useCallback(async()=>{const O=await F();y(_=>({..._,cachedCount:O.itemCount,totalCacheSize:O.totalSize}))},[F]);e.useEffect(()=>{const O=()=>{y(W=>({...W,isOnline:!0})),d.autoResumeOnReconnect&&r()},_=()=>{y(W=>({...W,isOnline:!1})),a()};return window.addEventListener("online",O),window.addEventListener("offline",_),()=>{window.removeEventListener("online",O),window.removeEventListener("offline",_)}},[d.autoResumeOnReconnect,r,a]),e.useEffect(()=>{if(!d.autoCleanup)return;const O=setInterval(()=>{j()},d.cleanupInterval);return()=>clearInterval(O)},[d.autoCleanup,d.cleanupInterval,j]),e.useEffect(()=>{A().then(()=>m());const O=x.current;return()=>{for(const[,_]of O)URL.revokeObjectURL(_)}},[A,m]),e.useImperativeHandle(f,()=>({getState:()=>u,download:k,downloadMultiple:S,getCachedMedia:z,getAllCachedMedia:Y,getMediaByType:B,getMediaByTag:G,getBlobUrl:R,isCached:$,pauseDownload:D,resumeDownload:c,cancelDownload:s,pauseAll:a,resumeAll:r,removeMedia:o,clearCache:l,clearExpired:j,getCacheStats:F,preload:g}),[u,k,S,z,Y,B,G,R,$,D,c,s,a,r,o,l,j,F,g]);const w={...u,download:k,downloadMultiple:S,getCachedMedia:z,getAllCachedMedia:Y,getMediaByType:B,getMediaByTag:G,getBlobUrl:R,isCached:$,pauseDownload:D,resumeDownload:c,cancelDownload:s,removeMedia:o,clearCache:l,preload:g};return t.jsx(xt.Provider,{value:w,children:i})});Ne.displayName="NiceOfflineMedia";const kt=Ne;kt.displayName="NiceOfflineMediaProvider";function Qn(n){const f=Ct(),[p,C]=e.useState(),[h,N]=e.useState(),[T,P]=e.useState(!1);return e.useEffect(()=>{n&&(P(!0),Promise.all([f.getCachedMedia(n),f.getBlobUrl(n)]).then(([i,d])=>{C(i),N(d)}).finally(()=>{P(!1)}))},[n,f]),{item:p,blobUrl:h,isLoading:T,isOnline:f.isOnline}}const St=e.createContext(null),Jn=()=>{const n=e.useContext(St);if(!n)throw new Error("useServiceWorker must be used within NiceServiceWorkerProvider");return n},Zn={swPath:"/service-worker.js",scope:"/",updateCheckInterval:6e4,autoUpdate:!1,skipWaiting:!1,reloadOnActivation:!0},Ie=e.forwardRef((n,f)=>{const{config:p,showUpdateNotification:C=!0,showOfflineIndicator:h=!0,renderUpdateNotification:N,renderOfflineIndicator:T,notificationPosition:P="bottom",autoDismissDelay:i=0,onRegistered:d,onUpdateAvailable:b,onActivated:L,onError:x,onOnlineStatusChange:u,children:y,className:A}=n,q={...Zn,...p},{swPath:U,scope:V,updateCheckInterval:z,autoUpdate:Y,reloadOnActivation:B}=q,G=q.skipWaiting,E=e.useMemo(()=>({swPath:U,scope:V,updateCheckInterval:z,autoUpdate:Y,skipWaiting:G,reloadOnActivation:B}),[U,V,z,Y,G,B]),$=e.useRef({onRegistered:d,onUpdateAvailable:b,onActivated:L,onError:x});e.useEffect(()=>{$.current={onRegistered:d,onUpdateAvailable:b,onActivated:L,onError:x}});const[R,k]=e.useState({status:"idle",updateAvailable:!1,waitingWorker:!1,cachedUrls:[],caches:[],isOnline:typeof navigator<"u"?navigator.onLine:!0}),[S,D]=e.useState(!1);e.useEffect(()=>{const I=()=>{k(M=>({...M,isOnline:!0})),u==null||u(!0)},H=()=>{k(M=>({...M,isOnline:!1})),u==null||u(!1)};return window.addEventListener("online",I),window.addEventListener("offline",H),()=>{window.removeEventListener("online",I),window.removeEventListener("offline",H)}},[u]);const c=e.useCallback(async()=>{if(!("caches"in window))return[];const I=await caches.keys(),H=[];for(const M of I){const X=await caches.open(M),v=await X.keys();let J=0;for(const Q of v){const K=await X.match(Q);if(K){const Z=await K.clone().blob();J+=Z.size}}H.push({name:M,size:J,itemCount:v.length})}return k(M=>({...M,caches:H})),H},[]),s=e.useCallback(async I=>{if(!("caches"in window))return!1;const H=await caches.delete(I);return await c(),H},[c]),a=e.useCallback(async()=>{if(!("caches"in window))return;const I=await caches.keys();await Promise.all(I.map(H=>caches.delete(H))),k(H=>({...H,caches:[],cachedUrls:[]}))},[]),r=e.useCallback(async(I,H)=>{if(!("caches"in window))return;await(await caches.open(I)).addAll(H),await c()},[c]),o=e.useCallback(async(I,H)=>{if(!("caches"in window))return!1;const X=await(await caches.open(I)).delete(H);return await c(),X},[c]),l=e.useCallback(async I=>"caches"in window?(await(await caches.open(I)).keys()).map(X=>X.url):[],[]),j=e.useCallback(async()=>{var H,M,X,v,J,Q;if(!("serviceWorker"in navigator)){k(K=>({...K,status:"error",error:"Service Worker not supported"}));return}k(K=>({...K,status:"registering"}));const I=!!navigator.serviceWorker.controller;try{const K=await navigator.serviceWorker.register(E.swPath,{scope:E.scope});k(ee=>({...ee,status:"registered",registration:K})),(M=(H=$.current).onRegistered)==null||M.call(H,K),K.addEventListener("updatefound",()=>{const ee=K.installing;ee&&ee.addEventListener("statechange",()=>{var te,ne,re,ie;switch(ee.state){case"installing":k(se=>({...se,status:"installing"}));break;case"installed":navigator.serviceWorker.controller?(k(se=>({...se,status:"installed",updateAvailable:!0,waitingWorker:!0})),D(!0),(ne=(te=$.current).onUpdateAvailable)==null||ne.call(te)):k(se=>({...se,status:"installed"}));break;case"activating":k(se=>({...se,status:"activating"}));break;case"activated":k(se=>({...se,status:"activated",updateAvailable:!1,waitingWorker:!1})),(ie=(re=$.current).onActivated)==null||ie.call(re),E.reloadOnActivation&&I&&window.location.reload();break;case"redundant":k(se=>({...se,status:"redundant"}));break}})}),K.waiting&&(k(ee=>({...ee,updateAvailable:!0,waitingWorker:!0})),D(!0),(v=(X=$.current).onUpdateAvailable)==null||v.call(X));let Z=!1;return navigator.serviceWorker.addEventListener("controllerchange",()=>{!Z&&E.reloadOnActivation&&(Z=!0,window.location.reload())}),await c(),K}catch(K){const Z=K instanceof Error?K.message:"Registration failed";k(ee=>({...ee,status:"error",error:Z})),(Q=(J=$.current).onError)==null||Q.call(J,K instanceof Error?K:new Error(Z));return}},[E,c]),F=e.useCallback(async()=>{if(!R.registration)return!1;const I=await R.registration.unregister();return I&&k(H=>({...H,status:"idle",registration:void 0,updateAvailable:!1,waitingWorker:!1})),I},[R.registration]),g=e.useCallback(async()=>{R.registration&&await R.registration.update()},[R.registration]),m=e.useCallback(()=>{var I;(I=R.registration)!=null&&I.waiting&&R.registration.waiting.postMessage({type:"SKIP_WAITING"})},[R.registration]),w=e.useCallback(()=>{E.skipWaiting&&m(),D(!1)},[E.skipWaiting,m]),O=e.useCallback(()=>{window.location.reload()},[]);e.useEffect(()=>{j()},[j]),e.useEffect(()=>{if(!E.updateCheckInterval||E.updateCheckInterval<=0)return;const I=setInterval(()=>{g()},E.updateCheckInterval);return()=>clearInterval(I)},[E.updateCheckInterval,g]),e.useEffect(()=>{if(!S||i<=0)return;const I=setTimeout(()=>{D(!1)},i);return()=>clearTimeout(I)},[S,i]),e.useImperativeHandle(f,()=>({getState:()=>R,register:j,unregister:F,checkForUpdates:g,applyUpdate:w,skipWaiting:m,getCachesInfo:c,clearCache:s,clearAllCaches:a,addToCache:r,removeFromCache:o,getCachedUrls:l,forceReload:O}),[R,j,F,g,w,m,c,s,a,r,o,l,O]);const _={...R,register:j,unregister:F,checkForUpdates:g,applyUpdate:w,skipWaiting:m,getCachesInfo:c,clearCache:s,clearAllCaches:a,addToCache:r,removeFromCache:o,getCachedUrls:l},W=`nice-sw-notification--${P}`;return t.jsx(St.Provider,{value:_,children:t.jsxs("div",{className:`nice-service-worker ${A||""}`,children:[y,C&&S&&R.updateAvailable&&t.jsx("div",{className:`nice-sw-notification ${W}`,children:N?N({onUpdate:w,onDismiss:()=>D(!1)}):t.jsxs("div",{className:"nice-sw-notification__content",children:[t.jsxs("div",{className:"nice-sw-notification__text",children:[t.jsx("strong",{children:"Update Available"}),t.jsx("span",{children:"A new version is ready to install"})]}),t.jsxs("div",{className:"nice-sw-notification__actions",children:[t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--primary",onClick:w,children:"Update Now"}),t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--secondary",onClick:()=>D(!1),children:"Later"})]})]})}),h&&!R.isOnline&&t.jsx("div",{className:`nice-sw-offline ${W}`,children:T?T({isOnline:R.isOnline}):t.jsx("div",{className:"nice-sw-offline__content",children:t.jsx("span",{children:"You are offline"})})})]})})});Ie.displayName="NiceServiceWorker";const _t=e.forwardRef((n,f)=>t.jsx(Ie,{...n,ref:f}));_t.displayName="NiceServiceWorkerProvider";exports.NiceAutoStart=he;exports.NiceAutoStartProvider=Te;exports.NiceBackgroundSync=xe;exports.NiceBackgroundSyncProvider=ot;exports.NiceBarcodeScanner=tt;exports.NiceBatchScanner=st;exports.NiceBatchScannerProvider=yn;exports.NiceCacheStrategies=Ce;exports.NiceCacheStrategiesProvider=dt;exports.NiceConflictResolution=ke;exports.NiceConflictResolutionProvider=mt;exports.NiceExternalDisplay=ge;exports.NiceExternalDisplayProvider=Be;exports.NiceHardwareBarcodeGenerator=et;exports.NiceHardwareQRGenerator=rt;exports.NiceIndexedDB=Se;exports.NiceIndexedDBProvider=pt;exports.NiceKioskMode=pe;exports.NiceKioskModeProvider=Ue;exports.NiceLowPowerMode=ye;exports.NiceLowPowerModeProvider=We;exports.NiceOfflineForms=_e;exports.NiceOfflineFormsProvider=wt;exports.NiceOfflineIndicator=vt;exports.NiceOfflineMedia=Ne;exports.NiceOfflineMediaProvider=kt;exports.NiceOrientationLock=be;exports.NiceOrientationLockProvider=Ge;exports.NiceQRScanner=at;exports.NiceRemoteManagement=we;exports.NiceRemoteManagementProvider=Xe;exports.NiceScreenBurnPrevention=Ke;exports.NiceScreenSelector=$e;exports.NiceServiceWorker=Ie;exports.NiceServiceWorkerProvider=_t;exports.NiceSymbologyConfig=it;exports.NiceSymbologyProvider=jn;exports.NiceTouchCalibration=Qe;exports.useAutoStart=jt;exports.useBackgroundSync=An;exports.useBatchScanner=fn;exports.useCacheStrategies=ut;exports.useCachedFetch=On;exports.useConflictResolution=Tn;exports.useConnectionStatus=zn;exports.useExternalDisplay=Fe;exports.useIndexedDB=gt;exports.useIndexedDBStore=Un;exports.useKioskMode=Ot;exports.useLowPowerMode=Mt;exports.useOfflineForm=Vn;exports.useOfflineForms=bt;exports.useOfflineMedia=Ct;exports.useOfflineMediaItem=Qn;exports.useOrientationLock=$t;exports.useRemoteManagement=Wt;exports.useServiceWorker=Jn;exports.useSymbology=In;
|
|
11
|
+
</svg>`}catch{return null}},[h,i]),z=e.useCallback((F="qrcode",V="png")=>{const I=document.createElement("a");if(V==="svg"){const U=q();if(!U)return;const D=new Blob([U],{type:"image/svg+xml"});I.href=URL.createObjectURL(D),I.download=`${F}.svg`}else{const U=B();if(!U)return;I.href=U,I.download=`${F}.png`}I.click()},[B,q]),Y=e.useCallback(()=>{j()},[j]);e.useImperativeHandle(f,()=>({toDataURL:B,toSVG:q,download:z,regenerate:Y}),[B,q,z,Y]);const K=["nice-qr-generator",R&&"nice-qr-generator--bordered",A&&"nice-qr-generator--error",G].filter(Boolean).join(" ");return t.jsxs("div",{className:K,children:[t.jsx("canvas",{ref:l,className:"nice-qr-generator__canvas",style:{maxWidth:"100%",height:"auto"}}),A&&t.jsx("div",{className:"nice-qr-generator__error",children:t.jsx("span",{children:A})})]})});it.displayName="NiceQRGenerator";const Sn={continuous:!0,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd",parseDataType:!0,highlightDetected:!0},_n=n=>{var f,h,k;if(/^https?:\/\//i.test(n))return{type:"url",data:{url:n}};if(/^mailto:/i.test(n)){const g=n.match(/^mailto:([^?]+)(?:\?(.*))?$/i);return{type:"email",data:{email:g==null?void 0:g[1],params:g==null?void 0:g[2]}}}if(/^tel:/i.test(n))return{type:"tel",data:{phone:n.replace(/^tel:/i,"")}};if(/^smsto?:/i.test(n)){const g=n.match(/^smsto?:([^:]+)(?::(.*))?$/i);return{type:"sms",data:{phone:g==null?void 0:g[1],message:g==null?void 0:g[2]}}}if(/^geo:/i.test(n)){const g=n.match(/^geo:(-?\d+\.?\d*),(-?\d+\.?\d*)(?:,(-?\d+\.?\d*))?/i);return{type:"geo",data:{latitude:parseFloat((g==null?void 0:g[1])||"0"),longitude:parseFloat((g==null?void 0:g[2])||"0"),altitude:g!=null&&g[3]?parseFloat(g[3]):void 0}}}if(/^BEGIN:VCARD/i.test(n))return{type:"vcard",data:{raw:n}};if(/^BEGIN:VEVENT/i.test(n))return{type:"vevent",data:{raw:n}};if(/^WIFI:/i.test(n)){const g=(f=n.match(/S:([^;]+)/))==null?void 0:f[1],N=(h=n.match(/P:([^;]+)/))==null?void 0:h[1],R=(k=n.match(/T:([^;]+)/))==null?void 0:k[1],G=n.includes("H:true");return{type:"wifi",data:{ssid:g,password:N,type:R,hidden:G}}}return{type:"text"}},Nn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),h=n.createGain();f.connect(h),h.connect(n.destination),f.type="square",f.frequency.value=1200,h.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},80)}catch{}},In=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate([50,30,50])},jn=()=>typeof window<"u"&&"BarcodeDetector"in window,An=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],ct=e.forwardRef((n,f)=>{const{config:h,onScan:k,onError:g,onCameraReady:N,autoStart:R=!1,showScanFrame:G=!0,children:i,className:l}=n,y={...Sn,...h},A=e.useRef(null),v=e.useRef(null),d=e.useRef(null),p=e.useRef(null),j=e.useRef(null),B=e.useRef(null),[q,z]=e.useState(!1),[Y,K]=e.useState(!1),[F,V]=e.useState(null),[I,U]=e.useState(null),[D,P]=e.useState(null),[T,O]=e.useState(y.facingMode),[b,s]=e.useState(!1),[r,a]=e.useState(!1),[c,o]=e.useState(null),S=jn(),E=e.useCallback(async()=>{var Q;if(!A.current)return;const J=An(y.resolution),H={video:{facingMode:T,width:{ideal:J.width},height:{ideal:J.height}},audio:!1};try{const ee=await navigator.mediaDevices.getUserMedia(H);d.current=ee,A.current.srcObject=ee,await A.current.play();const te=ee.getVideoTracks()[0],ne=(Q=te.getCapabilities)==null?void 0:Q.call(te);s(!!(ne!=null&&ne.torch)),K(!0),P(!0),U(null),N==null||N()}catch(ee){const te=ee instanceof Error?ee.message:"Failed to access camera";U(te),P(!1),g==null||g(new Error(te))}},[y.resolution,T,N,g]),m=e.useCallback(()=>{d.current&&(d.current.getTracks().forEach(J=>J.stop()),d.current=null),A.current&&(A.current.srcObject=null),K(!1),a(!1)},[]),w=e.useCallback(async()=>{O(T==="user"?"environment":"user"),q&&m()},[T,q,m]),u=e.useCallback(async()=>{if(!d.current||!b)return;const J=d.current.getVideoTracks()[0],H=!r;try{await J.applyConstraints({advanced:[{torch:H}]}),a(H)}catch{}},[b,r]),C=e.useCallback(async()=>{if(S)try{const J=window.BarcodeDetector;p.current=new J({formats:["qr_code"]})}catch(J){const H=J instanceof Error?J.message:"Failed to initialize QR detector";U(H),g==null||g(new Error(H))}},[S,g]),x=e.useCallback((J,H)=>{const Q={text:J,boundingBox:H.boundingBox?{x:H.boundingBox.x,y:H.boundingBox.y,width:H.boundingBox.width,height:H.boundingBox.height}:void 0,cornerPoints:H.cornerPoints,timestamp:new Date};if(y.parseDataType){const ee=_n(J);Q.dataType=ee.type,Q.parsedData=ee.data}return Q},[y.parseDataType]),W=e.useCallback(async()=>{if(!(!A.current||!p.current||!Y))try{const H=await p.current.detect(A.current);if(H.length>0){const Q=H[0];if(y.continuous&&Q.rawValue===B.current)return;B.current=Q.rawValue;const ee=x(Q.rawValue,Q);y.highlightDetected&&ee.boundingBox&&(o(ee.boundingBox),setTimeout(()=>o(null),500)),y.beepOnScan&&Nn(),y.vibrateOnScan&&In(),V(ee),k==null||k(ee),setTimeout(()=>{B.current=null},1e3)}}catch{}},[Y,y.continuous,y.highlightDetected,y.beepOnScan,y.vibrateOnScan,x,k]),_=e.useCallback(async()=>{z(!0),U(null),await C(),await E()},[C,E]),M=e.useCallback(()=>{z(!1),j.current&&(clearInterval(j.current),j.current=null),m()},[m]),L=e.useCallback(async()=>{q?M():await _()},[q,_,M]),X=e.useCallback(()=>{if(!A.current||!v.current)return null;const J=v.current,H=A.current;J.width=H.videoWidth,J.height=H.videoHeight;const Q=J.getContext("2d");return Q?(Q.drawImage(H,0,0),J.toDataURL("image/png")):null},[]),$=e.useCallback(async J=>!S||!p.current?null:new Promise(H=>{const Q=new Image;Q.onload=async()=>{try{const te=await p.current.detect(Q);if(te.length>0){const ne=x(te[0].rawValue,te[0]);H(ne)}else H(null)}catch{H(null)}},Q.onerror=()=>H(null),Q.src=URL.createObjectURL(J)}),[S,x]);e.useEffect(()=>(q&&Y&&y.continuous&&(j.current=setInterval(W,y.scanInterval)),()=>{j.current&&(clearInterval(j.current),j.current=null)}),[q,Y,y.continuous,y.scanInterval,W]),e.useEffect(()=>(R&&_(),()=>{M()}),[]),e.useEffect(()=>{q&&!Y&&E()},[T,q,Y,E]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:q,isCameraReady:Y,lastResult:F,error:I,isSupported:S,hasPermission:D,torchAvailable:b,torchOn:r}),start:_,stop:M,toggle:L,switchCamera:w,toggleTorch:u,takeSnapshot:X,scanImage:$}),[q,Y,F,I,S,D,b,r,_,M,L,w,u,X,$]);const Z=["nice-qr-scanner",q&&"nice-qr-scanner--scanning",Y&&"nice-qr-scanner--ready",I&&"nice-qr-scanner--error",l].filter(Boolean).join(" ");return t.jsxs("div",{className:Z,children:[t.jsx("video",{ref:A,className:"nice-qr-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:v,className:"nice-qr-scanner__canvas"}),G&&q&&t.jsxs("div",{className:"nice-qr-scanner__frame",children:[t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--br"})]}),c&&A.current&&t.jsx("div",{className:"nice-qr-scanner__bounding-box",style:{left:`${c.x/A.current.videoWidth*100}%`,top:`${c.y/A.current.videoHeight*100}%`,width:`${c.width/A.current.videoWidth*100}%`,height:`${c.height/A.current.videoHeight*100}%`}}),I&&t.jsxs("div",{className:"nice-qr-scanner__error",children:[t.jsx("div",{className:"nice-qr-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-qr-scanner__error-text",children:I}),t.jsx("button",{className:"nice-qr-scanner__error-btn",onClick:()=>_(),children:"Try Again"})]}),!S&&t.jsx("div",{className:"nice-qr-scanner__unsupported",children:t.jsx("p",{children:"QR scanning is not supported in this browser."})}),i&&t.jsx("div",{className:"nice-qr-scanner__overlay",children:i})]})});ct.displayName="NiceQRScanner";const Ce=e.createContext(null),Dn=()=>{const n=e.useContext(Ce);if(!n)throw new Error("useSymbology must be used within NiceSymbologyConfigProvider");return n},ie=[{id:"code128",name:"Code 128",category:"linear",description:"High-density barcode for alphanumeric data. Auto-switches between subsets A/B/C.",charset:"ASCII 0-127",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Shipping labels","Inventory","General purpose"],standard:"ISO/IEC 15417",detectorFormat:"code_128"},{id:"code128a",name:"Code 128A",category:"linear",description:"Code 128 subset A: uppercase + control characters.",charset:"ASCII 0-95 (uppercase, digits, control chars)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Systems with control characters","Legacy integration"],standard:"ISO/IEC 15417"},{id:"code128b",name:"Code 128B",category:"linear",description:"Code 128 subset B: uppercase + lowercase.",charset:"ASCII 32-127 (upper/lowercase, digits, symbols)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Alphanumeric data","Mixed case text"],standard:"ISO/IEC 15417"},{id:"code128c",name:"Code 128C",category:"linear",description:"Code 128 subset C: double-density numeric only.",charset:"0-9 (pairs only)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Long numeric values","Compact encoding"],standard:"ISO/IEC 15417"},{id:"code39",name:"Code 39",category:"linear",description:"Self-checking barcode supporting uppercase and digits.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Military (LOGMARS)","Automotive (AIAG)","Healthcare"],standard:"ISO/IEC 16388",detectorFormat:"code_39"},{id:"code93",name:"Code 93",category:"linear",description:"Compact barcode, denser than Code 39.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Canadian postal","General logistics"],standard:"ANSI/AIM BC5",detectorFormat:"code_93"},{id:"codabar",name:"Codabar",category:"linear",description:"Numeric barcode used in libraries and blood banks.",charset:"0-9, -, $, :, /, ., +, A-D (start/stop)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Blood banks","Libraries","FedEx"],standard:"ANSI/AIM BC3",detectorFormat:"codabar"},{id:"ean13",name:"EAN-13",category:"linear",description:"European Article Numbering — worldwide retail standard.",charset:"0-9",minLength:12,maxLength:12,fixedLength:13,hasCheckDigit:!0,useCases:["Retail worldwide","ISBN","ISSN"],standard:"ISO/IEC 15420",detectorFormat:"ean_13"},{id:"ean8",name:"EAN-8",category:"linear",description:"Compact version of EAN-13 for small products.",charset:"0-9",minLength:7,maxLength:7,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Space-constrained packaging"],standard:"ISO/IEC 15420",detectorFormat:"ean_8"},{id:"ean5",name:"EAN-5 Supplement",category:"linear",description:"5-digit addon for periodicals and books.",charset:"0-9",minLength:5,maxLength:5,fixedLength:5,hasCheckDigit:!0,useCases:["Book pricing","Magazine issues"],standard:"ISO/IEC 15420"},{id:"ean2",name:"EAN-2 Supplement",category:"linear",description:"2-digit addon for periodicals.",charset:"0-9",minLength:2,maxLength:2,fixedLength:2,hasCheckDigit:!1,useCases:["Magazine issue numbers"],standard:"ISO/IEC 15420"},{id:"upc_a",name:"UPC-A",category:"linear",description:"Universal Product Code — North American retail standard.",charset:"0-9",minLength:11,maxLength:11,fixedLength:12,hasCheckDigit:!0,useCases:["US/Canada retail","Point of Sale"],standard:"ISO/IEC 15420",detectorFormat:"upc_a"},{id:"upc_e",name:"UPC-E",category:"linear",description:"Compressed UPC for small packages.",charset:"0-9",minLength:6,maxLength:6,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Compact packaging"],standard:"ISO/IEC 15420",detectorFormat:"upc_e"},{id:"itf",name:"Interleaved 2 of 5",category:"linear",description:"Numeric pairs encoded in interleaved format.",charset:"0-9 (even length)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Warehouse distribution","Packaging"],standard:"ISO/IEC 16390",detectorFormat:"itf"},{id:"itf14",name:"ITF-14",category:"linear",description:"GTIN-14 barcode for shipping containers.",charset:"0-9",minLength:13,maxLength:13,fixedLength:14,hasCheckDigit:!0,useCases:["Shipping containers","Outer packaging"],standard:"ISO/IEC 16390"},{id:"msi",name:"MSI (Modified Plessey)",category:"linear",description:"Numeric barcode used in inventory management.",charset:"0-9",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Retail shelves","Inventory"],standard:"Proprietary"},{id:"pharmacode",name:"Pharmacode",category:"linear",description:"Pharmaceutical packaging identification.",charset:"3-131070 (numeric value)",minLength:1,maxLength:6,fixedLength:null,hasCheckDigit:!1,useCases:["Pharmaceutical packaging","Drug identification"],standard:"Laetus"},{id:"plessey",name:"Plessey",category:"linear",description:"Legacy barcode used in UK libraries.",charset:"0-9, A-F",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Legacy systems"],standard:"Proprietary"},{id:"telepen",name:"Telepen",category:"linear",description:"Full ASCII barcode used in UK libraries.",charset:"Full ASCII",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Inventory"],standard:"AIM"},{id:"qr_code",name:"QR Code",category:"2d",description:"Quick Response code — high capacity 2D barcode.",charset:"Full Unicode",minLength:1,maxLength:7089,fixedLength:null,hasCheckDigit:!0,useCases:["Mobile scanning","URLs","vCards","Payments"],standard:"ISO/IEC 18004",detectorFormat:"qr_code"},{id:"data_matrix",name:"Data Matrix",category:"2d",description:"High-density 2D code for small items.",charset:"Full ASCII",minLength:1,maxLength:2335,fixedLength:null,hasCheckDigit:!0,useCases:["Electronics","PCB marking","Medical devices","Aerospace"],standard:"ISO/IEC 16022",detectorFormat:"data_matrix"},{id:"aztec",name:"Aztec Code",category:"2d",description:"Compact 2D code, no quiet zone required.",charset:"Full ASCII",minLength:1,maxLength:3832,fixedLength:null,hasCheckDigit:!0,useCases:["Transport tickets","Boarding passes","Government IDs"],standard:"ISO/IEC 24778",detectorFormat:"aztec"},{id:"pdf417",name:"PDF417",category:"2d",description:"Stacked linear barcode with high capacity.",charset:"Full ASCII",minLength:1,maxLength:1850,fixedLength:null,hasCheckDigit:!0,useCases:["ID cards","Driver's licenses","Airline boarding","Postage"],standard:"ISO/IEC 15438",detectorFormat:"pdf417"},{id:"maxicode",name:"MaxiCode",category:"2d",description:"Fixed-size 2D code used by UPS.",charset:"Full ASCII",minLength:1,maxLength:93,fixedLength:null,hasCheckDigit:!0,useCases:["UPS shipping","High-speed sorting"],standard:"ISO/IEC 16023"},{id:"gs1_128",name:"GS1-128",category:"gs1",description:"Application Identifier-based supply chain barcode.",charset:"Full ASCII (with AI prefixes)",minLength:1,maxLength:48,fixedLength:null,hasCheckDigit:!0,useCases:["Supply chain","Healthcare","Food traceability"],standard:"ISO/IEC 15417 + GS1 General Specifications"},{id:"gs1_databar",name:"GS1 DataBar",category:"gs1",description:"Compact GS1 barcode for fresh food and coupons.",charset:"0-9 (GTIN-based)",minLength:14,maxLength:74,fixedLength:null,hasCheckDigit:!0,useCases:["Fresh food","Pharmacy","Coupons","Variable weight"],standard:"ISO/IEC 24724"}],de=(n,f)=>{const h=ie.find(i=>i.id===f);if(!h)return{valid:!1,errors:["Unknown symbology"],warnings:[]};const k=[],g=[],N=h.fixedLength&&h.hasCheckDigit?h.fixedLength-1:h.fixedLength,R=!!h.fixedLength&&h.hasCheckDigit&&n.length===h.fixedLength;switch(h.fixedLength?n.length!==N&&!R&&k.push(h.hasCheckDigit?`Expected ${N} digits, or ${h.fixedLength} with the check digit; got ${n.length}`:`Expected ${h.fixedLength} characters, got ${n.length}`):(n.length<h.minLength&&k.push(`Minimum ${h.minLength} characters required`),n.length>h.maxLength&&k.push(`Maximum ${h.maxLength} characters allowed`)),f){case"ean13":case"ean8":case"ean5":case"ean2":case"upc_a":case"upc_e":case"itf":case"itf14":case"msi":case"pharmacode":/^\d+$/.test(n)||k.push("Only numeric digits allowed");break;case"code128c":/^\d+$/.test(n)||k.push("Only numeric digits allowed"),n.length%2!==0&&g.push("Length should be even for optimal encoding");break;case"code39":case"code93":/^[0-9A-Z\-. $/+%]+$/.test(n.toUpperCase())||k.push("Invalid characters for this symbology");break;case"codabar":/^[0-9\-$:/.+ABCD]+$/.test(n.toUpperCase())||k.push("Invalid characters for Codabar");break;case"plessey":/^[0-9A-F]+$/i.test(n)||k.push("Only hex characters (0-9, A-F) allowed");break}let G;if(h.hasCheckDigit&&k.length===0)switch(f){case"ean13":case"ean8":case"upc_a":case"itf14":{const i=(R?n.slice(0,-1):n).split("").map(Number);let l=0;for(let y=0;y<i.length;y++)l+=i[y]*((i.length-1-y)%2===0?3:1);G=String((10-l%10)%10),R&&n[n.length-1]!==G&&k.push(`Check digit should be ${G}, not ${n[n.length-1]}`);break}}return f==="itf"&&n.length%2!==0&&k.push("ITF requires even number of digits"),{valid:k.length===0,errors:k,warnings:g,checkDigit:G,formattedValue:G&&!R?n+G:n}},Me={linear:"Linear (1D)","2d":"2D Matrix",postal:"Postal",gs1:"GS1 Standards"},ot=e.forwardRef((n,f)=>{const{selected:h,onChange:k,category:g="all",multiSelect:N=!0,showDetails:R=!0,showValidation:G=!1,testValue:i="",readOnly:l=!1,className:y}=n,[A,v]=e.useState([]),[d,p]=e.useState(null),j=h??A,B=e.useMemo(()=>g==="all"?ie:ie.filter(b=>b.category===g),[g]),q=e.useMemo(()=>{const b={};for(const s of B)b[s.category]||(b[s.category]=[]),b[s.category].push(s);return b},[B]),z=e.useCallback(b=>{h||v(b),k==null||k(b)},[h,k]),Y=e.useCallback(b=>{N?j.includes(b)||z([...j,b]):z([b])},[j,N,z]),K=e.useCallback(b=>{z(j.filter(s=>s!==b))},[j,z]),F=e.useCallback(b=>{l||(j.includes(b)?K(b):Y(b))},[j,l,Y,K]),V=e.useCallback(()=>{z(B.map(b=>b.id))},[B,z]),I=e.useCallback(()=>{z([])},[z]),U=e.useCallback(b=>ie.find(s=>s.id===b),[]),D=e.useMemo(()=>!G||!i||!d?null:de(i,d),[G,i,d]);e.useImperativeHandle(f,()=>({getSelected:()=>j,select:Y,deselect:K,selectAll:V,clearSelection:I,validate:de,getInfo:U,getAll:()=>ie}),[j,Y,K,V,I,U]);const P=e.useMemo(()=>({symbologies:ie,selected:j,validate:de,getInfo:U}),[j,U]),T=d?U(d):null,O=["nice-symbology-config",l&&"nice-symbology-config--readonly",y].filter(Boolean).join(" ");return t.jsx(Ce.Provider,{value:P,children:t.jsxs("div",{className:O,children:[N&&!l&&t.jsxs("div",{className:"nice-symbology-config__toolbar",children:[t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:V,children:"Select All"}),t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:I,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(q).map(([b,s])=>t.jsxs("div",{className:"nice-symbology-config__group",children:[t.jsx("h3",{className:"nice-symbology-config__group-title",children:Me[b]||b}),t.jsx("div",{className:"nice-symbology-config__grid",children:s.map(r=>{const a=j.includes(r.id),c=d===r.id;return t.jsxs("div",{className:["nice-symbology-config__item",a&&"nice-symbology-config__item--selected",c&&"nice-symbology-config__item--active"].filter(Boolean).join(" "),onClick:()=>{F(r.id),p(r.id)},role:"option","aria-selected":a,tabIndex:0,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),F(r.id),p(r.id))},children:[N&&t.jsx("span",{className:`nice-symbology-config__checkbox ${a?"nice-symbology-config__checkbox--checked":""}`,children:a&&t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"0.3em",height:"0.6em",marginBottom:"0.15em",borderRight:"0.12em solid currentColor",borderBottom:"0.12em solid currentColor",transform:"rotate(45deg)"}})}),t.jsxs("div",{className:"nice-symbology-config__item-info",children:[t.jsx("span",{className:"nice-symbology-config__item-name",children:r.name}),t.jsx("span",{className:"nice-symbology-config__item-desc",children:r.fixedLength?`${r.fixedLength} digits`:`${r.minLength}-${r.maxLength} chars`})]})]},r.id)})})]},b))}),R&&T&&t.jsxs("div",{className:"nice-symbology-config__details",children:[t.jsx("h3",{className:"nice-symbology-config__details-title",children:T.name}),t.jsx("p",{className:"nice-symbology-config__details-desc",children:T.description}),t.jsxs("div",{className:"nice-symbology-config__details-props",children:[t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Category"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:Me[T.category]})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Character Set"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.charset})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Length"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.fixedLength?`Fixed: ${T.fixedLength}`:`${T.minLength} – ${T.maxLength}`})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Check Digit"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.hasCheckDigit?"Yes":"No"})]}),T.standard&&t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Standard"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.standard})]})]}),t.jsxs("div",{className:"nice-symbology-config__use-cases",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Use Cases"}),t.jsx("div",{className:"nice-symbology-config__tags",children:T.useCases.map(b=>t.jsx("span",{className:"nice-symbology-config__tag",children:b},b))})]}),G&&D&&t.jsxs("div",{className:"nice-symbology-config__validation",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Validation"}),t.jsxs("div",{className:`nice-symbology-config__validation-result ${D.valid?"nice-symbology-config__validation-result--valid":"nice-symbology-config__validation-result--invalid"}`,children:[t.jsx("span",{children:D.valid?"Valid":"Invalid"}),D.checkDigit&&t.jsxs("span",{children:["Check digit: ",D.checkDigit]})]}),D.errors.map((b,s)=>t.jsx("div",{className:"nice-symbology-config__validation-error",children:b},s)),D.warnings.map((b,s)=>t.jsx("div",{className:"nice-symbology-config__validation-warning",children:b},s))]})]})]})]})})});ot.displayName="NiceSymbologyConfig";const En=({children:n})=>{const f=e.useCallback(k=>ie.find(g=>g.id===k),[]),h={symbologies:ie,selected:[],validate:de,getInfo:f};return t.jsx(Ce.Provider,{value:h,children:n})},lt=e.createContext(null),Pn=()=>{const n=e.useContext(lt);if(!n)throw new Error("useBackgroundSync must be used within NiceBackgroundSyncProvider");return n},Ln={dbName:"nice-background-sync",storeName:"sync-queue",defaultMaxAttempts:5,retryDelay:1e3,backoffFactor:2,maxRetryDelay:6e4,autoSyncOnConnect:!0,periodicSyncInterval:0},Rn=()=>`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,On=n=>new Promise(f=>setTimeout(f,n)),ke=e.forwardRef((n,f)=>{const{config:h,handlers:k,onSyncStart:g,onSyncComplete:N,onTaskSuccess:R,onTaskFailed:G,onOnlineChange:i,children:l}=n,y={...Ln,...h},A=e.useRef(null),v=e.useRef(!1),[d,p]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,pendingCount:0,failedCount:0,syncProgress:0}),j=e.useCallback(async()=>A.current?A.current:new Promise((a,c)=>{const o=indexedDB.open(y.dbName,1);o.onerror=()=>c(o.error),o.onupgradeneeded=()=>{const S=o.result;if(!S.objectStoreNames.contains(y.storeName)){const E=S.createObjectStore(y.storeName,{keyPath:"id"});E.createIndex("tag","tag",{unique:!1}),E.createIndex("status","status",{unique:!1}),E.createIndex("priority","priority",{unique:!1})}},o.onsuccess=()=>{A.current=o.result,a(o.result)}}),[y.dbName,y.storeName]),B=e.useCallback(async(a,c,o)=>{const S=await j(),E={id:Rn(),tag:a,data:c,status:"pending",createdAt:new Date,attempts:0,maxAttempts:(o==null?void 0:o.maxAttempts)??y.defaultMaxAttempts,priority:(o==null?void 0:o.priority)??0};return new Promise((m,w)=>{const x=S.transaction(y.storeName,"readwrite").objectStore(y.storeName).add(E);x.onerror=()=>w(x.error),x.onsuccess=()=>{p(W=>({...W,pendingCount:W.pendingCount+1})),m(E.id)}})},[j,y.storeName,y.defaultMaxAttempts]),q=e.useCallback(async a=>{const c=await j();return new Promise((o,S)=>{const w=c.transaction(y.storeName,"readwrite").objectStore(y.storeName).delete(a);w.onerror=()=>S(w.error),w.onsuccess=()=>o(!0)})},[j,y.storeName]),z=e.useCallback(async a=>{const c=await j();return new Promise((o,S)=>{const m=c.transaction(y.storeName,"readonly").objectStore(y.storeName),w=a?m.index("tag").getAll(a):m.getAll();w.onerror=()=>S(w.error),w.onsuccess=()=>o(w.result)})},[j,y.storeName]),Y=e.useCallback(async a=>(await z(a)).filter(o=>o.status==="pending"),[z]),K=e.useCallback(async a=>(await z(a)).filter(o=>o.status==="failed"),[z]),F=e.useCallback(async a=>{const c=await j();return new Promise((o,S)=>{const w=c.transaction(y.storeName,"readwrite").objectStore(y.storeName).put(a);w.onerror=()=>S(w.error),w.onsuccess=()=>o()})},[j,y.storeName]),V=e.useCallback(async()=>{const a=await z(),c=a.filter(S=>S.status==="pending").length,o=a.filter(S=>S.status==="failed").length;p(S=>({...S,pendingCount:c,failedCount:o}))},[z]),I=e.useCallback(async a=>{const c=k[a.tag];if(!c)return console.warn(`No handler registered for tag: ${a.tag}`),!1;a.status="syncing",a.lastAttemptAt=new Date,a.attempts++,await F(a);try{return await c.handler(a),a.status="success",await F(a),R==null||R(a),await q(a.id),!0}catch(o){const S=o instanceof Error?o.message:"Unknown error";return a.error=S,a.attempts>=a.maxAttempts?(a.status="failed",G==null||G(a,o instanceof Error?o:new Error(S))):a.status="pending",await F(a),!1}},[k,F,q,R,G]),U=e.useCallback(async a=>{if(d.isSyncing)return{success:0,failed:0};v.current=!1,p(o=>({...o,isSyncing:!0,syncProgress:0,error:void 0})),g==null||g();const c={success:0,failed:0};try{const o=await Y(a);o.sort((E,m)=>m.priority-E.priority);const S=o.length;for(let E=0;E<o.length&&!v.current;E++){const m=o[E],w=await I(m);if(w?c.success++:m.attempts>=m.maxAttempts&&c.failed++,!w&&m.attempts<m.maxAttempts){const u=Math.min(y.retryDelay*Math.pow(y.backoffFactor,m.attempts-1),y.maxRetryDelay);await On(u)}p(u=>({...u,syncProgress:Math.round((E+1)/S*100)}))}}catch(o){const S=o instanceof Error?o.message:"Sync failed";p(E=>({...E,error:S}))}return await V(),p(o=>({...o,isSyncing:!1,lastSyncAt:new Date,syncProgress:100})),N==null||N(c),c},[d.isSyncing,Y,I,y.retryDelay,y.backoffFactor,y.maxRetryDelay,V,g,N]),D=e.useCallback(()=>{v.current=!0},[]),P=e.useCallback(async a=>{const o=(await z()).find(S=>S.id===a);o&&o.status==="failed"&&(o.status="pending",o.attempts=0,o.error=void 0,await F(o),await V())},[z,F,V]),T=e.useCallback(async a=>{const c=await K(a);for(const o of c)o.status="pending",o.attempts=0,o.error=void 0,await F(o);await V()},[K,F,V]),O=e.useCallback(async a=>{const c=await j(),o=await z(a);return new Promise((S,E)=>{const m=c.transaction(y.storeName,"readwrite"),w=m.objectStore(y.storeName);m.onerror=()=>E(m.error),m.oncomplete=async()=>{await V(),S()};for(const u of o)w.delete(u.id)})},[j,z,y.storeName,V]),b=e.useCallback(async a=>{const c=await j(),o=await K(a);return new Promise((S,E)=>{const m=c.transaction(y.storeName,"readwrite"),w=m.objectStore(y.storeName);m.onerror=()=>E(m.error),m.oncomplete=async()=>{await V(),S()};for(const u of o)w.delete(u.id)})},[j,K,y.storeName,V]),s=e.useCallback(async a=>{if(!("serviceWorker"in navigator))return!1;try{const c=await navigator.serviceWorker.ready;if("sync"in c)return await c.sync.register(a),!0}catch(c){console.warn("Background Sync registration failed:",c)}return!1},[]);e.useEffect(()=>{const a=()=>{p(o=>({...o,isOnline:!0})),i==null||i(!0),y.autoSyncOnConnect&&U()},c=()=>{p(o=>({...o,isOnline:!1})),i==null||i(!1)};return window.addEventListener("online",a),window.addEventListener("offline",c),()=>{window.removeEventListener("online",a),window.removeEventListener("offline",c)}},[y.autoSyncOnConnect,U,i]),e.useEffect(()=>{if(y.periodicSyncInterval<=0)return;const a=setInterval(()=>{d.isOnline&&!d.isSyncing&&U()},y.periodicSyncInterval);return()=>clearInterval(a)},[y.periodicSyncInterval,d.isOnline,d.isSyncing,U]),e.useEffect(()=>{V()},[V]),e.useImperativeHandle(f,()=>({getState:()=>d,addTask:B,removeTask:q,getTasks:z,getPendingTasks:Y,getFailedTasks:K,retryTask:P,retryAllFailed:T,clearTasks:O,clearFailed:b,syncNow:U,cancelSync:D,registerBackgroundSync:s}),[d,B,q,z,Y,K,P,T,O,b,U,D,s]);const r={...d,addTask:B,removeTask:q,getTasks:z,getPendingTasks:Y,getFailedTasks:K,retryTask:P,retryAllFailed:T,clearTasks:O,clearFailed:b,syncNow:U,cancelSync:D};return t.jsx(lt.Provider,{value:r,children:l})});ke.displayName="NiceBackgroundSync";const ut=ke;ut.displayName="NiceBackgroundSyncProvider";const dt=e.createContext(null),ft=()=>{const n=e.useContext(dt);if(!n)throw new Error("useCacheStrategies must be used within NiceCacheStrategiesProvider");return n},Tn={cacheName:"nice-cache-strategies",defaultTTL:300*1e3,maxEntries:500,defaultStrategy:"stale-while-revalidate",networkTimeout:5e3,serveStale:!0,staleThreshold:60*1e3};class Mn{constructor(){oe(this,"dbName","nice-cache-db");oe(this,"storeName","cache-entries");oe(this,"db",null)}async init(){if(!this.db)return new Promise((f,h)=>{const k=indexedDB.open(this.dbName,1);k.onerror=()=>h(k.error),k.onupgradeneeded=()=>{const g=k.result;g.objectStoreNames.contains(this.storeName)||g.createObjectStore(this.storeName,{keyPath:"key"})},k.onsuccess=()=>{this.db=k.result,f()}})}async get(f){if(await this.init(),!!this.db)return new Promise((h,k)=>{const R=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(f);R.onerror=()=>k(R.error),R.onsuccess=()=>{const G=R.result;h(G?G.value:void 0)}})}async set(f,h){if(await this.init(),!!this.db)return new Promise((k,g)=>{const G=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:f,value:h});G.onerror=()=>g(G.error),G.onsuccess=()=>k()})}async delete(f){return await this.init(),this.db?new Promise((h,k)=>{const R=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(f);R.onerror=()=>k(R.error),R.onsuccess=()=>h(!0)}):!1}async keys(){return await this.init(),this.db?new Promise((f,h)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();N.onerror=()=>h(N.error),N.onsuccess=()=>f(N.result)}):[]}async clear(){if(await this.init(),!!this.db)return new Promise((f,h)=>{const N=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();N.onerror=()=>h(N.error),N.onsuccess=()=>f()})}async getAll(){return await this.init(),this.db?new Promise((f,h)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();N.onerror=()=>h(N.error),N.onsuccess=()=>f(N.result)}):[]}}const Se=e.forwardRef((n,f)=>{const{config:h,routeStrategies:k={},precacheUrls:g=[],onFetch:N,onCacheHit:R,onCacheMiss:G,onNetworkError:i,children:l}=n,y={...Tn,...h},A=e.useRef(new Mn),[v,d]=e.useState({isFetching:!1,totalSize:0,entryCount:0,hits:0,misses:0,strategy:y.defaultStrategy}),p=e.useCallback(s=>{for(const[r,a]of Object.entries(k))if(new RegExp(r).test(s))return a;return v.strategy},[k,v.strategy]),j=e.useCallback(s=>{d(r=>({...r,strategy:s}))},[]),B=e.useCallback(async s=>{const r=await A.current.get(s);if(!r)return;const a=Date.now(),c=r.expiresAt&&r.expiresAt<a,o=r.timestamp+y.staleThreshold<a;if(c&&!y.serveStale){await A.current.delete(s);return}return{data:r.data,timestamp:new Date(r.timestamp),expiresAt:r.expiresAt?new Date(r.expiresAt):void 0,etag:r.etag,key:s,isStale:o||!!c,source:"cache",url:r.url}},[y.staleThreshold,y.serveStale]),q=e.useCallback(async()=>{const s=await A.current.getAll();let r=0,a,c;for(const o of s){const S=JSON.stringify(o.value.data).length;r+=S,(!a||o.value.timestamp<a)&&(a=o.value.timestamp),(!c||o.value.timestamp>c)&&(c=o.value.timestamp)}return{size:r,entryCount:s.length,oldestEntry:a?new Date(a):void 0,newestEntry:c?new Date(c):void 0}},[]),z=e.useCallback(async()=>{const s=await q();d(r=>({...r,entryCount:s.entryCount,totalSize:s.size}))},[q]),Y=e.useCallback(async(s,r,a)=>{const c=Date.now(),o={data:r,timestamp:c,expiresAt:a?c+a:c+y.defaultTTL};if(await A.current.set(s,o),(await A.current.keys()).length>y.maxEntries){const E=await A.current.getAll();E.sort((w,u)=>w.value.timestamp-u.value.timestamp);const m=E.slice(0,E.length-y.maxEntries);for(const w of m)await A.current.delete(w.key)}await z()},[y.defaultTTL,y.maxEntries,z]),K=e.useCallback(async s=>{const r=await A.current.delete(s);return await z(),r},[z]),F=e.useCallback(async()=>{await A.current.clear(),d(s=>({...s,entryCount:0,totalSize:0}))},[]),V=e.useCallback(async()=>A.current.keys(),[]),I=e.useCallback(async s=>await B(s)!==void 0,[B]),U=e.useCallback(async s=>{const r=await A.current.keys();let a=0;for(const c of r)s.test(c)&&(await A.current.delete(c),a++);return await z(),a},[z]),D=e.useCallback(async(s,r,a)=>{const c=new AbortController,o=setTimeout(()=>c.abort(),a);try{const S=await fetch(s,{...r,signal:c.signal});return clearTimeout(o),S}catch(S){throw clearTimeout(o),S}},[]),P=e.useCallback(async(s,r={})=>{const{strategy:a=p(s),ttl:c,cacheKey:o=s,forceRefresh:S=!1,timeout:E=y.networkTimeout,...m}=r;d(u=>({...u,isFetching:!0}));const w=async()=>{try{const u=await D(s,m,E);if(!u.ok)throw new Error(`HTTP ${u.status}`);const C=await u.json(),x=u.headers.get("etag")||void 0;await Y(o,C,c);const W={data:C,timestamp:new Date,etag:x,key:o,isStale:!1,source:"network",url:s};return d(_=>({..._,isFetching:!1})),N==null||N(W),W}catch(u){throw i==null||i(u instanceof Error?u:new Error(String(u)),s),u}};try{switch(a){case"cache-only":{const u=await B(o);if(u)return d(C=>({...C,isFetching:!1,hits:C.hits+1})),R==null||R(u),u;throw d(C=>({...C,isFetching:!1,misses:C.misses+1})),G==null||G(s),new Error("No cache entry found")}case"network-only":return d(u=>({...u,misses:u.misses+1})),await w();case"cache-first":{if(!S){const u=await B(o);if(u&&!u.isStale)return d(C=>({...C,isFetching:!1,hits:C.hits+1})),R==null||R(u),u}return d(u=>({...u,misses:u.misses+1})),await w()}case"network-first":try{return d(u=>({...u,misses:u.misses+1})),await w()}catch(u){const C=await B(o);if(C)return d(x=>({...x,isFetching:!1,hits:x.hits+1})),R==null||R(C),C;throw u}case"stale-while-revalidate":default:{const u=await B(o);return u&&!S?(d(C=>({...C,hits:C.hits+1})),R==null||R(u),u.isStale&&w().catch(()=>{}),d(C=>({...C,isFetching:!1})),u):(d(C=>({...C,misses:C.misses+1})),await w())}}}catch(u){throw d(C=>({...C,isFetching:!1})),u}},[p,y.networkTimeout,D,B,Y,N,R,G,i]),T=e.useCallback(async(s,r)=>(await P(s,r)).data,[P]),O=e.useCallback(async(s,r)=>{await Promise.all(s.map(a=>P(a,{...r,strategy:"network-first"}).catch(()=>{})))},[P]);e.useEffect(()=>{g.length>0&&O(g)},[g,O]),e.useEffect(()=>{(async()=>{await A.current.init();const r=await q();d(a=>({...a,totalSize:r.size,entryCount:r.entryCount}))})()},[q]),e.useImperativeHandle(f,()=>({getState:()=>v,fetch:P,fetchJSON:T,getFromCache:B,addToCache:Y,removeFromCache:K,clearCache:F,getCacheKeys:V,getCacheStats:q,prefetch:O,isCached:I,invalidateByPattern:U,setStrategy:j,getStrategyForUrl:p}),[v,P,T,B,Y,K,F,V,q,O,I,U,j,p]);const b={...v,fetch:P,fetchJSON:T,getFromCache:B,addToCache:Y,removeFromCache:K,clearCache:F,getCacheKeys:V,prefetch:O,isCached:I,setStrategy:j,getStrategyForUrl:p};return t.jsx(dt.Provider,{value:b,children:l})});Se.displayName="NiceCacheStrategies";const mt=Se;mt.displayName="NiceCacheStrategiesProvider";function Fn(n,f){const h=ft(),[k,g]=e.useState(void 0),[N,R]=e.useState(!1),[G,i]=e.useState(void 0),l=e.useCallback(async()=>{if(n){R(!0),i(void 0);try{const y=await h.fetchJSON(n,f);g(y)}catch(y){i(y instanceof Error?y:new Error(String(y)))}finally{R(!1)}}},[n,f,h]);return e.useEffect(()=>{l()},[l]),{data:k,isLoading:N,error:G,refetch:l}}const ht=e.createContext(null),Bn=()=>{const n=e.useContext(ht);if(!n)throw new Error("useConflictResolution must be used within NiceConflictResolutionProvider");return n},$n={defaultStrategy:"manual",autoResolve:!1,maxPendingConflicts:100,persistConflicts:!0,storageKey:"nice-conflict-resolution"},qn=()=>`conflict-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Un=n=>JSON.stringify(n),Hn=(n,f)=>JSON.stringify(n)===JSON.stringify(f),Wn=(n,f,h)=>({...n,...f}),_e=e.forwardRef((n,f)=>{const{config:h,handlers:k={},showConflictUI:g=!0,uiPosition:N="modal",autoOpenUI:R=!0,onConflictDetected:G,onConflictResolved:i,onResolutionFailed:l,renderConflictList:y,renderConflictItem:A,children:v}=n,d={...$n,...h},[p,j]=e.useState([]),[B,q]=e.useState(!1),[z,Y]=e.useState(!1),K=e.useCallback(_=>k[_]||{},[k]),F=e.useCallback(_=>({pending:_.filter(M=>M.status==="pending").length,resolving:_.filter(M=>M.status==="resolving").length,resolved:_.filter(M=>M.status==="resolved").length,failed:_.filter(M=>M.status==="failed").length}),[]),V={conflicts:p,isResolving:B,counts:F(p)},I=e.useCallback(()=>{if(d.persistConflicts)try{const _=localStorage.getItem(d.storageKey);if(_){const L=JSON.parse(_).map(X=>({...X,createdAt:new Date(X.createdAt),resolvedAt:X.resolvedAt?new Date(X.resolvedAt):void 0,clientVersion:{...X.clientVersion,timestamp:new Date(X.clientVersion.timestamp)},serverVersion:{...X.serverVersion,timestamp:new Date(X.serverVersion.timestamp)},baseVersion:X.baseVersion?{...X.baseVersion,timestamp:new Date(X.baseVersion.timestamp)}:void 0}));j(L)}}catch(_){console.warn("Failed to load persisted conflicts:",_)}},[d.persistConflicts,d.storageKey]),U=e.useCallback(_=>{if(d.persistConflicts)try{const M=_.filter(L=>L.status==="pending"||L.status==="failed");localStorage.setItem(d.storageKey,JSON.stringify(M))}catch(M){console.warn("Failed to persist conflicts:",M)}},[d.persistConflicts,d.storageKey]);e.useEffect(()=>{I()},[I]),e.useEffect(()=>{U(p)},[p,U]);const D=e.useCallback((_,M,L,X,$)=>{const Z=K(_),J=Z.compare||Hn,H=Z.hash||Un,Q=Z.getConflictingFields;if(J(L.data,X.data)||L.timestamp<X.timestamp&&$&&J(L.data,$.data))return null;const ee={id:qn(),entityType:_,entityId:M,clientVersion:{...L,hash:H(L.data)},serverVersion:{...X,hash:H(X.data)},baseVersion:$?{...$,hash:H($.data)}:void 0,status:"pending",createdAt:new Date,conflictingFields:Q?Q(L.data,X.data):void 0};return P(ee),ee},[K]),P=e.useCallback(_=>{j(M=>{const L=M.findIndex($=>$.entityType===_.entityType&&$.entityId===_.entityId);let X;return L>=0?(X=[...M],X[L]=_):X=[...M,_],X.length>d.maxPendingConflicts&&(X=X.slice(-d.maxPendingConflicts)),X}),G==null||G(_),R&&g&&Y(!0),d.autoResolve&&d.defaultStrategy!=="manual"&&T(_.id,d.defaultStrategy)},[d.maxPendingConflicts,d.autoResolve,d.defaultStrategy,R,g,G]),T=e.useCallback(async(_,M,L)=>{var J;const X=p.findIndex(H=>H.id===_);if(X===-1)return;const $=p[X],Z=K($.entityType);q(!0),j(H=>{const Q=[...H];return Q[X]={...$,status:"resolving"},Q});try{let H;switch(M){case"client-wins":H=$.clientVersion.data;break;case"server-wins":H=$.serverVersion.data;break;case"latest-wins":H=$.clientVersion.timestamp>$.serverVersion.timestamp?$.clientVersion.data:$.serverVersion.data;break;case"merge":{H=await(Z.merge||Wn)($.clientVersion.data,$.serverVersion.data,(J=$.baseVersion)==null?void 0:J.data);break}case"manual":if(L===void 0)throw new Error("Manual resolution requires merged data");H=L;break}const Q={...$,status:"resolved",resolvedVersion:{data:H,timestamp:new Date,source:M==="client-wins"?"client":"server"},resolvedWith:M,resolvedAt:new Date};j(ee=>{const te=[...ee];return te[X]=Q,te}),i==null||i(Q)}catch(H){const Q=H instanceof Error?H.message:"Resolution failed";j(ee=>{const te=[...ee];return te[X]={...$,status:"failed",error:Q},te}),l==null||l($,H instanceof Error?H:new Error(Q))}finally{q(!1)}},[p,K,i,l]),O=e.useCallback(async _=>{const M=p.filter(L=>L.status==="pending");for(const L of M)await T(L.id,_)},[p,T]),b=e.useCallback(_=>p.find(M=>M.id===_),[p]),s=e.useCallback((_,M)=>p.filter(L=>L.entityType===_&&(M===void 0||L.entityId===M)),[p]),r=e.useCallback(()=>p.filter(_=>_.status==="pending"),[p]),a=e.useCallback(_=>{j(M=>M.filter(L=>L.id!==_))},[]),c=e.useCallback(()=>{j(_=>_.filter(M=>M.status!=="resolved"))},[]),o=e.useCallback(()=>{j([])},[]),S=e.useCallback(()=>Y(!0),[]),E=e.useCallback(()=>Y(!1),[]);e.useImperativeHandle(f,()=>({getState:()=>V,detectConflict:D,addConflict:P,resolveConflict:T,resolveAll:O,getConflict:b,getConflictsByEntity:s,getPendingConflicts:r,dismissConflict:a,clearResolved:c,clearAll:o,openUI:S,closeUI:E}),[V,D,P,T,O,b,s,r,a,c,o,S,E]);const m={...V,detectConflict:D,addConflict:P,resolveConflict:T,resolveAll:O,getConflict:b,getConflictsByEntity:s,getPendingConflicts:r,dismissConflict:a,clearResolved:c,clearAll:o},w=r(),u=(_,M,L)=>{T(_,M,L)},C=_=>{a(_)},x=_=>A?A({conflict:_,onResolve:(M,L)=>u(_.id,M,L),onDismiss:()=>C(_.id)}):t.jsxs("div",{className:"nice-conflict-item",children:[t.jsxs("div",{className:"nice-conflict-item__header",children:[t.jsx("span",{className:"nice-conflict-item__type",children:_.entityType}),t.jsxs("span",{className:"nice-conflict-item__id",children:["ID: ",_.entityId]})]}),t.jsxs("div",{className:"nice-conflict-item__versions",children:[t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--client",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:"Your changes"}),t.jsx("span",{className:"nice-conflict-item__version-time",children:_.clientVersion.timestamp.toLocaleString()})]}),t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--server",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:"Server version"}),t.jsx("span",{className:"nice-conflict-item__version-time",children:_.serverVersion.timestamp.toLocaleString()})]})]}),_.conflictingFields&&_.conflictingFields.length>0&&t.jsxs("div",{className:"nice-conflict-item__fields",children:[t.jsx("span",{children:"Conflicting fields:"}),_.conflictingFields.map(M=>t.jsx("code",{children:M},M))]}),t.jsxs("div",{className:"nice-conflict-item__actions",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>u(_.id,"client-wins"),disabled:B,children:"Keep Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>u(_.id,"server-wins"),disabled:B,children:"Use Server"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--merge",onClick:()=>u(_.id,"merge"),disabled:B,children:"Merge"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--dismiss",onClick:()=>C(_.id),disabled:B,children:"Dismiss"})]})]},_.id),W=()=>{if(!g||!z||w.length===0)return null;if(y)return y({conflicts:w,onResolve:u,onDismiss:C});const _=t.jsxs("div",{className:"nice-conflict-list",children:[t.jsxs("div",{className:"nice-conflict-list__header",children:[t.jsxs("h3",{children:["Sync Conflicts (",w.length,")"]}),t.jsx("button",{className:"nice-conflict-list__close",onClick:E,"aria-label":"Close",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-conflict-list__items",children:w.map(x)}),w.length>1&&t.jsxs("div",{className:"nice-conflict-list__bulk",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>O("client-wins"),disabled:B,children:"Keep All Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>O("server-wins"),disabled:B,children:"Use All Server"})]})]});switch(N){case"modal":return t.jsx("div",{className:"nice-conflict-overlay",children:t.jsx("div",{className:"nice-conflict-modal",children:_})});case"drawer":return t.jsx("div",{className:"nice-conflict-drawer nice-conflict-drawer--open",children:_});case"toast":return t.jsx("div",{className:"nice-conflict-toast",children:_});case"inline":default:return _}};return t.jsxs(ht.Provider,{value:m,children:[v,W()]})});_e.displayName="NiceConflictResolution";const gt=_e;gt.displayName="NiceConflictResolutionProvider";const pt=e.createContext(null),yt=()=>{const n=e.useContext(pt);if(!n)throw new Error("useIndexedDB must be used within NiceIndexedDBProvider");return n};function Vn(n){const f=yt(),h=e.useCallback(d=>f.get(n,d),[f,n]),k=e.useCallback(d=>f.getAll(n,d),[f,n]),g=e.useCallback((d,p)=>f.add(n,d,p),[f,n]),N=e.useCallback((d,p)=>f.put(n,d,p),[f,n]),R=e.useCallback(d=>f.delete(n,d),[f,n]),G=e.useCallback(()=>f.clear(n),[f,n]),i=e.useCallback(d=>f.count(n,d),[f,n]),l=e.useCallback(d=>f.query(n,d),[f,n]),y=e.useCallback(d=>f.bulkAdd(n,d),[f,n]),A=e.useCallback(d=>f.bulkPut(n,d),[f,n]),v=e.useCallback(d=>f.bulkDelete(n,d),[f,n]);return{isOpen:f.isOpen,isLoading:f.isLoading,error:f.error,get:h,getAll:k,add:g,put:N,remove:R,clear:G,count:i,query:l,bulkAdd:y,bulkPut:A,bulkDelete:v}}const Ne=e.forwardRef((n,f)=>{const{config:h,autoOpen:k=!0,onOpen:g,onError:N,onClose:R,children:G}=n,i=e.useRef(null),[l,y]=e.useState({isOpen:!1,isLoading:!1,storeNames:[]}),A=e.useCallback(async()=>{if(i.current)return i.current;if(!("indexedDB"in window))throw new Error("IndexedDB is not supported in this browser");return y(s=>({...s,isLoading:!0,error:void 0})),new Promise((s,r)=>{const a=indexedDB.open(h.dbName,h.version);a.onerror=()=>{var o;const c=new Error(((o=a.error)==null?void 0:o.message)||"Failed to open database");y(S=>({...S,isLoading:!1,error:c.message})),N==null||N(c),r(c)},a.onblocked=()=>{var c;(c=h.onBlocked)==null||c.call(h)},a.onupgradeneeded=c=>{var m;const o=a.result,S=c.oldVersion,E=c.newVersion;for(const w of h.stores)if(!o.objectStoreNames.contains(w.name)){const u=o.createObjectStore(w.name,{keyPath:w.keyPath,autoIncrement:w.autoIncrement});if(w.indexes)for(const C of w.indexes)u.createIndex(C.name,C.keyPath,C.options)}(m=h.onUpgrade)==null||m.call(h,o,S,E)},a.onsuccess=()=>{const c=a.result;i.current=c,c.onclose=()=>{i.current=null,y(o=>({...o,isOpen:!1,db:void 0})),R==null||R()},c.onerror=o=>{var E;const S=o.target;N==null||N(new Error(((E=S.error)==null?void 0:E.message)||"Database error"))},y({db:c,isOpen:!0,isLoading:!1,version:c.version,storeNames:Array.from(c.objectStoreNames)}),g==null||g(c),s(c)}})},[h,g,N,R]),v=e.useCallback(()=>{i.current&&(i.current.close(),i.current=null,y(s=>({...s,isOpen:!1,db:void 0})),R==null||R())},[R]),d=e.useCallback(async()=>(v(),new Promise((s,r)=>{const a=indexedDB.deleteDatabase(h.dbName);a.onerror=()=>{var c;r(new Error(((c=a.error)==null?void 0:c.message)||"Failed to delete database"))},a.onsuccess=()=>{y({isOpen:!1,isLoading:!1,storeNames:[]}),s()}})),[h.dbName,v]),p=e.useCallback(async()=>i.current?i.current:A(),[A]),j=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const m=a.transaction(s,"readonly").objectStore(s).get(r);m.onerror=()=>{var w;return o(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>c(m.result)})},[p]),B=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const E=a.transaction(s,"readonly").objectStore(s),w=(r!=null&&r.index?E.index(r.index):E).getAll(r==null?void 0:r.range,r==null?void 0:r.limit);w.onerror=()=>{var u;return o(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>{let u=w.result;r!=null&&r.offset&&(u=u.slice(r.offset)),c(u)}})},[p]),q=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const E=a.transaction(s,"readonly").objectStore(s),w=(r!=null&&r.index?E.index(r.index):E).getAllKeys(r==null?void 0:r.range,r==null?void 0:r.limit);w.onerror=()=>{var u;return o(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>c(w.result)})},[p]),z=e.useCallback(async(s,r,a)=>{const c=await p();return new Promise((o,S)=>{const w=c.transaction(s,"readwrite").objectStore(s).add(r,a);w.onerror=()=>{var u;return S(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>o(w.result)})},[p]),Y=e.useCallback(async(s,r,a)=>{const c=await p();return new Promise((o,S)=>{const w=c.transaction(s,"readwrite").objectStore(s).put(r,a);w.onerror=()=>{var u;return S(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>o(w.result)})},[p]),K=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const m=a.transaction(s,"readwrite").objectStore(s).delete(r);m.onerror=()=>{var w;return o(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>c()})},[p]),F=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const E=r.transaction(s,"readwrite").objectStore(s).clear();E.onerror=()=>{var m;return c(new Error((m=E.error)==null?void 0:m.message))},E.onsuccess=()=>a()})},[p]),V=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const m=a.transaction(s,"readonly").objectStore(s).count(r);m.onerror=()=>{var w;return o(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>c(m.result)})},[p]),I=e.useCallback(async(s,r)=>{const a=await p(),c=[];return new Promise((o,S)=>{const m=a.transaction(s,"readonly").objectStore(s),u=(r.index?m.index(r.index):m).openCursor(r.range,r.direction);let C=0,x=0;u.onerror=()=>{var W;return S(new Error((W=u.error)==null?void 0:W.message))},u.onsuccess=()=>{const W=u.result;if(W){if(r.offset&&C<r.offset){C++,W.continue();return}if(r.limit&&x>=r.limit){o(c);return}c.push(W.value),x++,W.continue()}else o(c)}})},[p]),U=e.useCallback(async(s,r)=>{const c=(await p()).transaction(s.stores,s.mode||"readwrite");return new Promise((o,S)=>{c.onerror=()=>{var E;return S(new Error((E=c.error)==null?void 0:E.message))},c.onabort=()=>S(new Error("Transaction aborted")),r(c).then(E=>{c.oncomplete=()=>o(E)}).catch(S)})},[p]),D=e.useCallback(async(s,r)=>{const a=await p(),c=[];return new Promise((o,S)=>{const E=a.transaction(s,"readwrite"),m=E.objectStore(s);E.onerror=()=>{var w;return S(new Error((w=E.error)==null?void 0:w.message))},E.oncomplete=()=>o(c);for(const w of r){const u=m.add(w);u.onsuccess=()=>c.push(u.result)}})},[p]),P=e.useCallback(async(s,r)=>{const a=await p(),c=[];return new Promise((o,S)=>{const E=a.transaction(s,"readwrite"),m=E.objectStore(s);E.onerror=()=>{var w;return S(new Error((w=E.error)==null?void 0:w.message))},E.oncomplete=()=>o(c);for(const w of r){const u=m.put(w);u.onsuccess=()=>c.push(u.result)}})},[p]),T=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const S=a.transaction(s,"readwrite"),E=S.objectStore(s);S.onerror=()=>{var m;return o(new Error((m=S.error)==null?void 0:m.message))},S.oncomplete=()=>c();for(const m of r)E.delete(m)})},[p]),O=e.useCallback(async()=>{const s=await p(),r=[];for(const a of s.objectStoreNames){const o=s.transaction(a,"readonly").objectStore(a);r.push({name:o.name,keyPath:o.keyPath,autoIncrement:o.autoIncrement,indexNames:Array.from(o.indexNames)})}return{name:s.name,version:s.version,stores:r}},[p]);e.useEffect(()=>(k&&A().catch(()=>{}),()=>{v()}),[k,A,v]),e.useImperativeHandle(f,()=>({getState:()=>l,open:A,close:v,deleteDatabase:d,get:j,getAll:B,getAllKeys:q,add:z,put:Y,delete:K,clear:F,count:V,query:I,transaction:U,bulkAdd:D,bulkPut:P,bulkDelete:T,getInfo:O}),[l,A,v,d,j,B,q,z,Y,K,F,V,I,U,D,P,T,O]);const b={...l,open:A,close:v,deleteDatabase:d,get:j,getAll:B,getAllKeys:q,add:z,put:Y,delete:K,clear:F,count:V,query:I,transaction:U,bulkAdd:D,bulkPut:P,bulkDelete:T};return t.jsx(pt.Provider,{value:b,children:G})});Ne.displayName="NiceIndexedDB";const bt=Ne;bt.displayName="NiceIndexedDBProvider";const wt=e.createContext(null),vt=()=>{const n=e.useContext(wt);if(!n)throw new Error("useOfflineForms must be used within NiceOfflineFormsProvider");return n},zn={dbName:"nice-offline-forms",autoSaveInterval:5e3,maxDraftsPerForm:50,autoSubmitOnline:!0,retryFailed:!0,maxRetryAttempts:3,retryDelay:5e3},Gn=()=>`draft-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Ie=e.forwardRef((n,f)=>{const{config:h,submitHandlers:k={},onDraftSaved:g,onFormSubmitted:N,onSubmissionFailed:R,onSyncComplete:G,children:i}=n,l={...zn,...h},y=e.useRef(null),A=e.useRef(k),[v,d]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,draftCounts:{},pendingCount:0,failedCount:0}),p=e.useCallback(async()=>y.current?y.current:new Promise((s,r)=>{const a=indexedDB.open(l.dbName,1);a.onerror=()=>r(a.error),a.onupgradeneeded=()=>{const c=a.result;if(!c.objectStoreNames.contains("drafts")){const o=c.createObjectStore("drafts",{keyPath:"id"});o.createIndex("formId","formId",{unique:!1}),o.createIndex("status","status",{unique:!1})}},a.onsuccess=()=>{y.current=a.result,s(a.result)}}),[l.dbName]),j=e.useCallback(async(s,r,a)=>{const c=await p(),o={id:Gn(),formId:s,data:r,status:"draft",createdAt:new Date,modifiedAt:new Date,attempts:0,version:1,submittedOffline:!1,metadata:a};return new Promise((S,E)=>{const u=c.transaction("drafts","readwrite").objectStore("drafts").add(o);u.onerror=()=>E(u.error),u.onsuccess=()=>{g==null||g(o),O(),S(o.id)}})},[p,g]),B=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const E=r.transaction("drafts","readonly").objectStore("drafts").get(s);E.onerror=()=>c(E.error),E.onsuccess=()=>{const m=E.result;m&&(m.createdAt=new Date(m.createdAt),m.modifiedAt=new Date(m.modifiedAt),m.syncedAt&&(m.syncedAt=new Date(m.syncedAt))),a(m)}})},[p]),q=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const m=r.transaction("drafts","readonly").objectStore("drafts").index("formId").getAll(s);m.onerror=()=>c(m.error),m.onsuccess=()=>{const w=m.result.map(u=>({...u,createdAt:new Date(u.createdAt),modifiedAt:new Date(u.modifiedAt),syncedAt:u.syncedAt?new Date(u.syncedAt):void 0}));a(w)}})},[p]),z=e.useCallback(async()=>{const s=await p();return new Promise((r,a)=>{const S=s.transaction("drafts","readonly").objectStore("drafts").getAll();S.onerror=()=>a(S.error),S.onsuccess=()=>{const E=S.result.filter(m=>m.status==="pending"||m.status==="failed").map(m=>({...m,createdAt:new Date(m.createdAt),modifiedAt:new Date(m.modifiedAt),syncedAt:m.syncedAt?new Date(m.syncedAt):void 0}));r(E)}})},[p]),Y=e.useCallback(async(s,r)=>{const a=await B(s);if(!a)return;const c=await p(),o={...a,data:{...a.data,...r},modifiedAt:new Date,version:a.version+1};return new Promise((S,E)=>{const u=c.transaction("drafts","readwrite").objectStore("drafts").put(o);u.onerror=()=>E(u.error),u.onsuccess=()=>{g==null||g(o),S()}})},[p,B,g]),K=e.useCallback(async(s,r,a)=>{const c=await B(s);if(!c)return;const o=await p(),S={...c,status:r,error:a,attempts:r==="syncing"?c.attempts+1:c.attempts,syncedAt:r==="synced"?new Date:c.syncedAt};return new Promise((E,m)=>{const C=o.transaction("drafts","readwrite").objectStore("drafts").put(S);C.onerror=()=>m(C.error),C.onsuccess=()=>{O(),E()}})},[p,B]),F=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const E=r.transaction("drafts","readwrite").objectStore("drafts").delete(s);E.onerror=()=>c(E.error),E.onsuccess=()=>{O(),a()}})},[p]),V=e.useCallback(async s=>{const r=await q(s),a=await p();return new Promise((c,o)=>{const S=a.transaction("drafts","readwrite"),E=S.objectStore("drafts");S.onerror=()=>o(S.error),S.oncomplete=()=>{O(),c()};for(const m of r)E.delete(m.id)})},[p,q]),I=e.useCallback(async s=>{const r=await B(s);if(!r)throw new Error("Draft not found");const a=A.current[r.formId];if(!a)throw new Error(`No handler registered for form: ${r.formId}`);if(!v.isOnline){await K(s,"pending");return}await K(s,"syncing"),d(c=>({...c,isSyncing:!0}));try{await a(r.data,r),await K(s,"synced"),N==null||N(r),await F(s)}catch(c){const o=c instanceof Error?c.message:"Submission failed";await K(s,"failed",o),R==null||R(r,c instanceof Error?c:new Error(o))}finally{d(c=>({...c,isSyncing:!1}))}},[B,v.isOnline,K,F,N,R]),U=e.useCallback(async(s,r)=>{const a=await j(s,r);await K(a,"pending"),await I(a)},[j,K,I]),D=e.useCallback(async()=>{const s=await z(),r={synced:0,failed:0};d(a=>({...a,isSyncing:!0}));for(const a of s)if(!(a.status==="failed"&&a.attempts>=l.maxRetryAttempts))try{await I(a.id),r.synced++}catch{r.failed++}return d(a=>({...a,isSyncing:!1,lastSyncAt:new Date})),G==null||G(r),r},[z,I,l.maxRetryAttempts,G]),P=e.useCallback(async()=>{const r=(await z()).filter(a=>a.status==="failed");for(const a of r)a.attempts<l.maxRetryAttempts&&await K(a.id,"pending");await D()},[z,l.maxRetryAttempts,K,D]),T=e.useCallback((s,r)=>{A.current[s]=r},[]),O=e.useCallback(async()=>{try{const c=(await p()).transaction("drafts","readonly").objectStore("drafts").getAll();c.onsuccess=()=>{const o=c.result,S={};for(const w of o)S[w.formId]=(S[w.formId]||0)+1;const E=o.filter(w=>w.status==="pending").length,m=o.filter(w=>w.status==="failed").length;d(w=>({...w,draftCounts:S,pendingCount:E,failedCount:m}))}}catch{}},[p]);e.useEffect(()=>{const s=()=>{d(a=>({...a,isOnline:!0})),l.autoSubmitOnline&&D()},r=()=>{d(a=>({...a,isOnline:!1}))};return window.addEventListener("online",s),window.addEventListener("offline",r),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",r)}},[l.autoSubmitOnline,D]),e.useEffect(()=>{p().then(()=>O())},[p,O]),e.useImperativeHandle(f,()=>({getState:()=>v,saveDraft:j,getDraft:B,getDrafts:q,getPendingDrafts:z,updateDraft:Y,deleteDraft:F,submitDraft:I,submitForm:U,syncPending:D,retryFailed:P,clearDrafts:V,registerHandler:T}),[v,j,B,q,z,Y,F,I,U,D,P,V,T]);const b={...v,saveDraft:j,getDraft:B,getDrafts:q,getPendingDrafts:z,updateDraft:Y,deleteDraft:F,submitDraft:I,submitForm:U,syncPending:D,retryFailed:P,clearDrafts:V,registerHandler:T};return t.jsx(wt.Provider,{value:b,children:i})});Ie.displayName="NiceOfflineForms";const xt=Ie;xt.displayName="NiceOfflineFormsProvider";function Yn(n){const{formId:f,initialData:h={},autoSave:k=!0,autoSaveInterval:g=5e3,onSubmit:N}=n,R=vt(),[G,i]=e.useState(h),[l,y]=e.useState(),[A,v]=e.useState(!1),[d,p]=e.useState();e.useEffect(()=>{R.registerHandler(f,N)},[R,f,N]),e.useEffect(()=>{if(!k)return;const Y=setInterval(async()=>{if(Object.keys(G).length>0)if(l)await R.updateDraft(l,G);else{const K=await R.saveDraft(f,G);y(K)}},g);return()=>clearInterval(Y)},[k,g,G,l,f,R]);const j=e.useCallback(Y=>{const{name:K,value:F,type:V}=Y.target;i(I=>({...I,[K]:V==="checkbox"?Y.target.checked:F}))},[]),B=e.useCallback(async Y=>{Y==null||Y.preventDefault(),v(!0),p(void 0);try{await R.submitForm(f,G),i(h),y(void 0)}catch(K){p(K instanceof Error?K.message:"Submission failed")}finally{v(!1)}},[R,f,G,h]),q=e.useCallback(()=>{i(h),p(void 0),l&&(R.deleteDraft(l),y(void 0))},[h,l,R]),z=e.useCallback(async Y=>{const K=await R.getDraft(Y);K&&(i(K.data),y(Y))},[R]);return{data:G,setData:i,draftId:l,isSubmitting:A,error:d,isOnline:R.isOnline,isSyncing:R.isSyncing,pendingCount:R.pendingCount,handleChange:j,handleSubmit:B,reset:q,loadDraft:z}}const fe=()=>{const n=navigator;return n.connection?{type:n.connection.type,effectiveType:n.connection.effectiveType,downlink:n.connection.downlink,rtt:n.connection.rtt,saveData:n.connection.saveData}:{}},me=n=>{if(!n.effectiveType)return n.downlink?Math.min(100,n.downlink*10):50;switch(n.effectiveType){case"4g":return 100;case"3g":return 75;case"2g":return 50;case"slow-2g":return 25;default:return 50}},Ct=e.forwardRef((n,f)=>{const{mode:h="banner",position:k="top",showWhenOnline:g=!1,autoHideOnlineDelay:N=3e3,showSlowConnectionWarning:R=!0,slowConnectionThreshold:G=1,showReconnecting:i=!0,reconnectCheckInterval:l=5e3,offlineMessage:y="You're offline",onlineMessage:A="Back online",slowConnectionMessage:v="Slow connection",reconnectingMessage:d="Reconnecting...",showDetails:p=!1,animated:j=!0,pulseWhenOffline:B=!0,offlineIcon:q,onlineIcon:z,slowIcon:Y,renderContent:K,onStatusChange:F,onReconnect:V,className:I,style:U}=n,[D,P]=e.useState(()=>{const $=fe();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...$,quality:me($)}}),[T,O]=e.useState(!D.isOnline||g),[b,s]=e.useState(!1),[r,a]=e.useState(null),c=e.useCallback(()=>{const $=fe(),Z=navigator.onLine;P(J=>{const H={isOnline:Z,...$,quality:Z?me($):0,lastOnlineAt:Z?new Date:J.lastOnlineAt,offlineDuration:!Z&&r?Date.now()-r.getTime():void 0};return(J.isOnline!==H.isOnline||J.quality!==H.quality)&&(F==null||F(H)),H})},[r,F]),o=e.useCallback(async()=>{try{return(await fetch("/favicon.ico",{method:"HEAD",cache:"no-store"})).ok}catch{return!1}},[]);e.useEffect(()=>{const $=()=>{s(!1),a(null),c(),O(!0),V==null||V(),N>0&&setTimeout(()=>{O(g)},N)},Z=()=>{a(new Date),c(),O(!0),s(i)};window.addEventListener("online",$),window.addEventListener("offline",Z);const J=navigator;return J.connection&&J.connection.addEventListener("change",c),()=>{window.removeEventListener("online",$),window.removeEventListener("offline",Z),J.connection&&J.connection.removeEventListener("change",c)}},[c,N,g,i,V]),e.useEffect(()=>{if(!b||D.isOnline)return;const $=setInterval(async()=>{await o()&&window.dispatchEvent(new Event("online"))},l);return()=>clearInterval($)},[b,D.isOnline,l,o]),e.useEffect(()=>{if(D.isOnline||!r)return;const $=setInterval(()=>{P(Z=>({...Z,offlineDuration:Date.now()-r.getTime()}))},1e3);return()=>clearInterval($)},[D.isOnline,r]),e.useImperativeHandle(f,()=>({getConnectionInfo:()=>D,checkConnection:o,show:()=>O(!0),hide:()=>O(!1),toggle:()=>O($=>!$)}),[D,o]);const S=D.isOnline&&R&&D.downlink!==void 0&&D.downlink<G,m=D.isOnline?S?"slow":"online":b?"reconnecting":"offline",w=()=>{switch(m){case"offline":return y;case"reconnecting":return d;case"slow":return v;case"online":return A}},u=$=>({display:"inline-block",width:10,height:10,borderRadius:"50%",background:$}),C=()=>{switch(m){case"offline":case"reconnecting":return q||t.jsx("span",{style:u("var(--nice-color-error, #ef4444)")});case"slow":return Y||t.jsx("span",{style:u("var(--nice-color-warning, #f59e0b)")});case"online":return z||t.jsx("span",{style:u("var(--nice-color-success, #22c55e)")})}},x=$=>{const Z=Math.floor($/1e3);if(Z<60)return`${Z}s`;const J=Math.floor(Z/60);return J<60?`${J}m ${Z%60}s`:`${Math.floor(J/60)}h ${J%60}m`};if(!T||D.isOnline&&!g&&!S)return null;const W=["nice-offline-indicator",`nice-offline-indicator--${h}`,`nice-offline-indicator--${k}`,`nice-offline-indicator--${m}`,j&&"nice-offline-indicator--animated",B&&m==="offline"&&"nice-offline-indicator--pulse",I].filter(Boolean).join(" ");if(K)return t.jsx("div",{className:W,style:U,children:K(D)});const _=()=>t.jsx("span",{className:"nice-offline-indicator__icon",children:C()}),M=()=>t.jsx("span",{className:"nice-offline-indicator__message",children:w()}),L=()=>p?t.jsxs("div",{className:"nice-offline-indicator__details",children:[D.offlineDuration!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__duration",children:["Offline for ",x(D.offlineDuration)]}),D.effectiveType&&t.jsx("span",{className:"nice-offline-indicator__type",children:D.effectiveType.toUpperCase()}),D.downlink!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__speed",children:[D.downlink.toFixed(1)," Mbps"]}),D.rtt!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__latency",children:[D.rtt,"ms"]})]}):null,X=()=>!p||!D.isOnline?null:t.jsx("div",{className:"nice-offline-indicator__quality",children:t.jsx("div",{className:"nice-offline-indicator__quality-bar",style:{width:`${D.quality}%`,backgroundColor:D.quality>=75?"var(--nice-color-success, #22c55e)":D.quality>=50?"var(--nice-color-warning, #eab308)":"var(--nice-color-error, #ef4444)"}})});switch(h){case"icon-only":return t.jsx("div",{className:W,style:U,title:w(),children:_()});case"minimal":return t.jsxs("div",{className:W,style:U,children:[_(),M()]});case"badge":return t.jsxs("div",{className:W,style:U,children:[t.jsx("div",{className:"nice-offline-indicator__badge-dot"}),t.jsx("span",{className:"nice-offline-indicator__badge-text",children:w()})]});case"toast":return t.jsx("div",{className:W,style:U,children:t.jsxs("div",{className:"nice-offline-indicator__toast",children:[_(),t.jsxs("div",{className:"nice-offline-indicator__toast-content",children:[M(),L()]})]})});case"detailed":return t.jsx("div",{className:W,style:U,children:t.jsxs("div",{className:"nice-offline-indicator__detailed",children:[_(),t.jsxs("div",{className:"nice-offline-indicator__detailed-content",children:[M(),L(),X()]})]})});case"banner":default:return t.jsx("div",{className:W,style:U,children:t.jsxs("div",{className:"nice-offline-indicator__banner",children:[_(),M(),p&&t.jsxs(t.Fragment,{children:[L(),b&&t.jsx("span",{className:"nice-offline-indicator__spinner"})]})]})})}});Ct.displayName="NiceOfflineIndicator";function Xn(){const[n,f]=e.useState(()=>{const h=fe();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...h,quality:me(h)}});return e.useEffect(()=>{const h=()=>{const g=fe();f(N=>({...N,isOnline:navigator.onLine,...g,quality:navigator.onLine?me(g):0,lastOnlineAt:navigator.onLine?new Date:N.lastOnlineAt}))};window.addEventListener("online",h),window.addEventListener("offline",h);const k=navigator;return k.connection&&k.connection.addEventListener("change",h),()=>{window.removeEventListener("online",h),window.removeEventListener("offline",h),k.connection&&k.connection.removeEventListener("change",h)}},[]),n}const kt=e.createContext(null),St=()=>{const n=e.useContext(kt);if(!n)throw new Error("useOfflineMedia must be used within NiceOfflineMediaProvider");return n},Kn={dbName:"nice-offline-media",maxCacheSize:500*1024*1024,maxConcurrentDownloads:3,autoResumeOnReconnect:!0,defaultCacheDuration:10080*60*1e3,autoCleanup:!0,cleanupInterval:3600*1e3},Qn=()=>`media-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Jn=(n,f)=>{var g;const h=((g=n.split(".").pop())==null?void 0:g.toLowerCase())||"",k=(f==null?void 0:f.toLowerCase())||"";return k.startsWith("image/")||["jpg","jpeg","png","gif","webp","svg"].includes(h)?"image":k.startsWith("video/")||["mp4","webm","ogg","mov","avi"].includes(h)?"video":k.startsWith("audio/")||["mp3","wav","ogg","flac","m4a"].includes(h)?"audio":["pdf","doc","docx","xls","xlsx","ppt","pptx"].includes(h)?"document":"other"},Zn=n=>{try{return new URL(n).pathname.split("/").pop()||"unknown"}catch{return n.split("/").pop()||"unknown"}},je=e.forwardRef((n,f)=>{const{config:h,onDownloadStart:k,onDownloadProgress:g,onDownloadComplete:N,onDownloadFailed:R,onMediaRemoved:G,children:i}=n,l={...Kn,...h},y=e.useRef(null),A=e.useRef(new Map),v=e.useRef(new Map),[d,p]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,activeDownloads:0,queuedDownloads:0,cachedCount:0,totalCacheSize:0,isDownloading:!1}),j=e.useCallback(async()=>y.current?y.current:new Promise((C,x)=>{const W=indexedDB.open(l.dbName,1);W.onerror=()=>x(W.error),W.onupgradeneeded=()=>{const _=W.result;if(!_.objectStoreNames.contains("media")){const M=_.createObjectStore("media",{keyPath:"id"});M.createIndex("url","url",{unique:!0}),M.createIndex("type","type",{unique:!1}),M.createIndex("status","status",{unique:!1})}_.objectStoreNames.contains("blobs")||_.createObjectStore("blobs",{keyPath:"id"})},W.onsuccess=()=>{y.current=W.result,C(W.result)}}),[l.dbName]),B=e.useCallback(async C=>{const x=await j();return new Promise((W,_)=>{const X=x.transaction("media","readwrite").objectStore("media").put(C);X.onerror=()=>_(X.error),X.onsuccess=()=>W()})},[j]),q=e.useCallback(async(C,x)=>{const W=await j();return new Promise((_,M)=>{const $=W.transaction("blobs","readwrite").objectStore("blobs").put({id:C,blob:x});$.onerror=()=>M($.error),$.onsuccess=()=>_()})},[j]),z=e.useCallback(async C=>{const x=await j();return new Promise((W,_)=>{const X=x.transaction("blobs","readonly").objectStore("blobs").get(C);X.onerror=()=>_(X.error),X.onsuccess=()=>{var $;return W(($=X.result)==null?void 0:$.blob)}})},[j]),Y=e.useCallback(async C=>{const x=await j();return new Promise((W,_)=>{const X=x.transaction("media","readonly").objectStore("media").get(C);X.onerror=()=>_(X.error),X.onsuccess=()=>{const $=X.result;$&&($.cachedAt=$.cachedAt?new Date($.cachedAt):void 0,$.expiresAt=$.expiresAt?new Date($.expiresAt):void 0),W($)}})},[j]),K=e.useCallback(async()=>{const C=await j();return new Promise((x,W)=>{const L=C.transaction("media","readonly").objectStore("media").getAll();L.onerror=()=>W(L.error),L.onsuccess=()=>{x(L.result.map(X=>({...X,cachedAt:X.cachedAt?new Date(X.cachedAt):void 0,expiresAt:X.expiresAt?new Date(X.expiresAt):void 0})))}})},[j]),F=e.useCallback(async C=>{const x=await j();return new Promise((W,_)=>{const $=x.transaction("media","readonly").objectStore("media").index("type").getAll(C);$.onerror=()=>_($.error),$.onsuccess=()=>W($.result)})},[j]),V=e.useCallback(async C=>(await K()).filter(W=>{var _;return(_=W.tags)==null?void 0:_.includes(C)}),[K]),I=e.useCallback(async C=>{const x=await j();return new Promise((W,_)=>{const $=x.transaction("media","readonly").objectStore("media").index("url").get(C);$.onerror=()=>_($.error),$.onsuccess=()=>W($.result)})},[j]),U=e.useCallback(async C=>{const x=await I(C);return(x==null?void 0:x.status)==="completed"},[I]),D=e.useCallback(async C=>{const x=v.current.get(C);if(x)return x;const W=await z(C);if(!W)return;const _=URL.createObjectURL(W);return v.current.set(C,_),_},[z]),P=e.useCallback(async(C,x)=>{var X;const W=await I(C);if((W==null?void 0:W.status)==="completed")return W.id;const _=new AbortController,M=(W==null?void 0:W.id)||Qn(),L={id:M,url:C,type:(x==null?void 0:x.type)||"other",name:(x==null?void 0:x.name)||Zn(C),mimeType:"",size:0,status:"queued",progress:0,downloadedBytes:0,metadata:x==null?void 0:x.metadata,tags:x==null?void 0:x.tags,priority:x==null?void 0:x.priority};A.current.set(M,_),await B(L),k==null||k(L),p($=>({...$,queuedDownloads:$.queuedDownloads+1,isDownloading:!0}));try{L.status="downloading",await B(L),p(se=>({...se,activeDownloads:se.activeDownloads+1,queuedDownloads:se.queuedDownloads-1}));const $=await fetch(C,{signal:_.signal,headers:x==null?void 0:x.headers});if(!$.ok)throw new Error(`HTTP ${$.status}`);const Z=$.headers.get("content-length"),J=$.headers.get("content-type")||"",H=Z?parseInt(Z,10):0;L.size=H,L.mimeType=J,L.type=(x==null?void 0:x.type)||Jn(C,J);const Q=(X=$.body)==null?void 0:X.getReader();if(!Q)throw new Error("No response body");const ee=[];let te=0;for(;;){const{done:se,value:re}=await Q.read();if(se)break;ee.push(re),te+=re.length,L.downloadedBytes=te,L.progress=H>0?Math.round(te/H*100):0,await B(L),g==null||g(L)}const ne=new Blob(ee,{type:J});return await q(M,ne),L.status="completed",L.progress=100,L.size=ne.size,L.cachedAt=new Date,L.expiresAt=x!=null&&x.cacheDuration?new Date(Date.now()+x.cacheDuration):new Date(Date.now()+l.defaultCacheDuration),await B(L),N==null||N(L),M}catch($){throw $.name==="AbortError"?L.status="cancelled":(L.status="failed",L.error=$ instanceof Error?$.message:"Download failed",R==null||R(L,$ instanceof Error?$:new Error(String($)))),await B(L),$}finally{A.current.delete(M),p($=>({...$,activeDownloads:Math.max(0,$.activeDownloads-1),isDownloading:$.activeDownloads>1})),await w()}},[I,B,q,l.defaultCacheDuration,k,g,N,R]),T=e.useCallback(async C=>{const x=[];for(let W=0;W<C.length;W+=l.maxConcurrentDownloads){const _=C.slice(W,W+l.maxConcurrentDownloads),M=await Promise.allSettled(_.map(L=>P(L.url,L.options)));for(const L of M)L.status==="fulfilled"&&x.push(L.value)}return x},[P,l.maxConcurrentDownloads]),O=e.useCallback(C=>{const x=A.current.get(C);x&&x.abort()},[]),b=e.useCallback(async C=>{const x=await Y(C);x&&(x.status==="paused"||x.status==="failed")&&await P(x.url,{type:x.type,name:x.name,metadata:x.metadata,tags:x.tags})},[Y,P]),s=e.useCallback(C=>{O(C)},[O]),r=e.useCallback(()=>{for(const[C]of A.current)O(C)},[O]),a=e.useCallback(async()=>{const x=(await K()).filter(W=>W.status==="paused"||W.status==="failed");await T(x.map(W=>({url:W.url})))},[K,T]),c=e.useCallback(async C=>{const x=await j(),W=v.current.get(C);W&&(URL.revokeObjectURL(W),v.current.delete(C)),await new Promise((_,M)=>{const L=x.transaction(["media","blobs"],"readwrite");L.objectStore("media").delete(C),L.objectStore("blobs").delete(C),L.onerror=()=>M(L.error),L.oncomplete=()=>_()}),G==null||G(C),await w()},[j,G]),o=e.useCallback(async()=>{const C=await j();for(const[,x]of v.current)URL.revokeObjectURL(x);v.current.clear(),await new Promise((x,W)=>{const _=C.transaction(["media","blobs"],"readwrite");_.objectStore("media").clear(),_.objectStore("blobs").clear(),_.onerror=()=>W(_.error),_.oncomplete=()=>x()}),await w()},[j]),S=e.useCallback(async()=>{const C=await K(),x=Date.now();let W=0;for(const _ of C)_.expiresAt&&_.expiresAt.getTime()<x&&(await c(_.id),W++);return W},[K,c]),E=e.useCallback(async()=>{const x=(await K()).filter(M=>M.status==="completed"),W={image:{count:0,size:0},video:{count:0,size:0},audio:{count:0,size:0},document:{count:0,size:0},other:{count:0,size:0}};let _=0;for(const M of x)_+=M.size,W[M.type].count++,W[M.type].size+=M.size;return{totalSize:_,itemCount:x.length,byType:W}},[K]),m=e.useCallback(async C=>{await T(C.map(x=>({url:x,options:{priority:-1}})))},[T]),w=e.useCallback(async()=>{const C=await E();p(x=>({...x,cachedCount:C.itemCount,totalCacheSize:C.totalSize}))},[E]);e.useEffect(()=>{const C=()=>{p(W=>({...W,isOnline:!0})),l.autoResumeOnReconnect&&a()},x=()=>{p(W=>({...W,isOnline:!1})),r()};return window.addEventListener("online",C),window.addEventListener("offline",x),()=>{window.removeEventListener("online",C),window.removeEventListener("offline",x)}},[l.autoResumeOnReconnect,a,r]),e.useEffect(()=>{if(!l.autoCleanup)return;const C=setInterval(()=>{S()},l.cleanupInterval);return()=>clearInterval(C)},[l.autoCleanup,l.cleanupInterval,S]),e.useEffect(()=>{j().then(()=>w());const C=v.current;return()=>{for(const[,x]of C)URL.revokeObjectURL(x)}},[j,w]),e.useImperativeHandle(f,()=>({getState:()=>d,download:P,downloadMultiple:T,getCachedMedia:Y,getAllCachedMedia:K,getMediaByType:F,getMediaByTag:V,getBlobUrl:D,isCached:U,pauseDownload:O,resumeDownload:b,cancelDownload:s,pauseAll:r,resumeAll:a,removeMedia:c,clearCache:o,clearExpired:S,getCacheStats:E,preload:m}),[d,P,T,Y,K,F,V,D,U,O,b,s,r,a,c,o,S,E,m]);const u={...d,download:P,downloadMultiple:T,getCachedMedia:Y,getAllCachedMedia:K,getMediaByType:F,getMediaByTag:V,getBlobUrl:D,isCached:U,pauseDownload:O,resumeDownload:b,cancelDownload:s,removeMedia:c,clearCache:o,preload:m};return t.jsx(kt.Provider,{value:u,children:i})});je.displayName="NiceOfflineMedia";const _t=je;_t.displayName="NiceOfflineMediaProvider";function es(n){const f=St(),[h,k]=e.useState(),[g,N]=e.useState(),[R,G]=e.useState(!1);return e.useEffect(()=>{n&&(G(!0),Promise.all([f.getCachedMedia(n),f.getBlobUrl(n)]).then(([i,l])=>{k(i),N(l)}).finally(()=>{G(!1)}))},[n,f]),{item:h,blobUrl:g,isLoading:R,isOnline:f.isOnline}}const Nt=e.createContext(null),ts=()=>{const n=e.useContext(Nt);if(!n)throw new Error("useServiceWorker must be used within NiceServiceWorkerProvider");return n},ns={swPath:"/service-worker.js",scope:"/",updateCheckInterval:6e4,autoUpdate:!1,skipWaiting:!1,reloadOnActivation:!0},Ae=e.forwardRef((n,f)=>{const{config:h,showUpdateNotification:k=!0,showOfflineIndicator:g=!0,renderUpdateNotification:N,renderOfflineIndicator:R,notificationPosition:G="bottom",autoDismissDelay:i=0,onRegistered:l,onUpdateAvailable:y,onActivated:A,onError:v,onOnlineStatusChange:d,children:p,className:j}=n,B={...ns,...h},{swPath:q,scope:z,updateCheckInterval:Y,autoUpdate:K,reloadOnActivation:F}=B,V=B.skipWaiting,I=e.useMemo(()=>({swPath:q,scope:z,updateCheckInterval:Y,autoUpdate:K,skipWaiting:V,reloadOnActivation:F}),[q,z,Y,K,V,F]),U=e.useRef({onRegistered:l,onUpdateAvailable:y,onActivated:A,onError:v});e.useEffect(()=>{U.current={onRegistered:l,onUpdateAvailable:y,onActivated:A,onError:v}});const[D,P]=e.useState({status:"idle",updateAvailable:!1,waitingWorker:!1,cachedUrls:[],caches:[],isOnline:typeof navigator<"u"?navigator.onLine:!0}),[T,O]=e.useState(!1);e.useEffect(()=>{const _=()=>{P(L=>({...L,isOnline:!0})),d==null||d(!0)},M=()=>{P(L=>({...L,isOnline:!1})),d==null||d(!1)};return window.addEventListener("online",_),window.addEventListener("offline",M),()=>{window.removeEventListener("online",_),window.removeEventListener("offline",M)}},[d]);const b=e.useCallback(async()=>{if(!("caches"in window))return[];const _=await caches.keys(),M=[];for(const L of _){const X=await caches.open(L),$=await X.keys();let Z=0;for(const J of $){const H=await X.match(J);if(H){const Q=await H.clone().blob();Z+=Q.size}}M.push({name:L,size:Z,itemCount:$.length})}return P(L=>({...L,caches:M})),M},[]),s=e.useCallback(async _=>{if(!("caches"in window))return!1;const M=await caches.delete(_);return await b(),M},[b]),r=e.useCallback(async()=>{if(!("caches"in window))return;const _=await caches.keys();await Promise.all(_.map(M=>caches.delete(M))),P(M=>({...M,caches:[],cachedUrls:[]}))},[]),a=e.useCallback(async(_,M)=>{if(!("caches"in window))return;await(await caches.open(_)).addAll(M),await b()},[b]),c=e.useCallback(async(_,M)=>{if(!("caches"in window))return!1;const X=await(await caches.open(_)).delete(M);return await b(),X},[b]),o=e.useCallback(async _=>"caches"in window?(await(await caches.open(_)).keys()).map(X=>X.url):[],[]),S=e.useCallback(async()=>{var M,L,X,$,Z,J;if(!("serviceWorker"in navigator)){P(H=>({...H,status:"error",error:"Service Worker not supported"}));return}P(H=>({...H,status:"registering"}));const _=!!navigator.serviceWorker.controller;try{const H=await navigator.serviceWorker.register(I.swPath,{scope:I.scope});P(ee=>({...ee,status:"registered",registration:H})),(L=(M=U.current).onRegistered)==null||L.call(M,H),H.addEventListener("updatefound",()=>{const ee=H.installing;ee&&ee.addEventListener("statechange",()=>{var te,ne,se,re;switch(ee.state){case"installing":P(ae=>({...ae,status:"installing"}));break;case"installed":navigator.serviceWorker.controller?(P(ae=>({...ae,status:"installed",updateAvailable:!0,waitingWorker:!0})),O(!0),(ne=(te=U.current).onUpdateAvailable)==null||ne.call(te)):P(ae=>({...ae,status:"installed"}));break;case"activating":P(ae=>({...ae,status:"activating"}));break;case"activated":P(ae=>({...ae,status:"activated",updateAvailable:!1,waitingWorker:!1})),(re=(se=U.current).onActivated)==null||re.call(se),I.reloadOnActivation&&_&&window.location.reload();break;case"redundant":P(ae=>({...ae,status:"redundant"}));break}})}),H.waiting&&(P(ee=>({...ee,updateAvailable:!0,waitingWorker:!0})),O(!0),($=(X=U.current).onUpdateAvailable)==null||$.call(X));let Q=!1;return navigator.serviceWorker.addEventListener("controllerchange",()=>{!Q&&I.reloadOnActivation&&(Q=!0,window.location.reload())}),await b(),H}catch(H){const Q=H instanceof Error?H.message:"Registration failed";P(ee=>({...ee,status:"error",error:Q})),(J=(Z=U.current).onError)==null||J.call(Z,H instanceof Error?H:new Error(Q));return}},[I,b]),E=e.useCallback(async()=>{if(!D.registration)return!1;const _=await D.registration.unregister();return _&&P(M=>({...M,status:"idle",registration:void 0,updateAvailable:!1,waitingWorker:!1})),_},[D.registration]),m=e.useCallback(async()=>{D.registration&&await D.registration.update()},[D.registration]),w=e.useCallback(()=>{var _;(_=D.registration)!=null&&_.waiting&&D.registration.waiting.postMessage({type:"SKIP_WAITING"})},[D.registration]),u=e.useCallback(()=>{I.skipWaiting&&w(),O(!1)},[I.skipWaiting,w]),C=e.useCallback(()=>{window.location.reload()},[]);e.useEffect(()=>{S()},[S]),e.useEffect(()=>{if(!I.updateCheckInterval||I.updateCheckInterval<=0)return;const _=setInterval(()=>{m()},I.updateCheckInterval);return()=>clearInterval(_)},[I.updateCheckInterval,m]),e.useEffect(()=>{if(!T||i<=0)return;const _=setTimeout(()=>{O(!1)},i);return()=>clearTimeout(_)},[T,i]),e.useImperativeHandle(f,()=>({getState:()=>D,register:S,unregister:E,checkForUpdates:m,applyUpdate:u,skipWaiting:w,getCachesInfo:b,clearCache:s,clearAllCaches:r,addToCache:a,removeFromCache:c,getCachedUrls:o,forceReload:C}),[D,S,E,m,u,w,b,s,r,a,c,o,C]);const x={...D,register:S,unregister:E,checkForUpdates:m,applyUpdate:u,skipWaiting:w,getCachesInfo:b,clearCache:s,clearAllCaches:r,addToCache:a,removeFromCache:c,getCachedUrls:o},W=`nice-sw-notification--${G}`;return t.jsx(Nt.Provider,{value:x,children:t.jsxs("div",{className:`nice-service-worker ${j||""}`,children:[p,k&&T&&D.updateAvailable&&t.jsx("div",{className:`nice-sw-notification ${W}`,children:N?N({onUpdate:u,onDismiss:()=>O(!1)}):t.jsxs("div",{className:"nice-sw-notification__content",children:[t.jsxs("div",{className:"nice-sw-notification__text",children:[t.jsx("strong",{children:"Update Available"}),t.jsx("span",{children:"A new version is ready to install"})]}),t.jsxs("div",{className:"nice-sw-notification__actions",children:[t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--primary",onClick:u,children:"Update Now"}),t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--secondary",onClick:()=>O(!1),children:"Later"})]})]})}),g&&!D.isOnline&&t.jsx("div",{className:`nice-sw-offline ${W}`,children:R?R({isOnline:D.isOnline}):t.jsx("div",{className:"nice-sw-offline__content",children:t.jsx("span",{children:"You are offline"})})})]})})});Ae.displayName="NiceServiceWorker";const It=e.forwardRef((n,f)=>t.jsx(Ae,{...n,ref:f}));It.displayName="NiceServiceWorkerProvider";exports.NiceAutoStart=ge;exports.NiceAutoStartProvider=Fe;exports.NiceBackgroundSync=ke;exports.NiceBackgroundSyncProvider=ut;exports.NiceBarcodeScanner=st;exports.NiceBatchScanner=at;exports.NiceBatchScannerProvider=vn;exports.NiceCacheStrategies=Se;exports.NiceCacheStrategiesProvider=mt;exports.NiceConflictResolution=_e;exports.NiceConflictResolutionProvider=gt;exports.NiceExternalDisplay=pe;exports.NiceExternalDisplayProvider=qe;exports.NiceHardwareBarcodeGenerator=nt;exports.NiceHardwareQRGenerator=it;exports.NiceIndexedDB=Ne;exports.NiceIndexedDBProvider=bt;exports.NiceKioskMode=ye;exports.NiceKioskModeProvider=We;exports.NiceLowPowerMode=be;exports.NiceLowPowerModeProvider=ze;exports.NiceOfflineForms=Ie;exports.NiceOfflineFormsProvider=xt;exports.NiceOfflineIndicator=Ct;exports.NiceOfflineMedia=je;exports.NiceOfflineMediaProvider=_t;exports.NiceOrientationLock=we;exports.NiceOrientationLockProvider=Xe;exports.NiceQRScanner=ct;exports.NiceRemoteManagement=ve;exports.NiceRemoteManagementProvider=Qe;exports.NiceScreenBurnPrevention=Je;exports.NiceScreenSelector=Ue;exports.NiceServiceWorker=Ae;exports.NiceServiceWorkerProvider=It;exports.NiceSymbologyConfig=ot;exports.NiceSymbologyProvider=En;exports.NiceTouchCalibration=Ze;exports.useAutoStart=Dt;exports.useBackgroundSync=Pn;exports.useBatchScanner=gn;exports.useCacheStrategies=ft;exports.useCachedFetch=Fn;exports.useConflictResolution=Bn;exports.useConnectionStatus=Xn;exports.useExternalDisplay=$e;exports.useIndexedDB=yt;exports.useIndexedDBStore=Vn;exports.useKioskMode=Mt;exports.useLowPowerMode=Bt;exports.useOfflineForm=Yn;exports.useOfflineForms=vt;exports.useOfflineMedia=St;exports.useOfflineMediaItem=es;exports.useOrientationLock=Ut;exports.useRemoteManagement=zt;exports.useServiceWorker=ts;exports.useSymbology=Dn;
|