@nice2dev/ui-platform 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var 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}">
1
+ "use strict";var yt=Object.defineProperty;var wt=(n,f,h)=>f in n?yt(n,f,{enumerable:!0,configurable:!0,writable:!0,value:h}):n[f]=h;var oe=(n,f,h)=>wt(n,typeof f!="symbol"?f+"":f,h);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("react"),ue=e.createContext(null),vt=()=>{const n=e.useContext(ue);if(!n)throw new Error("useAutoStart must be used within NiceAutoStartProvider");return n},xt={showSplash:!0,splashDuration:2e3,autoHideSplash:!0,showProgress:!0,showTaskNames:!0,globalTimeout:6e4,autoRecovery:!0,recoveryAttempts:3,recoveryDelay:2e3,checkUpdates:!1,sendAnalytics:!1},_e=Object.assign(e.forwardRef((n,f)=>{const{tasks:h=[],config:k,splash:g,errorScreen:N,onComplete:R,onTaskComplete:G,onError:i,onRecovery:l,children:b}=n,E={...xt,...k},v=e.useRef(0),d=e.useRef(h),p=e.useRef(null),[I,B]=e.useState(E.showSplash),[q,z]=e.useState({phase:"initializing",isLoading:!0,isReady:!1,hasError:!1,progress:0,completedTasks:0,totalTasks:h.length,results:[],recoveryAttempt:0,totalDuration:0}),Y=e.useCallback(async s=>{const r=Date.now();let a=0;const c=async()=>{try{const o=s.timeout||E.globalTimeout,S=new Promise((A,m)=>{setTimeout(()=>m(new Error("Task timeout")),o)});return await Promise.race([s.execute(),S]),{taskId:s.id,success:!0,duration:Date.now()-r,retriesUsed:a}}catch(o){const S=s.retries??0;return a<S?(a++,await new Promise(A=>setTimeout(A,500)),c()):{taskId:s.id,success:!1,error:o instanceof Error?o:new Error(String(o)),duration:Date.now()-r,retriesUsed:a}}};return c()},[E.globalTimeout]),K=e.useCallback(s=>{const r=[],a=[...s],c=new Set;for(;a.length>0;){const o=a.filter(A=>A.dependencies?A.dependencies.every(m=>c.has(m)):!0);if(o.length===0){r.push(...a);break}o.sort((A,m)=>(m.priority??0)-(A.priority??0));const S=o[0];r.push(S),c.add(S.id),a.splice(a.indexOf(S),1)}return r},[]),F=e.useCallback(async()=>{v.current=Date.now();const s=new AbortController;p.current=s;const r=K(d.current),a=[];z(o=>({...o,phase:"loading",isLoading:!0,isReady:!1,hasError:!1,errorMessage:void 0,progress:0,completedTasks:0,totalTasks:r.length,results:[]}));for(let o=0;o<r.length;o++){if(s.signal.aborted)return;const S=r[o];z(m=>({...m,currentTask:S.name,progress:Math.round(o/r.length*100)}));const A=await Y(S);if(s.signal.aborted)return;if(a.push(A),z(m=>({...m,completedTasks:o+1,results:[...m.results,A]})),G==null||G(A),!A.success&&S.critical){const m=A.error||new Error("Critical task failed");i==null||i(m,S.id),z(w=>({...w,phase:"error",isLoading:!1,hasError:!0,errorMessage:m.message}));return}}const c=Date.now()-v.current;if(z(o=>({...o,phase:"ready",isLoading:!1,isReady:!0,currentTask:void 0,progress:100,totalDuration:c})),R==null||R(a),E.autoHideSplash){const o=Date.now()-v.current,S=Math.max(0,E.splashDuration-o);setTimeout(()=>{B(!1)},S)}},[K,Y,E.autoHideSplash,E.splashDuration,G,i,R]),W=e.useCallback(async()=>{p.current&&p.current.abort(),z(s=>({...s,recoveryAttempt:0})),B(E.showSplash),await F()},[E.showSplash,F]),j=e.useCallback(()=>{p.current&&p.current.abort(),z(s=>({...s,phase:"ready",isLoading:!1,isReady:!0,progress:100})),B(!1)},[]),U=e.useCallback(()=>{B(!1)},[]),D=e.useCallback(async()=>{const s=q.recoveryAttempt+1;s>E.recoveryAttempts||(z(r=>({...r,phase:"recovery",recoveryAttempt:s})),l==null||l(s),await new Promise(r=>setTimeout(r,E.recoveryDelay)),await F())},[q.recoveryAttempt,E.recoveryAttempts,E.recoveryDelay,l,F]),P=e.useCallback(s=>{d.current=[...d.current,s]},[]),T=e.useCallback(s=>{d.current=d.current.filter(r=>r.id!==s)},[]),O=e.useCallback(s=>q.results.find(r=>r.taskId===s),[q.results]);e.useEffect(()=>{q.hasError&&E.autoRecovery&&q.recoveryAttempt<E.recoveryAttempts&&D()},[q.hasError,E.autoRecovery,E.recoveryAttempts,q.recoveryAttempt,D]),e.useEffect(()=>(F(),()=>{p.current&&p.current.abort()}),[]),e.useImperativeHandle(f,()=>({getState:()=>q,restart:W,skip:j,addTask:P,removeTask:T,getTaskResult:O,hideSplash:U,recover:D}),[q,W,j,P,T,O,U,D]);const y={...q,restart:W,skip:j,hideSplash:U};return q.hasError&&q.recoveryAttempt>=E.recoveryAttempts?t.jsx(ue.Provider,{value:y,children:N||t.jsxs("div",{className:"nice-auto-start__error",children:[t.jsx("div",{className:"nice-auto-start__error-icon","aria-hidden":"true",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert"})}),t.jsx("h2",{className:"nice-auto-start__error-title",children:"Startup Failed"}),t.jsx("p",{className:"nice-auto-start__error-message",children:q.errorMessage}),t.jsx("button",{className:"nice-auto-start__error-retry",onClick:W,children:"Retry"})]})}):I&&!q.isReady?t.jsx(ue.Provider,{value:y,children:g||t.jsx("div",{className:"nice-auto-start__splash",children:t.jsxs("div",{className:"nice-auto-start__splash-content",children:[t.jsx("div",{className:"nice-auto-start__splash-logo","aria-hidden":"true"}),t.jsx("h1",{className:"nice-auto-start__splash-title",children:"Loading..."}),E.showProgress&&t.jsx("div",{className:"nice-auto-start__splash-progress",children:t.jsx("div",{className:"nice-auto-start__splash-progress-bar",style:{width:`${q.progress}%`}})}),E.showTaskNames&&q.currentTask&&t.jsx("div",{className:"nice-auto-start__splash-task",children:q.currentTask}),q.phase==="recovery"&&t.jsxs("div",{className:"nice-auto-start__splash-recovery",children:["Recovery attempt ",q.recoveryAttempt," of ",E.recoveryAttempts]})]})})}):t.jsx(ue.Provider,{value:y,children:b})}),{displayName:"NiceAutoStart"}),Ne=_e;process.env.NODE_ENV!=="production"&&(Ne.displayName="NiceAutoStartProvider");const je=e.createContext(null),Ie=()=>{const n=e.useContext(je);if(!n)throw new Error("useExternalDisplay must be used within NiceExternalDisplayProvider");return n},Ct={autoDetect:!0,pollInterval:2e3,defaultFeatures:{resizable:!0,scrollbars:!0},allowMultiWindow:!0,syncContent:!1},kt=()=>typeof window>"u"?!1:"getScreenDetails"in window,St=()=>`window-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,_t=n=>{const f=[];return n.width!==void 0&&f.push(`width=${n.width}`),n.height!==void 0&&f.push(`height=${n.height}`),n.left!==void 0&&f.push(`left=${n.left}`),n.top!==void 0&&f.push(`top=${n.top}`),n.menubar!==void 0&&f.push(`menubar=${n.menubar?"yes":"no"}`),n.toolbar!==void 0&&f.push(`toolbar=${n.toolbar?"yes":"no"}`),n.location!==void 0&&f.push(`location=${n.location?"yes":"no"}`),n.status!==void 0&&f.push(`status=${n.status?"yes":"no"}`),n.resizable!==void 0&&f.push(`resizable=${n.resizable?"yes":"no"}`),n.scrollbars!==void 0&&f.push(`scrollbars=${n.scrollbars?"yes":"no"}`),f.join(",")},be=()=>{var f;if(typeof window>"u")return{id:"primary",label:"Primary Display",width:0,height:0,availWidth:0,availHeight:0,left:0,top:0,devicePixelRatio:1,isPrimary:!0,orientation:"landscape-primary",colorDepth:24};const n=window.screen;return{id:"primary",label:"Primary Display",width:n.width,height:n.height,availWidth:n.availWidth,availHeight:n.availHeight,left:n.availLeft||0,top:n.availTop||0,devicePixelRatio:window.devicePixelRatio,isPrimary:!0,orientation:((f=n.orientation)==null?void 0:f.type)||"landscape-primary",colorDepth:n.colorDepth}},Nt=async()=>{try{return(await navigator.permissions.query({name:"window-management"})).state}catch{return"unknown"}},ye=async()=>(await window.getScreenDetails()).screens.map((f,h)=>{var k;return{id:`screen-${h}`,label:f.label||`Display ${h+1}`,width:f.width,height:f.height,availWidth:f.availWidth,availHeight:f.availHeight,left:f.left,top:f.top,devicePixelRatio:f.devicePixelRatio,isPrimary:f.isPrimary,isInternal:f.isInternal,orientation:((k=f.orientation)==null?void 0:k.type)||"landscape-primary",colorDepth:f.colorDepth}}),we=(n,f)=>JSON.stringify(n)===JSON.stringify(f),Ee=Object.assign(e.forwardRef((n,f)=>{const{config:h,onScreensChange:k,onWindowOpen:g,onWindowClose:N,onPermissionChange:R,children:G}=n,i={...Ct,...h},l=e.useRef(new Map),b=e.useRef(null),[E,v]=e.useState([be()]),[d,p]=e.useState([]),[I,B]=e.useState("unknown"),[q]=e.useState(kt),z=e.useRef(k),Y=e.useRef(R);e.useEffect(()=>{z.current=k,Y.current=R});const K=e.useRef([]),F=e.useCallback(m=>{var w;v(u=>we(u,m)?u:m),we(K.current,m)||(K.current=m,(w=z.current)==null||w.call(z,m))},[]),W=e.useRef("unknown"),j=e.useCallback(m=>{var w;W.current!==m&&(W.current=m,B(m),(w=Y.current)==null||w.call(Y,m))},[]),U=e.useCallback(async()=>{if(q){const w=await Nt();if(j(w),w==="granted")try{const u=await ye();return F(u),u}catch{}}const m=[be()];return F(m),m},[q,j,F]),D=e.useCallback(async()=>{if(!q)return j("denied"),!1;try{return F(await ye()),j("granted"),!0}catch(m){return j(m instanceof DOMException&&m.name==="NotAllowedError"?"denied":"unknown"),!1}},[q,j,F]),P=e.useCallback(async(m,w="about:blank",u={})=>{if(!i.allowMultiWindow&&d.length>0)return console.warn("Multi-window mode is disabled"),null;const C=St(),x={...i.defaultFeatures,...u,width:u.width??m.availWidth,height:u.height??m.availHeight,left:u.left??m.left,top:u.top??m.top},H=_t(x),_={window:null,screen:m,id:C,state:"opening",isFullscreen:!1,features:x};p(M=>[...M,_]);try{const M=window.open(w,C,H);if(!M)return p($=>$.map(Z=>Z.id===C?{...Z,state:"error"}:Z)),null;l.current.set(C,M);const L={..._,window:M,state:"open"};p($=>$.map(Z=>Z.id===C?L:Z));const X=setInterval(()=>{M.closed&&(clearInterval(X),l.current.delete(C),p($=>$.filter(Z=>Z.id!==C)),N==null||N(L))},500);return x.fullscreen&&M.addEventListener("load",()=>{var $,Z;(Z=($=M.document.documentElement).requestFullscreen)==null||Z.call($)}),g==null||g(L),L}catch(M){return console.error("Failed to open window:",M),p(L=>L.map(X=>X.id===C?{...X,state:"error"}:X)),null}},[i.allowMultiWindow,i.defaultFeatures,d.length,g,N]),T=e.useCallback(m=>{const w=l.current.get(m);w&&!w.closed&&w.close(),l.current.delete(m),p(u=>u.filter(C=>C.id!==m))},[]),O=e.useCallback(()=>{for(const[m,w]of l.current)w.closed||w.close(),l.current.delete(m);p([])},[]),y=e.useCallback((m,w)=>{const u=l.current.get(m);u&&!u.closed&&(u.moveTo(w.left,w.top),u.resizeTo(w.availWidth,w.availHeight),p(C=>C.map(x=>x.id===m?{...x,screen:w}:x)))},[]),s=e.useCallback(async m=>{const w=l.current.get(m);if(!w||w.closed)return!1;try{const u=!!w.document.fullscreenElement;return u?await w.document.exitFullscreen():await w.document.documentElement.requestFullscreen(),p(C=>C.map(x=>x.id===m?{...x,isFullscreen:!u}:x)),!0}catch{return!1}},[]),r=e.useCallback((m,w)=>{const u=l.current.get(m);u&&!u.closed&&u.postMessage(w,"*")},[]),a=e.useCallback(m=>{for(const w of l.current.values())w.closed||w.postMessage(m,"*")},[]);e.useEffect(()=>{i.autoDetect&&U()},[i.autoDetect,U]),e.useEffect(()=>(i.autoDetect&&i.pollInterval>0&&(b.current=setInterval(U,i.pollInterval)),()=>{b.current&&clearInterval(b.current)}),[i.autoDetect,i.pollInterval,U]),e.useEffect(()=>{if(!q)return;const m=()=>{U()};return window.addEventListener("screenschange",m),()=>{window.removeEventListener("screenschange",m)}},[q,U]),e.useEffect(()=>()=>{O()},[O]);const c=E.find(m=>m.isPrimary)||null,o=E.filter(m=>!m.isPrimary),S={screens:E,primaryScreen:c,externalScreens:o,windows:d,isApiAvailable:q,permissionState:I};e.useImperativeHandle(f,()=>({getState:()=>S,requestPermission:D,getScreens:U,openWindow:P,closeWindow:T,closeAllWindows:O,moveWindowToScreen:y,toggleFullscreen:s,sendMessage:r,broadcast:a}),[S,D,U,P,T,O,y,s,r,a]);const A={...S,requestPermission:D,openWindow:P,closeWindow:T,moveWindowToScreen:y};return t.jsx(je.Provider,{value:A,children:t.jsx("div",{className:"nice-external-display",children:G})})}),{displayName:"NiceExternalDisplay"}),De=Ee;process.env.NODE_ENV!=="production"&&(De.displayName="NiceExternalDisplayProvider");const Ae=({onSelect:n,selectedId:f,showPreview:h=!0,className:k})=>{const{screens:g,primaryScreen:N}=Ie(),R=b=>{n==null||n(b)},i=(()=>{let b=0,E=0,v=0,d=0;for(const p of g)b=Math.min(b,p.left),E=Math.min(E,p.top),v=Math.max(v,p.left+p.width),d=Math.max(d,p.top+p.height);return{minX:b,minY:E,maxX:v,maxY:d,width:v-b,height:d-E}})(),l=Math.min(280/i.width,160/i.height,1);return t.jsxs("div",{className:`nice-screen-selector ${k||""}`,children:[h&&t.jsx("div",{className:"nice-screen-selector__preview",style:{width:i.width*l,height:i.height*l},children:g.map(b=>t.jsx("button",{className:`nice-screen-selector__screen ${f===b.id?"nice-screen-selector__screen--selected":""} ${b.isPrimary?"nice-screen-selector__screen--primary":""}`,style:{left:(b.left-i.minX)*l,top:(b.top-i.minY)*l,width:b.width*l,height:b.height*l},onClick:()=>R(b),title:b.label,children:t.jsx("span",{className:"nice-screen-selector__screen-label",children:b.isPrimary?"P":g.indexOf(b)+1})},b.id))}),t.jsx("div",{className:"nice-screen-selector__list",children:g.map(b=>t.jsxs("button",{className:`nice-screen-selector__item ${f===b.id?"nice-screen-selector__item--selected":""}`,onClick:()=>R(b),children:[t.jsx("span",{className:"nice-screen-selector__item-name",children:b.label}),t.jsxs("span",{className:"nice-screen-selector__item-resolution",children:[b.width," × ",b.height]}),b.isPrimary&&t.jsx("span",{className:"nice-screen-selector__item-badge",children:"Primary"})]},b.id))})]})};process.env.NODE_ENV!=="production"&&(Ae.displayName="NiceScreenSelector");const Pe=e.createContext(null),jt=()=>{const n=e.useContext(Pe);if(!n)throw new Error("useKioskMode must be used within NiceKioskModeProvider");return n},It={autoFullscreen:!0,lockNavigation:!0,disableContextMenu:!0,disableShortcuts:!0,disableSelection:!0,disableCopyPaste:!0,exitPin:"1234",exitShortcut:"ctrl+shift+k",adminTapCount:5,adminTapTimeout:2e3,inactivityTimeout:300*1e3,showCursor:!0,allowScrolling:!0,className:""},Le=Object.assign(e.forwardRef((n,f)=>{const{config:h,children:k,screensaver:g,adminPanel:N,onModeChange:R,onFullscreenChange:G,onAdminAccess:i,onInactivity:l,onActivity:b,onExitRequest:E}=n,v={...It,...h},d=e.useRef(null),p=e.useRef(null),I=e.useRef({count:0,timer:null}),[B,q]=e.useState({mode:"windowed",isFullscreen:!1,isLocked:!1,isAdminMode:!1,isScreensaverActive:!1,idleTime:0,isPinDialogOpen:!1}),[z,Y]=e.useState(""),[K,F]=e.useState(!1),W=e.useCallback(async()=>{const u=d.current;if(u)try{u.requestFullscreen?await u.requestFullscreen():u.webkitRequestFullscreen?await u.webkitRequestFullscreen():u.msRequestFullscreen&&await u.msRequestFullscreen()}catch(C){console.warn("Failed to enter fullscreen:",C)}},[]),j=e.useCallback(async()=>{try{document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen?await document.webkitExitFullscreen():document.msExitFullscreen&&await document.msExitFullscreen()}catch(u){console.warn("Failed to exit fullscreen:",u)}},[]),U=e.useCallback(async()=>{B.isFullscreen?await j():await W()},[B.isFullscreen,W,j]),D=e.useCallback(()=>{q(u=>({...u,mode:"locked",isLocked:!0,isAdminMode:!1})),R==null||R("locked")},[R]),P=e.useCallback(u=>v.exitPin&&u!==v.exitPin?(F(!0),setTimeout(()=>F(!1),1e3),!1):(q(C=>({...C,mode:C.isFullscreen?"fullscreen":"windowed",isLocked:!1,isPinDialogOpen:!1})),Y(""),!0),[v.exitPin]),T=e.useCallback(()=>{q(u=>({...u,isAdminMode:!0})),i==null||i()},[i]),O=e.useCallback(()=>{q(u=>({...u,isAdminMode:!1}))},[]),y=e.useCallback(()=>{I.current.timer&&clearTimeout(I.current.timer),I.current.count++,I.current.count>=v.adminTapCount?(I.current.count=0,T()):I.current.timer=setTimeout(()=>{I.current.count=0},v.adminTapTimeout)},[v.adminTapCount,v.adminTapTimeout,T]),s=e.useCallback(()=>{p.current&&clearTimeout(p.current),B.isScreensaverActive&&(q(u=>({...u,isScreensaverActive:!1})),b==null||b()),v.inactivityTimeout>0&&(p.current=setTimeout(()=>{q(u=>({...u,isScreensaverActive:!0})),l==null||l()},v.inactivityTimeout))},[v.inactivityTimeout,B.isScreensaverActive,b,l]),r=e.useCallback(()=>{q(u=>({...u,isScreensaverActive:!0}))},[]),a=e.useCallback(()=>{q(u=>({...u,isScreensaverActive:!1})),s()},[s]),c=e.useCallback(()=>{q(u=>({...u,isPinDialogOpen:!0})),Y(""),F(!1)},[]),o=e.useCallback(()=>{q(u=>({...u,isPinDialogOpen:!1})),Y(""),F(!1)},[]),S=e.useCallback(()=>{P(z)},[z,P]),A=e.useCallback(u=>{u.key==="Enter"&&S()},[S]);e.useEffect(()=>{const u=()=>{const C=!!document.fullscreenElement;q(x=>({...x,mode:x.isLocked?"locked":C?"fullscreen":"windowed",isFullscreen:C})),G==null||G(C)};return document.addEventListener("fullscreenchange",u),document.addEventListener("webkitfullscreenchange",u),()=>{document.removeEventListener("fullscreenchange",u),document.removeEventListener("webkitfullscreenchange",u)}},[G]),e.useEffect(()=>{if(!v.disableContextMenu)return;const u=C=>{B.isAdminMode||C.preventDefault()};return document.addEventListener("contextmenu",u),()=>document.removeEventListener("contextmenu",u)},[v.disableContextMenu,B.isAdminMode]),e.useEffect(()=>{const u=async C=>{const H=v.exitShortcut.toLowerCase().split("+"),_=H.includes("ctrl")===C.ctrlKey,M=H.includes("shift")===C.shiftKey,L=H.includes("alt")===C.altKey,X=H.some($=>$===C.key.toLowerCase());if(_&&M&&L&&X){C.preventDefault(),(E?await E("keyboard"):!0)&&(B.isLocked?c():j());return}if(v.disableShortcuts&&!B.isAdminMode){const $=["F5","F11","F12"],Z=[{ctrl:!0,key:"r"},{ctrl:!0,key:"w"},{ctrl:!0,key:"n"},{ctrl:!0,key:"t"},{ctrl:!0,shift:!0,key:"i"},{ctrl:!0,shift:!0,key:"j"},{alt:!0,key:"F4"}];if($.includes(C.key)){C.preventDefault();return}for(const J of Z)if(J.ctrl===C.ctrlKey&&(J.shift??!1)===C.shiftKey&&(J.alt??!1)===C.altKey&&J.key.toLowerCase()===C.key.toLowerCase()){C.preventDefault();return}}};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[v.disableShortcuts,v.exitShortcut,B.isAdminMode,B.isLocked,j,c,E]),e.useEffect(()=>{if(!v.disableCopyPaste)return;const u=x=>{B.isAdminMode||x.preventDefault()},C=x=>{B.isAdminMode||x.preventDefault()};return document.addEventListener("copy",u),document.addEventListener("paste",C),()=>{document.removeEventListener("copy",u),document.removeEventListener("paste",C)}},[v.disableCopyPaste,B.isAdminMode]),e.useEffect(()=>{const u=["mousedown","mousemove","keydown","touchstart","scroll"],C=()=>{s()};for(const x of u)document.addEventListener(x,C);return s(),()=>{for(const x of u)document.removeEventListener(x,C);p.current&&clearTimeout(p.current)}},[s]),e.useEffect(()=>{if(v.autoFullscreen){const u=setTimeout(()=>{W()},100);return()=>clearTimeout(u)}},[v.autoFullscreen,W]),e.useImperativeHandle(f,()=>({getState:()=>B,enterFullscreen:W,exitFullscreen:j,toggleFullscreen:U,lock:D,unlock:P,enterAdminMode:T,exitAdminMode:O,resetIdleTimer:s,showScreensaver:r,hideScreensaver:a,openPinDialog:c,closePinDialog:o}),[B,W,j,U,D,P,T,O,s,r,a,c,o]);const m={...B,enterFullscreen:W,exitFullscreen:j,toggleFullscreen:U,lock:D,unlock:P,enterAdminMode:T,exitAdminMode:O,resetIdleTimer:s},w=["nice-kiosk-mode",`nice-kiosk-mode--${B.mode}`,B.isFullscreen&&"nice-kiosk-mode--fullscreen",!v.showCursor&&"nice-kiosk-mode--no-cursor",v.disableSelection&&"nice-kiosk-mode--no-select",!v.allowScrolling&&"nice-kiosk-mode--no-scroll",v.className].filter(Boolean).join(" ");return t.jsx(Pe.Provider,{value:m,children:t.jsxs("div",{ref:d,className:w,onClick:y,children:[t.jsx("div",{className:"nice-kiosk-mode__content",children:k}),B.isAdminMode&&N&&t.jsxs("div",{className:"nice-kiosk-mode__admin",children:[t.jsxs("div",{className:"nice-kiosk-mode__admin-header",children:[t.jsx("h2",{className:"nice-kiosk-mode__admin-title",children:"Admin Mode"}),t.jsx("button",{className:"nice-kiosk-mode__admin-close",onClick:O,"aria-label":"Close admin panel",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-kiosk-mode__admin-content",children:N})]}),B.isScreensaverActive&&t.jsx("div",{className:"nice-kiosk-mode__screensaver",onClick:a,onTouchStart:a,children:g||t.jsx("div",{className:"nice-kiosk-mode__screensaver-default",children:t.jsx("div",{className:"nice-kiosk-mode__screensaver-text",children:"Touch to continue"})})}),B.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__pin-overlay",children:t.jsxs("div",{className:"nice-kiosk-mode__pin-dialog",children:[t.jsx("h3",{className:"nice-kiosk-mode__pin-title",children:"Enter PIN"}),t.jsx("input",{type:"password",className:`nice-kiosk-mode__pin-input ${K?"nice-kiosk-mode__pin-input--error":""}`,value:z,onChange:u=>Y(u.target.value),onKeyPress:A,maxLength:8,autoFocus:!0,placeholder:"••••"}),t.jsxs("div",{className:"nice-kiosk-mode__pin-buttons",children:[t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--cancel",onClick:o,children:"Cancel"}),t.jsx("button",{className:"nice-kiosk-mode__pin-btn nice-kiosk-mode__pin-btn--submit",onClick:S,children:"Unlock"})]}),K&&t.jsx("div",{className:"nice-kiosk-mode__pin-error",children:"Incorrect PIN"})]})}),B.isLocked&&!B.isPinDialogOpen&&t.jsx("div",{className:"nice-kiosk-mode__lock-indicator",children:t.jsx("span",{className:"nice-kiosk-mode__lock-text",children:"Kiosk Locked"})})]})})}),{displayName:"NiceKioskMode"}),Re=Le;process.env.NODE_ENV!=="production"&&(Re.displayName="NiceKioskModeProvider");const Oe=e.createContext(null),Et=()=>{const n=e.useContext(Oe);if(!n)throw new Error("useLowPowerMode must be used within NiceLowPowerModeProvider");return n},Dt={normal:{mode:"normal",brightness:1,wakeOnTouch:!0},dim:{mode:"dim",brightness:.6,disableAnimations:!1,wakeOnTouch:!0},low:{mode:"low",brightness:.3,frameRateCap:30,disableAnimations:!0,reduceImageQuality:!0,wakeOnTouch:!0},sleep:{mode:"sleep",brightness:0,frameRateCap:1,disableAnimations:!0,disableBackgroundProcesses:!0,reduceImageQuality:!0,wakeOnTouch:!0,wakeOnMotion:!0}},At={initialMode:"normal",autoDimTimeout:120*1e3,autoSleepTimeout:600*1e3,lowBatteryThreshold:20,criticalBatteryThreshold:5,wakeOnTouch:!0,wakeOnMotion:!1,transitionDuration:500},Te=Object.assign(e.forwardRef((n,f)=>{const{config:h,onModeChange:k,onBrightnessChange:g,onSleep:N,onWake:R,onLowBattery:G,children:i}=n,l={...At,...h},b={...Dt,...h==null?void 0:h.modes},E=e.useRef(null),v=e.useRef(null),d=e.useRef(Date.now()),p=e.useRef(null),[I,B]=e.useState({currentMode:l.initialMode,brightness:b[l.initialMode].brightness??1,isPowerSaving:l.initialMode!=="normal",isSleeping:l.initialMode==="sleep",idleTime:0,isDisplayOn:!0}),q=e.useCallback(O=>{const y=b[O];document.documentElement.style.setProperty("--lpm-brightness",String(y.brightness)),document.documentElement.style.setProperty("--lpm-transition",`${l.transitionDuration}ms`),y.disableAnimations?document.documentElement.classList.add("nice-lpm-no-animations"):document.documentElement.classList.remove("nice-lpm-no-animations"),y.reduceImageQuality?document.documentElement.classList.add("nice-lpm-reduced-quality"):document.documentElement.classList.remove("nice-lpm-reduced-quality")},[b,l.transitionDuration]),z=e.useCallback(O=>{B(y=>{if(y.currentMode===O)return y;const s=y.currentMode,r=b[O];return q(O),k==null||k(O,s),g==null||g(r.brightness??1),O==="sleep"&&s!=="sleep"?N==null||N():s==="sleep"&&O!=="sleep"&&(R==null||R()),{...y,currentMode:O,brightness:r.brightness??1,isPowerSaving:O!=="normal",isSleeping:O==="sleep",isDisplayOn:O!=="sleep"}})},[b,q,k,g,N,R]),Y=e.useCallback(O=>{const y=Math.max(0,Math.min(1,O));document.documentElement.style.setProperty("--lpm-brightness",String(y)),B(s=>({...s,brightness:y})),g==null||g(y)},[g]),K=e.useCallback(()=>{z("sleep")},[z]),F=e.useCallback(()=>{z("normal"),j()},[z]),W=e.useCallback(()=>{I.currentMode==="normal"?z("low"):z("normal")},[I.currentMode,z]),j=e.useCallback(()=>{if(d.current=Date.now(),E.current&&clearTimeout(E.current),v.current&&clearTimeout(v.current),I.isSleeping){F();return}I.currentMode!=="normal"&&I.currentMode!=="sleep"&&z("normal"),l.autoDimTimeout>0&&(E.current=setTimeout(()=>{I.currentMode==="normal"&&z("dim")},l.autoDimTimeout)),l.autoSleepTimeout>0&&(v.current=setTimeout(()=>{z("sleep")},l.autoSleepTimeout)),B(O=>({...O,idleTime:0}))},[I.isSleeping,I.currentMode,l.autoDimTimeout,l.autoSleepTimeout,z,F]),U=e.useCallback(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const O=await navigator.getBattery();return{level:Math.round(O.level*100),charging:O.charging}}catch{return{}}return{}},[]),D=e.useCallback(async()=>{const O=await U();O.level!==void 0&&(B(y=>({...y,batteryLevel:O.level,isCharging:O.charging})),O.charging||(O.level<=l.criticalBatteryThreshold?(z("sleep"),G==null||G(O.level)):O.level<=l.lowBatteryThreshold&&(I.currentMode==="normal"&&z("low"),G==null||G(O.level))))},[U,l.lowBatteryThreshold,l.criticalBatteryThreshold,I.currentMode,z,G]),P=e.useCallback(()=>{if(!(h!=null&&h.schedule)||h.schedule.length===0)return;const y=new Date().getHours();for(const s of h.schedule){const{startHour:r,endHour:a,mode:c}=s;let o;if(r<=a?o=y>=r&&y<a:o=y>=r||y<a,o){B(S=>({...S,scheduledModeActive:c})),I.currentMode!==c&&z(c);return}}B(s=>({...s,scheduledModeActive:void 0}))},[h==null?void 0:h.schedule,I.currentMode,z]);e.useEffect(()=>{const O=["mousedown","mousemove","keydown","touchstart","scroll"],y=()=>{l.wakeOnTouch&&j()};for(const s of O)document.addEventListener(s,y);return j(),()=>{for(const s of O)document.removeEventListener(s,y);E.current&&clearTimeout(E.current),v.current&&clearTimeout(v.current)}},[l.wakeOnTouch,j]),e.useEffect(()=>{D(),(async()=>{if(typeof navigator<"u"&&"getBattery"in navigator)try{const y=await navigator.getBattery();p.current=y,y.addEventListener("levelchange",D),y.addEventListener("chargingchange",D)}catch{}})()},[D]),e.useEffect(()=>{P();const O=setInterval(P,6e4);return()=>clearInterval(O)},[P]),e.useEffect(()=>{q(l.initialMode)},[l.initialMode,q]),e.useImperativeHandle(f,()=>({getState:()=>I,setMode:z,setBrightness:Y,sleep:K,wake:F,togglePowerSaving:W,resetIdleTimer:j,getBatteryInfo:U}),[I,z,Y,K,F,W,j,U]);const T={...I,setMode:z,setBrightness:Y,sleep:K,wake:F,resetIdleTimer:j};return t.jsx(Oe.Provider,{value:T,children:t.jsxs("div",{className:`nice-lpm nice-lpm--${I.currentMode}`,children:[t.jsx("div",{className:"nice-lpm__overlay",style:{opacity:1-I.brightness}}),t.jsx("div",{className:"nice-lpm__content",children:i}),I.isSleeping&&t.jsx("div",{className:"nice-lpm__sleep-screen",onClick:l.wakeOnTouch?F:void 0,onTouchStart:l.wakeOnTouch?F:void 0,children:t.jsx("div",{className:"nice-lpm__sleep-message",children:"Touch to wake"})})]})})}),{displayName:"NiceLowPowerMode"}),Me=Te;process.env.NODE_ENV!=="production"&&(Me.displayName="NiceLowPowerModeProvider");const Fe=e.createContext(null),Pt=()=>{const n=e.useContext(Fe);if(!n)throw new Error("useOrientationLock must be used within NiceOrientationLockProvider");return n},Lt={preferredOrientation:"any",allowUserChange:!0,showRotationPrompt:!0,lockOnMount:!1,autoRotateContent:!1,supportedOrientations:["any","portrait","portrait-primary","portrait-secondary","landscape","landscape-primary","landscape-secondary","natural"]},Be=()=>{if(typeof window>"u")return"portrait";const n=window.screen;return n.orientation?n.orientation.type:window.innerHeight>window.innerWidth?"portrait":"landscape"},Rt=()=>{if(typeof window>"u")return 0;const n=window.screen;return n.orientation?n.orientation.angle:window.orientation||0},he=()=>{if(typeof window>"u")return{type:"portrait",angle:0,isPortrait:!0,isLandscape:!1,width:0,height:0,aspectRatio:0};const n=Be(),f=Rt(),h=window.screen.width,k=window.screen.height,g=n.includes("portrait")||window.innerHeight>window.innerWidth,N=n.includes("landscape")||window.innerWidth>window.innerHeight;return{type:n,angle:f,isPortrait:g,isLandscape:N,width:h,height:k,aspectRatio:h/k}},Ot=()=>{if(typeof window>"u")return!1;const n=window.screen;return!!(n.orientation&&typeof n.orientation.lock=="function")},$e=Object.assign(e.forwardRef((n,f)=>{const{config:h,onOrientationChange:k,onLockChange:g,onUnsupportedOrientation:N,rotationPrompt:R,children:G,className:i}=n,l={...Lt,...h},b=e.useRef(!1),[E,v]=e.useState(Be),[d,p]=e.useState(null),[I,B]=e.useState(he),[q]=e.useState(Ot),z=e.useCallback(y=>!!(l.supportedOrientations.includes("any")||l.supportedOrientations.includes(y)||y.includes("portrait")&&l.supportedOrientations.includes("portrait")||y.includes("landscape")&&l.supportedOrientations.includes("landscape")),[l.supportedOrientations]),Y=e.useCallback(async y=>{if(!q)return console.warn("Screen Orientation API is not available"),p(y),g==null||g(!0,y),!1;try{return await window.screen.orientation.lock(y),p(y),g==null||g(!0,y),!0}catch(s){return console.warn("Failed to lock orientation:",s),p(y),g==null||g(!0,y),!1}},[q,g]),K=e.useCallback(async()=>{if(p(null),g==null||g(!1,null),!q)return!1;try{return window.screen.orientation.unlock(),!0}catch(y){return console.warn("Failed to unlock orientation:",y),!1}},[q,g]),F=e.useCallback(async()=>d?K():Y(E),[d,E,Y,K]),W=e.useCallback(()=>he(),[]),j=e.useCallback(()=>{const y=he(),s=y.type;v(s),B(y),k==null||k(y),z(s)||N==null||N(s,l.supportedOrientations)},[l.supportedOrientations,z,k,N]);e.useEffect(()=>{b.current||(b.current=!0,j(),l.lockOnMount&&l.preferredOrientation!=="any"&&Y(l.preferredOrientation))},[l.lockOnMount,l.preferredOrientation,j,Y]),e.useEffect(()=>{const y=window.screen.orientation;return y&&y.addEventListener("change",j),window.addEventListener("resize",j),window.addEventListener("orientationchange",j),()=>{y&&y.removeEventListener("change",j),window.removeEventListener("resize",j),window.removeEventListener("orientationchange",j)}},[j]);const U={current:E,locked:d,isLocked:d!==null,isSupported:z(E),info:I,isApiAvailable:q};e.useImperativeHandle(f,()=>({getState:()=>U,lock:Y,unlock:K,toggleLock:F,getOrientationInfo:W,isOrientationSupported:z}),[U,Y,K,F,W,z]);const D={...U,lock:Y,unlock:K,getOrientationInfo:W},P=e.useCallback(()=>{if(!l.autoRotateContent||!d||d==="any")return;const y=d.includes("portrait"),s=I.isPortrait;return y===s?void 0:{transform:`rotate(${y?90:-90}deg)`,transformOrigin:"center center",width:y?I.height:I.width,height:y?I.width:I.height}},[l.autoRotateContent,d,I]),T=l.showRotationPrompt&&d!==null&&d!=="any"&&!U.isSupported,O=["nice-orientation",`nice-orientation--${E}`,d&&`nice-orientation--locked-${d}`,!U.isSupported&&"nice-orientation--unsupported",i].filter(Boolean).join(" ");return t.jsx(Fe.Provider,{value:D,children:t.jsxs("div",{className:O,style:P(),"data-orientation":E,"data-locked":d||void 0,children:[G,T&&t.jsx("div",{className:"nice-orientation__prompt",children:R||t.jsxs("div",{className:"nice-orientation__prompt-content",children:[t.jsx("div",{className:"nice-orientation__prompt-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--device","aria-hidden":"true"})}),t.jsxs("p",{className:"nice-orientation__prompt-text",children:["Please rotate your device to"," ",d!=null&&d.includes("portrait")?"portrait":"landscape"," mode"]})]})})]})})}),{displayName:"NiceOrientationLock"}),qe=$e;process.env.NODE_ENV!=="production"&&(qe.displayName="NiceOrientationLockProvider");const Ue=e.createContext(null),Tt=()=>{const n=e.useContext(Ue);if(!n)throw new Error("useRemoteManagement must be used within NiceRemoteManagementProvider");return n},Mt={heartbeatInterval:3e4,reconnectDelay:5e3,maxReconnectAttempts:10,enableHealthMonitoring:!0,healthReportInterval:6e4,enableScreenshot:!0,enableLogs:!0,logBufferSize:100},Ve=Object.assign(e.forwardRef((n,f)=>{const{config:h,onConnectionChange:k,onCommandReceived:g,onCustomCommand:N,onCaptureScreenshot:R,children:G}=n,i={...Mt,...h},l=e.useRef(null),b=e.useRef(null),E=e.useRef(null),v=e.useRef([]),d=e.useRef(Date.now()),p=e.useRef(0),[I,B]=e.useState({status:"disconnected",isConnected:!1,reconnectAttempts:0,pendingCommands:[],commandHistory:[]}),q=e.useCallback(()=>{const s=typeof navigator<"u"?navigator:null,r=typeof window<"u"?window:null;return{deviceId:i.deviceId,name:i.deviceName||i.deviceId,type:"embedded-display",os:s==null?void 0:s.platform,browser:s==null?void 0:s.userAgent,resolution:r?`${r.screen.width}x${r.screen.height}`:void 0,uptime:Math.floor((Date.now()-d.current)/1e3),metadata:{}}},[i.deviceId,i.deviceName]),z=e.useCallback(async()=>{const s={isOnline:typeof navigator<"u"?navigator.onLine:!0,lastUpdated:new Date};if(typeof performance<"u"&&"memory"in performance){const r=performance.memory;r&&(s.memory=Math.round(r.usedJSHeapSize/r.jsHeapSizeLimit*100))}if(typeof navigator<"u"&&"getBattery"in navigator)try{const r=await navigator.getBattery();s.battery=Math.round(r.level*100)}catch{}if(typeof navigator<"u"&&"storage"in navigator&&"estimate"in navigator.storage)try{const r=await navigator.storage.estimate();r.quota&&r.usage&&(s.storageFree=r.quota-r.usage)}catch{}return s},[]),Y=e.useRef({enabled:i.enableScreenshot,capture:R});e.useEffect(()=>{Y.current={enabled:i.enableScreenshot,capture:R}});const K=e.useCallback(async()=>{const{enabled:s,capture:r}=Y.current;if(!s)throw new Error("Screenshots are disabled on this device (enableScreenshot: false)");if(!r)throw new Error("This device cannot take screenshots: no onCaptureScreenshot handler");const a=await r();if(!a)throw new Error("The screenshot handler returned no image");return a},[]),F=e.useCallback(()=>K().catch(()=>{}),[K]),W=e.useRef({onConnectionChange:k,onCommandReceived:g,onCustomCommand:N});e.useEffect(()=>{W.current={onConnectionChange:k,onCommandReceived:g,onCustomCommand:N}});const j=e.useCallback(async()=>{var s,r,a,c,o;if(((s=l.current)==null?void 0:s.readyState)!==WebSocket.OPEN){B(S=>({...S,status:"connecting"})),(a=(r=W.current).onConnectionChange)==null||a.call(r,"connecting");try{const S=new URL(i.serverUrl);S.searchParams.set("deviceId",i.deviceId),i.apiKey&&S.searchParams.set("apiKey",i.apiKey);const A=new WebSocket(S.toString());l.current=A,A.onopen=()=>{var m,w;p.current=0,B(u=>({...u,status:"connected",isConnected:!0,reconnectAttempts:0,error:void 0})),(w=(m=W.current).onConnectionChange)==null||w.call(m,"connected"),A.send(JSON.stringify({type:"register",payload:q()}))},A.onmessage=async m=>{var w,u;try{const C=JSON.parse(m.data);if(C.type==="command"){const x={id:C.id,type:C.commandType,payload:C.payload,timestamp:new Date,acknowledged:!0,executed:!1};B(M=>({...M,pendingCommands:[...M.pendingCommands,x]})),(u=(w=W.current).onCommandReceived)==null||u.call(w,x);let H,_;try{switch(x.type){case"restart":typeof window<"u"&&window.location.reload();break;case"screenshot":H=await K();break;case"logs":H=v.current;break;case"custom":W.current.onCustomCommand&&(H=await W.current.onCustomCommand(x));break}x.executed=!0,x.result=H}catch(M){_=M instanceof Error?M.message:String(M),x.error=_}A.send(JSON.stringify({type:"commandResult",commandId:x.id,result:H,error:_})),B(M=>({...M,pendingCommands:M.pendingCommands.filter(L=>L.id!==x.id),commandHistory:[...M.commandHistory.slice(-49),x]}))}}catch{}},A.onerror=()=>{l.current===A&&B(m=>({...m,status:"error",error:"WebSocket error"}))},A.onclose=()=>{var m,w;l.current===A&&(l.current=null,B(u=>({...u,status:"disconnected",isConnected:!1})),p.current<i.maxReconnectAttempts&&setTimeout(()=>{p.current>=i.maxReconnectAttempts||(p.current+=1,B(u=>({...u,reconnectAttempts:p.current})),j())},i.reconnectDelay),(w=(m=W.current).onConnectionChange)==null||w.call(m,"disconnected"))}}catch(S){B(A=>({...A,status:"error",error:S instanceof Error?S.message:"Connection failed"})),(o=(c=W.current).onConnectionChange)==null||o.call(c,"error")}}},[i.serverUrl,i.deviceId,i.apiKey,i.maxReconnectAttempts,i.reconnectDelay,q,K]),U=e.useCallback(()=>{p.current=i.maxReconnectAttempts,l.current&&(l.current.close(),l.current=null),B(s=>({...s,status:"disconnected",isConnected:!1,reconnectAttempts:i.maxReconnectAttempts}))},[i.maxReconnectAttempts]),D=e.useCallback(async()=>{var s;((s=l.current)==null?void 0:s.readyState)===WebSocket.OPEN&&(l.current.send(JSON.stringify({type:"heartbeat",timestamp:new Date().toISOString(),deviceId:i.deviceId})),B(r=>({...r,lastHeartbeat:new Date})))},[i.deviceId]),P=e.useCallback(async s=>{var a;if(((a=l.current)==null?void 0:a.readyState)!==WebSocket.OPEN)return;const r=s||await z();l.current.send(JSON.stringify({type:"health",metrics:r,deviceId:i.deviceId})),B(c=>({...c,healthMetrics:r}))},[i.deviceId,z]),T=e.useCallback(async(s,r,a)=>{var c;((c=l.current)==null?void 0:c.readyState)===WebSocket.OPEN&&l.current.send(JSON.stringify({type:"commandResult",commandId:s,result:r,error:a}))},[]),O=e.useCallback((s,r,a)=>{var o;const c={level:s,message:r,data:a,timestamp:new Date};v.current=[...v.current.slice(-(i.logBufferSize-1)),c],i.enableLogs&&((o=l.current)==null?void 0:o.readyState)===WebSocket.OPEN&&l.current.send(JSON.stringify({type:"log",...c,deviceId:i.deviceId}))},[i.deviceId,i.enableLogs,i.logBufferSize]);e.useEffect(()=>(p.current=0,j(),()=>{U(),b.current&&clearInterval(b.current),E.current&&clearInterval(E.current)}),[]),e.useEffect(()=>{if(I.isConnected)return b.current=setInterval(D,i.heartbeatInterval),()=>{b.current&&clearInterval(b.current)}},[I.isConnected,i.heartbeatInterval,D]),e.useEffect(()=>{if(!(!I.isConnected||!i.enableHealthMonitoring))return E.current=setInterval(()=>{P()},i.healthReportInterval),P(),()=>{E.current&&clearInterval(E.current)}},[I.isConnected,i.enableHealthMonitoring,i.healthReportInterval,P]),e.useImperativeHandle(f,()=>({getState:()=>I,connect:j,disconnect:U,sendHeartbeat:D,sendHealthMetrics:P,reportCommandResult:T,sendLog:O,captureScreenshot:F,getDeviceInfo:q}),[I,j,U,D,P,T,O,F,q]);const y={...I,deviceInfo:q(),connect:j,disconnect:U,sendLog:O};return t.jsx(Ue.Provider,{value:y,children:G})}),{displayName:"NiceRemoteManagement"}),He=Ve;process.env.NODE_ENV!=="production"&&(He.displayName="NiceRemoteManagementProvider");const Ft={modes:["pixel-shift","dimming"],inactivityTimeout:300*1e3,pixelShift:{maxShift:3,interval:6e4,smooth:!0},colorCycle:{colors:["var(--nice-text-primary, #000000)","var(--nice-text, #111111)","var(--nice-bg, #0a0a0a)"],interval:3e4,transitionDuration:1e3},dimming:{level:.3,fadeDuration:2e3},screensaver:{type:"blank"},staticDetectionThreshold:3e4,autoDetectStatic:!1},Bt=Object.assign(e.forwardRef((n,f)=>{var S,A,m,w,u,C;const{config:h,enabled:k=!0,onActivate:g,onDeactivate:N,onModeChange:R,children:G}=n,i={...Ft,...h},l=e.useRef(null),b=e.useRef(null),E=e.useRef(null),v=e.useRef(null),[d,p]=e.useState({isActive:!1,activeModes:[],shiftX:0,shiftY:0,isDimmed:!1,isScreensaverActive:!1,idleTime:0}),[I,B]=e.useState(0),[q,z]=e.useState({x:50,y:50,dx:1,dy:1}),Y=e.useCallback(()=>{if(!i.pixelShift)return;const{maxShift:x}=i.pixelShift,H=Math.floor(Math.random()*(x*2+1))-x,_=Math.floor(Math.random()*(x*2+1))-x;p(M=>({...M,shiftX:H,shiftY:_}))},[i.pixelShift]),K=e.useCallback(()=>{!i.pixelShift||E.current||(Y(),E.current=setInterval(Y,i.pixelShift.interval))},[i.pixelShift,Y]),F=e.useCallback(()=>{E.current&&(clearInterval(E.current),E.current=null),p(x=>({...x,shiftX:0,shiftY:0}))},[]),W=e.useCallback(()=>{!i.colorCycle||v.current||(v.current=setInterval(()=>{B(x=>{var H;return(x+1)%(((H=i.colorCycle)==null?void 0:H.colors.length)||1)})},i.colorCycle.interval))},[i.colorCycle]),j=e.useCallback(()=>{v.current&&(clearInterval(v.current),v.current=null),B(0)},[]),U=e.useCallback(()=>{if(!k||d.isActive)return;const x=i.modes;p(H=>({...H,isActive:!0,activeModes:x})),x.includes("pixel-shift")&&K(),x.includes("color-cycling")&&W(),x.includes("dimming")&&p(H=>({...H,isDimmed:!0})),x.includes("screensaver")&&p(H=>({...H,isScreensaverActive:!0})),g==null||g(),R==null||R(x)},[k,d.isActive,i.modes,K,W,g,R]),D=e.useCallback(()=>{d.isActive&&(F(),j(),p(x=>({...x,isActive:!1,activeModes:[],isDimmed:!1,isScreensaverActive:!1})),N==null||N(),R==null||R([]))},[d.isActive,F,j,N,R]),P=e.useCallback(()=>{d.isActive?D():U()},[d.isActive,U,D]),T=e.useCallback(()=>{b.current&&clearTimeout(b.current),d.isActive&&D(),k&&i.inactivityTimeout>0&&(b.current=setTimeout(()=>{U()},i.inactivityTimeout))},[k,d.isActive,i.inactivityTimeout,U,D]),O=e.useCallback(()=>{p(x=>({...x,isScreensaverActive:!0}))},[]),y=e.useCallback(()=>{p(x=>({...x,isScreensaverActive:!1})),T()},[T]),s=e.useCallback(x=>{p(H=>({...H,isDimmed:x>0}))},[]);e.useEffect(()=>{var H;if(!d.isScreensaverActive||((H=i.screensaver)==null?void 0:H.type)!=="bounce")return;const x=setInterval(()=>{z(_=>{let{x:M,y:L,dx:X,dy:$}=_;return M+=X*.5,L+=$*.5,(M<=0||M>=90)&&(X=-X),(L<=0||L>=90)&&($=-$),{x:M,y:L,dx:X,dy:$}})},50);return()=>clearInterval(x)},[d.isScreensaverActive,(S=i.screensaver)==null?void 0:S.type]),e.useEffect(()=>{if(!k)return;const x=["mousedown","mousemove","keydown","touchstart","scroll","wheel"],H=()=>{T()};for(const _ of x)document.addEventListener(_,H);return T(),()=>{for(const _ of x)document.removeEventListener(_,H);b.current&&clearTimeout(b.current),F(),j()}},[k,T,F,j]),e.useImperativeHandle(f,()=>({getState:()=>d,activate:U,deactivate:D,toggle:P,resetIdleTimer:T,forceShift:Y,showScreensaver:O,hideScreensaver:y,setDimLevel:s}),[d,U,D,P,T,Y,O,y,s]);const r=()=>{if(!d.isScreensaverActive)return null;const x=i.screensaver||{type:"blank"};switch(x.type){case"blank":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--blank",onClick:y,onTouchStart:y});case"bounce":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--bounce",onClick:y,onTouchStart:y,children:t.jsx("div",{className:"nice-sbp__bounce-logo",style:{left:`${q.x}%`,top:`${q.y}%`},children:t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"1em",height:"1em",background:"currentColor",clipPath:"polygon(25% 5%, 75% 5%, 100% 50%, 75% 95%, 25% 95%, 0% 50%)"}})})});case"matrix":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--matrix",onClick:y,onTouchStart:y,children:Array.from({length:20}).map((H,_)=>t.jsx("div",{className:"nice-sbp__matrix-column",style:{left:`${_*5}%`,animationDelay:`${Math.random()*5}s`,animationDuration:`${5+Math.random()*5}s`},children:Array.from({length:20}).map((M,L)=>t.jsx("span",{children:String.fromCharCode(12448+Math.random()*96)},L))},_))});case"noise":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--noise",onClick:y,onTouchStart:y});case"custom":return t.jsx("div",{className:"nice-sbp__screensaver nice-sbp__screensaver--custom",onClick:y,onTouchStart:y,children:x.component});default:return null}},a={transform:d.isActive&&i.modes.includes("pixel-shift")?`translate(${d.shiftX}px, ${d.shiftY}px)`:void 0,transition:(A=i.pixelShift)!=null&&A.smooth?"transform 0.5s ease":void 0},c={"--dim-level":d.isDimmed?((m=i.dimming)==null?void 0:m.level)||.3:0,"--dim-duration":`${((w=i.dimming)==null?void 0:w.fadeDuration)||2e3}ms`},o=d.isActive&&i.modes.includes("color-cycling")?{backgroundColor:(u=i.colorCycle)==null?void 0:u.colors[I],transition:`background-color ${((C=i.colorCycle)==null?void 0:C.transitionDuration)||1e3}ms ease`}:{};return t.jsxs("div",{ref:l,className:`nice-sbp ${d.isActive?"nice-sbp--active":""}`,style:{...o},children:[t.jsx("div",{className:"nice-sbp__content",style:a,children:G}),d.isDimmed&&t.jsx("div",{className:"nice-sbp__dim-overlay",style:c,onClick:T,onTouchStart:T}),r(),d.isActive&&i.modes.includes("invert")&&t.jsx("div",{className:"nice-sbp__invert-overlay"})]})}),{displayName:"NiceScreenBurnPrevention"}),$t={pointCount:5,targetSize:40,accuracyThreshold:20,pointTimeout:1e4,showAccuracy:!0,allowRetry:!0,persistCalibration:!0,storageKey:"nice-touch-calibration"},qt=n=>({4:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:90,targetY:90},{targetX:10,targetY:90}],5:[{targetX:10,targetY:10},{targetX:90,targetY:10},{targetX:50,targetY:50},{targetX:10,targetY:90},{targetX:90,targetY:90}],9:[{targetX:10,targetY:10},{targetX:50,targetY:10},{targetX:90,targetY:10},{targetX:10,targetY:50},{targetX:50,targetY:50},{targetX:90,targetY:50},{targetX:10,targetY:90},{targetX:50,targetY:90},{targetX:90,targetY:90}]})[n],Ut=Object.assign(e.forwardRef((n,f)=>{const{config:h,autoStart:k=!1,onStart:g,onPointCalibrated:N,onComplete:R,onCancel:G,children:i}=n,l={...$t,...h},b=e.useRef(null),E=e.useRef(null),[v,d]=e.useState({isActive:!1,currentPointIndex:0,totalPoints:l.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),p=e.useCallback(P=>{const T=P.filter(L=>L.calibrated&&L.actualX!==void 0&&L.actualY!==void 0);if(T.length<3)return{scaleX:1,scaleY:1,offsetX:0,offsetY:0,rotation:0};let O=0,y=0,s=0,r=0;const a=T.length;for(const L of T)O+=L.targetX,y+=L.targetY,s+=L.actualX,r+=L.actualY;const c=O/a,o=y/a,S=s/a,A=r/a;let m=0,w=0,u=0,C=0;for(const L of T){const X=L.targetX-c,$=L.targetY-o,Z=L.actualX-S,J=L.actualY-A;m+=X*X,w+=X*Z,u+=$*$,C+=$*J}const x=w!==0?m/w:1,H=C!==0?u/C:1,_=c-x*S,M=o-H*A;return{scaleX:x,scaleY:H,offsetX:_,offsetY:M,rotation:0}},[]),I=e.useCallback((P,T)=>{const O=P.filter(s=>s.calibrated);if(O.length===0)return 0;let y=0;for(const s of O){if(s.actualX===void 0||s.actualY===void 0)continue;const r=T.scaleX*s.actualX+T.offsetX,a=T.scaleY*s.actualY+T.offsetY,c=s.targetX-r,o=s.targetY-a;y+=Math.sqrt(c*c+o*o)}return y/O.length},[]),B=e.useCallback(()=>{const T=qt(l.pointCount).map(O=>({...O,calibrated:!1}));d({isActive:!0,currentPointIndex:0,totalPoints:l.pointCount,points:T,isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0}),g==null||g()},[l.pointCount,g]),q=e.useCallback(()=>{E.current&&clearTimeout(E.current),d(P=>({...P,isActive:!1,isCompleted:!1})),G==null||G()},[G]),z=e.useCallback(()=>{d(P=>({...P,isCompleted:!1}))},[]),Y=e.useCallback(()=>{if(l.persistCalibration)try{localStorage.removeItem(l.storageKey)}catch{}d({isActive:!1,currentPointIndex:0,totalPoints:l.pointCount,points:[],isCompleted:!1,isSuccessful:!1,matrix:null,averageError:0})},[l.persistCalibration,l.storageKey,l.pointCount]),K=e.useCallback(P=>{const T=p(P),O=I(P,T),y=O<=l.accuracyThreshold;if(l.persistCalibration&&y)try{localStorage.setItem(l.storageKey,JSON.stringify({matrix:T,points:P}))}catch{}d(s=>({...s,points:P,isActive:!1,isCompleted:!0,isSuccessful:y,matrix:T,averageError:O})),R==null||R(T,y)},[l.accuracyThreshold,l.persistCalibration,l.storageKey,p,I,R]),F=e.useCallback(P=>{if(!v.isActive||!b.current)return;P.preventDefault();const T=b.current.getBoundingClientRect();let O,y;"touches"in P?(O=P.touches[0].clientX,y=P.touches[0].clientY):(O=P.clientX,y=P.clientY);const s=(O-T.left)/T.width*100,r=(y-T.top)/T.height*100,a=v.currentPointIndex,c=[...v.points];c[a]={...c[a],actualX:s,actualY:r,calibrated:!0};const o=a+1;N==null||N(c[a],a),o>=v.totalPoints?K(c):d(S=>({...S,currentPointIndex:o,points:c}))},[v.isActive,v.currentPointIndex,v.points,v.totalPoints,K,N]),W=e.useCallback((P,T)=>{const O=v.matrix;return O?{x:O.scaleX*P+O.offsetX,y:O.scaleY*T+O.offsetY}:{x:P,y:T}},[v.matrix]),j=e.useCallback(()=>{if(v.matrix)return!0;if(l.persistCalibration)try{return!!localStorage.getItem(l.storageKey)}catch{return!1}return!1},[v.matrix,l.persistCalibration,l.storageKey]),U=e.useCallback(()=>{if(l.persistCalibration)try{localStorage.removeItem(l.storageKey)}catch{}d(P=>({...P,matrix:null}))},[l.persistCalibration,l.storageKey]);if(e.useEffect(()=>{if(l.persistCalibration)try{const P=localStorage.getItem(l.storageKey);if(P){const T=JSON.parse(P);d(O=>({...O,matrix:T.matrix,points:T.points||[],isCompleted:!0,isSuccessful:!0}))}}catch{}},[l.persistCalibration,l.storageKey]),e.useEffect(()=>{if(!v.isActive)return;const P=b.current;if(P)return P.addEventListener("touchstart",F,{passive:!1}),P.addEventListener("mousedown",F),()=>{P.removeEventListener("touchstart",F),P.removeEventListener("mousedown",F)}},[v.isActive,F]),e.useEffect(()=>{if(!(!v.isActive||l.pointTimeout<=0))return E.current=setTimeout(()=>{v.currentPointIndex<v.totalPoints-1?d(P=>({...P,currentPointIndex:P.currentPointIndex+1})):K(v.points)},l.pointTimeout),()=>{E.current&&clearTimeout(E.current)}},[v.isActive,v.currentPointIndex,v.points,v.totalPoints,l.pointTimeout,K]),e.useEffect(()=>{k&&!j()&&B()},[k,j,B]),e.useImperativeHandle(f,()=>({getState:()=>v,start:B,cancel:q,reset:Y,getMatrix:()=>v.matrix,transformPoint:W,hasCalibration:j,clearCalibration:U}),[v,B,q,Y,W,j,U]),!v.isActive&&!v.isCompleted)return t.jsx(t.Fragment,{children:i});const D=v.isActive?v.points[v.currentPointIndex]:void 0;return t.jsxs("div",{ref:b,className:"nice-touch-calibration",children:[t.jsxs("div",{className:"nice-touch-calibration__overlay",children:[t.jsxs("div",{className:"nice-touch-calibration__instructions",children:[t.jsx("h2",{className:"nice-touch-calibration__title",children:"Touch Screen Calibration"}),t.jsx("p",{className:"nice-touch-calibration__text",children:"Touch the center of each target to calibrate your screen."}),t.jsxs("div",{className:"nice-touch-calibration__progress",children:["Point ",v.currentPointIndex+1," of ",v.totalPoints]})]}),D&&t.jsx("div",{className:"nice-touch-calibration__target",style:{left:`${D.targetX}%`,top:`${D.targetY}%`,width:l.targetSize,height:l.targetSize},children:(h==null?void 0:h.targetComponent)||t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"nice-touch-calibration__target-outer"}),t.jsx("div",{className:"nice-touch-calibration__target-inner"}),t.jsx("div",{className:"nice-touch-calibration__target-center"})]})}),v.points.map((P,T)=>P.calibrated&&t.jsx("div",{className:"nice-touch-calibration__calibrated",style:{left:`${P.actualX}%`,top:`${P.actualY}%`}},T)),v.isActive&&t.jsx("button",{className:"nice-touch-calibration__cancel",onClick:q,children:"Cancel"})]}),v.isCompleted&&t.jsxs("div",{className:"nice-touch-calibration__result",children:[t.jsx("div",{className:`nice-touch-calibration__result-icon ${v.isSuccessful?"nice-touch-calibration__result-icon--success":"nice-touch-calibration__result-icon--error"}`,children:t.jsx("span",{className:`nice-platform-mark nice-platform-mark--${v.isSuccessful?"check":"alert"}`,"aria-hidden":"true"})}),t.jsx("h3",{className:"nice-touch-calibration__result-title",children:v.isSuccessful?"Calibration Complete":"Calibration Failed"}),l.showAccuracy&&t.jsxs("p",{className:"nice-touch-calibration__result-accuracy",children:["Average error: ",v.averageError.toFixed(1),"px"]}),!v.isSuccessful&&l.allowRetry&&t.jsx("button",{className:"nice-touch-calibration__retry",onClick:B,children:"Retry Calibration"}),t.jsx("button",{className:"nice-touch-calibration__retry nice-touch-calibration__done",onClick:z,children:"Done"})]})]})}),{displayName:"NiceTouchCalibration"}),Vt={format:"code128",width:2,height:100,displayValue:!0,font:"monospace",fontSize:14,textAlign:"center",textPosition:"bottom",textMargin:2,background:"#ffffff",lineColor:"#000000",margin:10,flat:!1},ve=104,Ht=106,Wt=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",le=["11011001100","11001101100","11001100110","10010011000","10010001100","10001001100","10011001000","10011000100","10001100100","11001001000","11001000100","11000100100","10110011100","10011011100","10011001110","10111001100","10011101100","10011100110","11001110010","11001011100","11001001110","11011100100","11001110100","11101101110","11101001100","11100101100","11100100110","11101100100","11100110100","11100110010","11011011000","11011000110","11000110110","10100011000","10001011000","10001000110","10110001000","10001101000","10001100010","11010001000","11000101000","11000100010","10110111000","10110001110","10001101110","10111011000","10111000110","10001110110","11101110110","11010001110","11000101110","11011101000","11011100010","11011101110","11101011000","11101000110","11100010110","11101101000","11101100010","11100011010","11101111010","11001000010","11110001010","10100110000","10100001100","10010110000","10010000110","10000101100","10000100110","10110010000","10110000100","10011010000","10011000010","10000110100","10000110010","11000010010","11001010000","11110111010","11000010100","10001111010","10100111100","10010111100","10010011110","10111100100","10011110100","10011110010","11110100100","11110010100","11110010010","11011011110","11011110110","11110110110","10101111000","10100011110","10001011110","10111101000","10111100010","11110101000","11110100010","10111011110","10111101110","11101011110","11110101110","11010000100","11010010000","11010011100","1100011101011"],xe=n=>{let f=le[ve],h=ve;for(let k=0;k<n.length;k++){const g=n[k],N=Wt.indexOf(g);N!==-1&&(f+=le[N],h+=N*(k+1))}return h=h%103,f+=le[h],f+=le[Ht],f},We=["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],zt=["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"],ze=["1110010","1100110","1101100","1000010","1011100","1001110","1010000","1000100","1001000","1110100"],Gt=["LLLLLL","LLGLGG","LLGGLG","LLGGGL","LGLLGG","LGGLLG","LGGGLL","LGLGLG","LGLGGL","LGGLGL"],Yt=n=>{let f=0;for(let h=0;h<12;h++)f+=parseInt(n[h])*(h%2===0?1:3);return(10-f%10)%10},Xt=n=>{let f=n.replace(/\D/g,"").slice(0,12).padStart(12,"0");const h=Yt(f);f+=h;const k=parseInt(f[0]),g=Gt[k];let N="101";for(let R=1;R<=6;R++){const G=parseInt(f[R]);N+=g[R-1]==="L"?We[G]:zt[G]}N+="01010";for(let R=7;R<=12;R++){const G=parseInt(f[R]);N+=ze[G]}return N+="101",N},Kt=n=>{let f=n.replace(/\D/g,"").slice(0,7).padStart(7,"0"),h=0;for(let N=0;N<7;N++)h+=parseInt(f[N])*(N%2===0?3:1);const k=(10-h%10)%10;f+=k;let g="101";for(let N=0;N<4;N++)g+=We[parseInt(f[N])];g+="01010";for(let N=4;N<8;N++)g+=ze[parseInt(f[N])];return g+="101",g},Qt={0:"101001101101",1:"110100101011",2:"101100101011",3:"110110010101",4:"101001101011",5:"110100110101",6:"101100110101",7:"101001011011",8:"110100101101",9:"101100101101",A:"110101001011",B:"101101001011",C:"110110100101",D:"101011001011",E:"110101100101",F:"101101100101",G:"101010011011",H:"110101001101",I:"101101001101",J:"101011001101",K:"110101010011",L:"101101010011",M:"110110101001",N:"101011010011",O:"110101101001",P:"101101101001",Q:"101010110011",R:"110101011001",S:"101101011001",T:"101011011001",U:"110010101011",V:"100110101011",W:"110011010101",X:"100101101011",Y:"110010110101",Z:"100110110101","-":"100101011011",".":"110010101101"," ":"100110101101",$:"100100100101","/":"100100101001","+":"100101001001","%":"101001001001","*":"100101101101"},Jt=n=>{const f=("*"+n.toUpperCase()+"*").split("");let h="";for(const k of f){const g=Qt[k];g&&(h+=g+"0")}return h.slice(0,-1)},Ce=n=>{switch(n){case"code128":return xe;case"code39":case"code93":return Jt;case"ean13":return Xt;case"ean8":return Kt;default:return xe}},Zt=Object.assign(e.forwardRef((n,f)=>{const{value:h,options:k,onGenerate:g,onError:N,showBorder:R=!1,className:G}=n,i={...Vt,...k},l=e.useRef(null),b=e.useRef(null),[E,v]=e.useState(null),[d,p]=e.useState(null),I=e.useCallback(()=>{if(!l.current||!h)return;const W=l.current,j=W.getContext("2d");if(j)try{const D=Ce(i.format)(h),P=i.width,T=D.length*P,O=i.marginTop??i.margin,y=i.marginBottom??i.margin,s=i.marginLeft??i.margin,r=i.marginRight??i.margin,a=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,c=T+s+r,o=i.height+O+y+a;W.width=c,W.height=o,j.fillStyle=i.background,j.fillRect(0,0,c,o),j.fillStyle=i.lineColor;let S=s;const A=i.textPosition==="top"&&i.displayValue?O+a:O;for(let w=0;w<D.length;w++)D[w]==="1"&&j.fillRect(S,A,P,i.height),S+=P;if(i.displayValue&&!i.flat){j.fillStyle=i.lineColor,j.font=`${i.fontSize}px ${i.font}`,j.textBaseline=i.textPosition==="top"?"top":"bottom";let w=s;i.textAlign==="center"?(w=s+T/2,j.textAlign="center"):i.textAlign==="right"?(w=s+T,j.textAlign="right"):j.textAlign="left";const u=i.textPosition==="top"?O+i.textMargin:o-y-i.textMargin;j.fillText(h,w,u)}const m=W.toDataURL("image/png");p(m),v(null),g==null||g(m)}catch(U){const D=U instanceof Error?U.message:"Failed to generate barcode";v(D),N==null||N(new Error(D))}},[h,i,g,N]);e.useEffect(()=>{I()},[I]);const B=e.useCallback((W="image/png",j=1)=>{var U;return((U=l.current)==null?void 0:U.toDataURL(W,j))||null},[]),q=e.useCallback(()=>{if(!l.current||!h)return null;try{const j=Ce(i.format)(h),U=i.width,D=i.marginTop??i.margin,P=i.marginBottom??i.margin,T=i.marginLeft??i.margin,O=i.marginRight??i.margin,y=i.displayValue&&!i.flat?i.fontSize+i.textMargin*2:0,s=j.length*U,r=s+T+O,a=i.height+D+P+y,c=[];let o=T;const S=i.textPosition==="top"&&i.displayValue?D+y:D;for(let m=0;m<j.length;m++)j[m]==="1"&&c.push(`<rect x="${o}" y="${S}" width="${U}" height="${i.height}" fill="${i.lineColor}"/>`),o+=U;let A="";if(i.displayValue&&!i.flat){const m=i.textAlign==="center"?"middle":i.textAlign==="right"?"end":"start";let w=T;i.textAlign==="center"?w=T+s/2:i.textAlign==="right"&&(w=T+s);const u=i.textPosition==="top"?D+i.fontSize:a-P-i.textMargin;A=`<text x="${w}" y="${u}" font-family="${i.font}" font-size="${i.fontSize}" text-anchor="${m}" fill="${i.lineColor}">${h}</text>`}return`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${a}" viewBox="0 0 ${r} ${a}">
2
2
  <rect width="100%" height="100%" fill="${i.background}"/>
3
3
  ${c.join(`
4
4
  `)}
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}">
5
+ ${A}
6
+ </svg>`}catch{return null}},[h,i]),z=e.useCallback(()=>l.current,[]),Y=e.useCallback((W="barcode",j="png")=>{const U=document.createElement("a");if(j==="svg"){const D=q();if(!D)return;const P=new Blob([D],{type:"image/svg+xml"});U.href=URL.createObjectURL(P),U.download=`${W}.svg`}else{const D=B();if(!D)return;U.href=D,U.download=`${W}.png`}U.click()},[B,q]),K=e.useCallback(()=>{I()},[I]);e.useImperativeHandle(f,()=>({toDataURL:B,toSVG:q,getCanvas:z,download:Y,regenerate:K}),[B,q,z,Y,K]);const F=["nice-barcode-generator",R&&"nice-barcode-generator--bordered",E&&"nice-barcode-generator--error",G].filter(Boolean).join(" ");return t.jsxs("div",{className:F,children:[t.jsx("canvas",{ref:l,className:"nice-barcode-generator__canvas"}),t.jsx("svg",{ref:b,style:{display:"none"}}),E&&t.jsx("div",{className:"nice-barcode-generator__error",children:t.jsx("span",{children:E})})]})}),{displayName:"NiceBarcodeGenerator"}),en={formats:["qr_code","ean_13","ean_8","code_128","code_39","upc_a","upc_e"],continuous:!0,scanInterval:100,showBoundingBox:!0,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd"},tn=n=>({aztec:"aztec",code_128:"code_128",code_39:"code_39",code_93:"code_93",codabar:"codabar",data_matrix:"data_matrix",ean_13:"ean_13",ean_8:"ean_8",itf:"itf",pdf417:"pdf417",qr_code:"qr_code",upc_a:"upc_a",upc_e:"upc_e"})[n.toLowerCase().replace("-","_")]||"unknown",nn=()=>typeof window<"u"&&"BarcodeDetector"in window,sn=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],rn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),h=n.createGain();f.connect(h),h.connect(n.destination),f.type="sine",f.frequency.value=1e3,h.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},100)}catch{}},an=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate(50)},cn=Object.assign(e.forwardRef((n,f)=>{const{config:h,onScan:k,onBatchScan:g,onError:N,onCameraReady:R,customScanFrame:G,showScanFrame:i=!0,autoStart:l=!1,children:b,className:E}=n,v={...en,...h},d=e.useRef(null),p=e.useRef(null),I=e.useRef(null),B=e.useRef(null),q=e.useRef(null),z=e.useRef(null),[Y,K]=e.useState(!1),[F,W]=e.useState(!1),[j,U]=e.useState(null),[D,P]=e.useState(null),[T,O]=e.useState(null),[y,s]=e.useState(v.facingMode),[r,a]=e.useState(null),c=nn(),o=e.useCallback(async()=>{try{return(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach(X=>X.stop()),O(!0),!0}catch{return O(!1),!1}},[]),S=e.useCallback(async()=>{if(!d.current)return;const L=sn(v.resolution),X={video:{facingMode:y,width:{ideal:L.width},height:{ideal:L.height}},audio:!1};try{const $=await navigator.mediaDevices.getUserMedia(X);I.current=$,d.current.srcObject=$,await d.current.play(),W(!0),O(!0),P(null),R==null||R()}catch($){const Z=$ instanceof Error?$.message:"Failed to access camera";P(Z),O(!1),N==null||N(new Error(Z))}},[v.resolution,y,R,N]),A=e.useCallback(()=>{I.current&&(I.current.getTracks().forEach(L=>L.stop()),I.current=null),d.current&&(d.current.srcObject=null),W(!1)},[]),m=e.useCallback(async()=>{s(y==="user"?"environment":"user"),Y&&A()},[y,Y,A]),w=e.useCallback(async()=>{if(c)try{const L=window.BarcodeDetector,X=v.formats.map($=>$.replace("_","-"));B.current=new L({formats:X})}catch(L){const X=L instanceof Error?L.message:"Failed to initialize barcode detector";P(X),N==null||N(new Error(X))}},[c,v.formats,N]),u=e.useCallback(async()=>{if(!(!d.current||!B.current||!F))try{const X=await B.current.detect(d.current);if(X.length>0){const $=X.map(J=>({rawValue:J.rawValue,format:tn(J.format),boundingBox:J.boundingBox?{x:J.boundingBox.x,y:J.boundingBox.y,width:J.boundingBox.width,height:J.boundingBox.height}:void 0,cornerPoints:J.cornerPoints,timestamp:new Date})),Z=$[0];if(v.continuous&&Z.rawValue===z.current)return;z.current=Z.rawValue,v.showBoundingBox&&Z.boundingBox&&(a(Z.boundingBox),setTimeout(()=>a(null),500)),v.beepOnScan&&rn(),v.vibrateOnScan&&an(),U(Z),k==null||k(Z),$.length>1&&(g==null||g($)),setTimeout(()=>{z.current=null},1e3)}}catch{}},[F,v.continuous,v.showBoundingBox,v.beepOnScan,v.vibrateOnScan,k,g]),C=e.useCallback(async()=>{K(!0),P(null),await w(),await S()},[w,S]),x=e.useCallback(()=>{K(!1),q.current&&(clearInterval(q.current),q.current=null),A()},[A]),H=e.useCallback(async()=>{Y?x():await C()},[Y,C,x]),_=e.useCallback(()=>{if(!d.current||!p.current)return null;const L=p.current,X=d.current;L.width=X.videoWidth,L.height=X.videoHeight;const $=L.getContext("2d");return $?($.drawImage(X,0,0),L.toDataURL("image/png")):null},[]);e.useEffect(()=>(Y&&F&&v.continuous&&(q.current=setInterval(u,v.scanInterval)),()=>{q.current&&(clearInterval(q.current),q.current=null)}),[Y,F,v.continuous,v.scanInterval,u]),e.useEffect(()=>(l&&C(),()=>{x()}),[]),e.useEffect(()=>{Y&&!F&&S()},[y,Y,F,S]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:Y,isCameraReady:F,lastResult:j,error:D,isSupported:c,hasPermission:T}),start:C,stop:x,toggle:H,takeSnapshot:_,switchCamera:m,requestPermission:o}),[Y,F,j,D,c,T,C,x,H,_,m,o]);const M=["nice-barcode-scanner",Y&&"nice-barcode-scanner--scanning",F&&"nice-barcode-scanner--ready",D&&"nice-barcode-scanner--error",E].filter(Boolean).join(" ");return t.jsxs("div",{className:M,children:[t.jsx("video",{ref:d,className:"nice-barcode-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:p,className:"nice-barcode-scanner__canvas"}),i&&Y&&t.jsxs("div",{className:"nice-barcode-scanner__frame",children:[t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-barcode-scanner__frame-corner nice-barcode-scanner__frame-corner--br"}),t.jsx("div",{className:"nice-barcode-scanner__scan-line"})]}),r&&d.current&&t.jsx("div",{className:"nice-barcode-scanner__bounding-box",style:{left:`${r.x/d.current.videoWidth*100}%`,top:`${r.y/d.current.videoHeight*100}%`,width:`${r.width/d.current.videoWidth*100}%`,height:`${r.height/d.current.videoHeight*100}%`}}),D&&t.jsxs("div",{className:"nice-barcode-scanner__error",children:[t.jsx("div",{className:"nice-barcode-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-barcode-scanner__error-text",children:D}),t.jsx("button",{className:"nice-barcode-scanner__error-btn",onClick:()=>C(),children:"Try Again"})]}),!c&&t.jsx("div",{className:"nice-barcode-scanner__unsupported",children:t.jsx("p",{children:"Barcode scanning is not supported in this browser."})}),b&&t.jsx("div",{className:"nice-barcode-scanner__overlay",children:b})]})}),{displayName:"NiceBarcodeScanner"}),ge=e.createContext(null),Ge=e.createContext(null),ce=n=>()=>{process.env.NODE_ENV!=="production"&&console.warn(`[NiceBatchScannerProvider] ${n}: no NiceBatchScanner is mounted below it.`)},on={items:[],isScanning:!1,addItem:ce("addItem"),removeItem:ce("removeItem"),updateQuantity:ce("updateQuantity"),clearAll:ce("clearAll"),startScanning:async()=>ce("startScanning")(),stopScanning:ce("stopScanning")},ln=()=>{const n=e.useContext(ge);if(!n)throw new Error("useBatchScanner must be used inside NiceBatchScanner or below NiceBatchScannerProvider");return n},un={autoIncrementDuplicates:!0,maxItems:1e3,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,showBoundingBox:!0,allowManualEntry:!0,minConfidence:0},dn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),h=n.createGain();f.connect(h),h.connect(n.destination),f.frequency.value=1200,f.type="sine",h.gain.setValueAtTime(.3,n.currentTime),h.gain.exponentialRampToValueAtTime(.01,n.currentTime+.1),f.start(),f.stop(n.currentTime+.1)}catch{}},fn=(n=50)=>{"vibrate"in navigator&&navigator.vibrate(n)},mn=()=>`${Date.now()}-${Math.random().toString(36).slice(2,11)}`,hn=Object.assign(e.forwardRef((n,f)=>{const{options:h,initialItems:k=[],onScan:g,onRemove:N,onBatchComplete:R,onQuantityChange:G,onError:i,validateScan:l,transformValue:b,className:E,children:v}=n,d=e.useMemo(()=>({...un,...h}),[h]),p=e.useRef(null),I=e.useRef(null),B=e.useRef(null),q=e.useRef(null),z=e.useRef(0),Y=e.useRef(""),K=e.useRef(0),[F,W]=e.useState(k),[j,U]=e.useState(!1),[D,P]=e.useState(!1),[T,O]=e.useState(""),[y,s]=e.useState([]),[r,a]=e.useState(null);e.useEffect(()=>{(async()=>{if("BarcodeDetector"in window)try{const Q=await BarcodeDetector.getSupportedFormats();Q.length>0&&(q.current=new BarcodeDetector({formats:(h==null?void 0:h.formats)||Q}),P(!0))}catch{P(!1)}})()},[h==null?void 0:h.formats]);const c=e.useCallback(async(V,Q="unknown",ee)=>{const te=b?b(V,Q):V;if(l&&!await l(te,Q))return;const ne=F.findIndex(se=>se.value===te);if(ne!==-1&&d.autoIncrementDuplicates){const se=[...F];se[ne]={...se[ne],quantity:se[ne].quantity+1,timestamp:Date.now()},W(se),G==null||G(se[ne],se[ne].quantity)}else if(F.length<d.maxItems){const se={id:mn(),value:te,format:Q,timestamp:Date.now(),rawValue:V,quantity:1,boundingBox:ee};W(re=>[se,...re]),g==null||g(se)}d.beepOnScan&&dn(),d.vibrateOnScan&&fn()},[F,d,l,b,g,G]),o=e.useCallback(V=>{const Q=F.find(ee=>ee.id===V);Q&&(W(ee=>ee.filter(te=>te.id!==V)),N==null||N(Q))},[F,N]),S=e.useCallback((V,Q)=>{if(Q<1){o(V);return}W(te=>te.map(ne=>ne.id===V?{...ne,quantity:Q}:ne));const ee=F.find(te=>te.id===V);ee&&(G==null||G(ee,Q))},[F,o,G]),A=e.useCallback(()=>{W([])},[]),m=e.useCallback(async()=>{if(!p.current||!q.current||!I.current)return;const V=p.current,Q=I.current,ee=Q.getContext("2d");if(!ee||V.readyState!==V.HAVE_ENOUGH_DATA){z.current=requestAnimationFrame(m);return}Q.width=V.videoWidth,Q.height=V.videoHeight,ee.drawImage(V,0,0);try{const te=await q.current.detect(Q);if(te.length>0){const ne=Date.now(),se=[];for(const re of te)se.push(re.boundingBox),(re.rawValue!==Y.current||ne-K.current>2e3)&&(Y.current=re.rawValue,K.current=ne,c(re.rawValue,re.format,re.boundingBox));d.showBoundingBox&&(s(se),setTimeout(()=>s([]),500))}}catch(te){console.warn("Scan error:",te)}z.current=requestAnimationFrame(m)},[c,d.showBoundingBox]),w=e.useCallback(async()=>{if(!D||!q.current){a("Camera or BarcodeDetector not available"),i==null||i(new Error("Camera or BarcodeDetector not available"));return}try{const V=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:1280},height:{ideal:720}}});B.current=V,p.current&&(p.current.srcObject=V,await p.current.play()),U(!0),a(null),z.current=requestAnimationFrame(m)}catch(V){const Q=V instanceof Error?V.message:"Failed to start camera";a(Q),i==null||i(new Error(Q))}},[D,m,i]),u=e.useCallback(()=>{z.current&&cancelAnimationFrame(z.current),B.current&&(B.current.getTracks().forEach(V=>V.stop()),B.current=null),p.current&&(p.current.srcObject=null),U(!1),s([])},[]);e.useEffect(()=>()=>{u()},[u]);const C=e.useCallback(()=>{T.trim()&&(c(T.trim()),O(""))},[T,c]),x=e.useCallback(()=>{const V=["Value","Format","Quantity","Timestamp"],Q=F.map(ee=>[`"${ee.value.replace(/"/g,'""')}"`,ee.format,ee.quantity.toString(),new Date(ee.timestamp).toISOString()]);return[V.join(","),...Q.map(ee=>ee.join(","))].join(`
7
+ `)},[F]),H=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:(V,Q)=>c(V,Q),removeItem:o,updateQuantity:S,clearAll:A,exportCSV:x,exportJSON:H,isScanning:()=>j}),[w,u,F,c,o,S,A,x,H,j]);const M={items:F,isScanning:j,addItem:(V,Q)=>c(V,Q),removeItem:o,updateQuantity:S,clearAll:A,startScanning:w,stopScanning:u},L=e.useContext(Ge),X=e.useRef(M);e.useEffect(()=>{X.current=M});const $=e.useMemo(()=>({items:F,isScanning:j,addItem:(V,Q)=>X.current.addItem(V,Q),removeItem:V=>X.current.removeItem(V),updateQuantity:(V,Q)=>X.current.updateQuantity(V,Q),clearAll:()=>X.current.clearAll(),startScanning:()=>X.current.startScanning(),stopScanning:()=>X.current.stopScanning()}),[F,j]);e.useEffect(()=>{L==null||L($)},[L,$]),e.useEffect(()=>{if(L)return()=>L(null)},[L]);const Z=F.reduce((V,Q)=>V+Q.quantity,0),J=["nice-batch-scanner",j&&"nice-batch-scanner--scanning",E].filter(Boolean).join(" ");return t.jsx(ge.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:I,className:"nice-batch-scanner__canvas"}),p.current&&y.map((V,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:V.x*te,top:V.y*ne,width:V.width*te,height:V.height*ne}},Q)}),j&&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})}),!j&&!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--${j?"stop":"start"}`,onClick:j?u:w,children:j?"Stop Scanning":"Start Scanning"}),d.allowManualEntry&&t.jsxs("div",{className:"nice-batch-scanner__manual",children:[t.jsx("input",{type:"text",value:T,onChange:V=>O(V.target.value),onKeyDown:V=>V.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(V=>t.jsxs("div",{className:"nice-batch-scanner__item",children:[t.jsxs("div",{className:"nice-batch-scanner__item-info",children:[t.jsx("span",{className:"nice-batch-scanner__item-value",children:V.value}),t.jsx("span",{className:"nice-batch-scanner__item-format",children:V.format})]}),t.jsxs("div",{className:"nice-batch-scanner__item-quantity",children:[t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>S(V.id,V.quantity-1),"aria-label":"Decrease quantity",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--minus","aria-hidden":"true"})}),t.jsx("span",{className:"nice-batch-scanner__qty-value",children:V.quantity}),t.jsx("button",{className:"nice-batch-scanner__qty-btn",onClick:()=>S(V.id,V.quantity+1),"aria-label":"Increase quantity",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--plus","aria-hidden":"true"})})]}),t.jsx("button",{className:"nice-batch-scanner__item-remove",onClick:()=>o(V.id),"aria-label":"Remove item",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]},V.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:A,children:"Clear All"}),t.jsxs("button",{className:"nice-batch-scanner__btn nice-batch-scanner__btn--primary",onClick:_,children:["Complete Batch (",Z,")"]})]}),v]})})}),{displayName:"NiceBatchScanner"}),gn=({children:n})=>{const[f,h]=e.useState(null);return t.jsx(Ge.Provider,{value:h,children:t.jsx(ge.Provider,{value:f??on,children:n})})},pn={errorCorrection:"M",size:200,margin:2,darkColor:"#000000",lightColor:"#ffffff",logoSize:.2,logoMargin:1,cornerRadius:0},bn={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]},yn=(n,f)=>{const h=n.length,k=bn[f];for(let g=0;g<k.length;g++)if(k[g]>=h)return g+1;return 10},ke=(n,f)=>{const h=yn(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,b)=>{for(let E=-1;E<=7;E++)for(let v=-1;v<=7;v++){const d=l+E,p=b+v;d<0||d>=k||p<0||p>=k||(N[d][p]=!0,E===-1||E===7||v===-1||v===7?g[d][p]=!1:E===0||E===6||v===0||v===6||E>=2&&E<=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 b of l)for(const E of l)if(!(b<9&&E<9||b<9&&E>k-10||b>k-10&&E<9))for(let v=-2;v<=2;v++)for(let d=-2;d<=2;d++){const p=b+v,I=E+d;p<0||p>=k||I<0||I>=k||(N[p][I]=!0,g[p][I]=v===-2||v===2||d===-2||d===2||v===0&&d===0)}}const G=n.split("").reduce((l,b)=>(l<<5)-l+b.charCodeAt(0),0);let i=0;for(let l=k-1;l>=0;l-=2){l===6&&(l=5);for(let b=0;b<k;b++)for(let E=0;E<=1;E++){const v=l-E;if(N[b][v])continue;const d=i%n.length,p=n.charCodeAt(d)&1<<i%8,I=(G+b*k+v)%256>127;g[b][v]=p!==0!==I,i++}}return g},wn=Object.assign(e.forwardRef((n,f)=>{const{value:h,options:k,onGenerate:g,onError:N,showBorder:R=!1,className:G}=n,i={...pn,...k},l=e.useRef(null),b=e.useRef(null),[E,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=()=>{b.current=F,p(!0)},F.onerror=()=>{b.current=null,p(!0)},F.src=k.logo}else b.current=null,p(!0)},[k==null?void 0:k.logo]);const I=e.useCallback(()=>{if(!l.current||!h||!d)return;const F=l.current,W=F.getContext("2d");if(W)try{const j=ke(h,i.errorCorrection),U=j.length,D=Math.floor((i.size-i.margin*2)/U),P=U*D+i.margin*2*D;F.width=P,F.height=P,W.fillStyle=i.lightColor,W.fillRect(0,0,P,P),W.fillStyle=i.darkColor;const T=i.margin*D;for(let y=0;y<U;y++)for(let s=0;s<U;s++)if(j[y][s]){const r=T+s*D,a=T+y*D;if(i.cornerRadius>0){const c=Math.min(i.cornerRadius,D/2);W.beginPath(),W.roundRect(r,a,D,D,c),W.fill()}else W.fillRect(r,a,D,D)}if(b.current){const y=P*i.logoSize,s=(P-y)/2,r=(P-y)/2,a=i.logoMargin*D;W.fillStyle=i.lightColor,W.fillRect(s-a,r-a,y+a*2,y+a*2),W.drawImage(b.current,s,r,y,y)}const O=F.toDataURL("image/png");v(null),g==null||g(O)}catch(j){const U=j instanceof Error?j.message:"Failed to generate QR code";v(U),N==null||N(new Error(U))}},[h,i,d,g,N]);e.useEffect(()=>{I()},[I]);const B=e.useCallback((F="image/png",W=1)=>{var j;return((j=l.current)==null?void 0:j.toDataURL(F,W))||null},[]),q=e.useCallback(()=>{if(!l.current||!h)return null;try{const F=ke(h,i.errorCorrection),W=F.length,j=Math.floor((i.size-i.margin*2)/W),U=W*j+i.margin*2*j,D=i.margin*j,P=[];for(let T=0;T<W;T++)for(let O=0;O<W;O++)if(F[T][O]){const y=D+O*j,s=D+T*j;if(i.cornerRadius>0){const r=Math.min(i.cornerRadius,j/2);P.push(`<rect x="${y}" y="${s}" width="${j}" height="${j}" rx="${r}" fill="${i.darkColor}"/>`)}else P.push(`<rect x="${y}" y="${s}" width="${j}" height="${j}" 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}},[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;
11
+ </svg>`}catch{return null}},[h,i]),z=e.useCallback((F="qrcode",W="png")=>{const j=document.createElement("a");if(W==="svg"){const U=q();if(!U)return;const D=new Blob([U],{type:"image/svg+xml"});j.href=URL.createObjectURL(D),j.download=`${F}.svg`}else{const U=B();if(!U)return;j.href=U,j.download=`${F}.png`}j.click()},[B,q]),Y=e.useCallback(()=>{I()},[I]);e.useImperativeHandle(f,()=>({toDataURL:B,toSVG:q,download:z,regenerate:Y}),[B,q,z,Y]);const K=["nice-qr-generator",R&&"nice-qr-generator--bordered",E&&"nice-qr-generator--error",G].filter(Boolean).join(" ");return t.jsxs("div",{className:K,children:[t.jsx("canvas",{ref:l,className:"nice-qr-generator__canvas",style:{maxWidth:"100%",height:"auto"}}),E&&t.jsx("div",{className:"nice-qr-generator__error",children:t.jsx("span",{children:E})})]})}),{displayName:"NiceQRGenerator"}),vn={continuous:!0,scanInterval:100,beepOnScan:!0,vibrateOnScan:!0,autoFocus:!0,facingMode:"environment",resolution:"hd",parseDataType:!0,highlightDetected:!0},xn=n=>{var f,h,k;if(/^https?:\/\//i.test(n))return{type:"url",data:{url:n}};if(/^mailto:/i.test(n)){const g=n.match(/^mailto:([^?]+)(?:\?(.*))?$/i);return{type:"email",data:{email:g==null?void 0:g[1],params:g==null?void 0:g[2]}}}if(/^tel:/i.test(n))return{type:"tel",data:{phone:n.replace(/^tel:/i,"")}};if(/^smsto?:/i.test(n)){const g=n.match(/^smsto?:([^:]+)(?::(.*))?$/i);return{type:"sms",data:{phone:g==null?void 0:g[1],message:g==null?void 0:g[2]}}}if(/^geo:/i.test(n)){const g=n.match(/^geo:(-?\d+\.?\d*),(-?\d+\.?\d*)(?:,(-?\d+\.?\d*))?/i);return{type:"geo",data:{latitude:parseFloat((g==null?void 0:g[1])||"0"),longitude:parseFloat((g==null?void 0:g[2])||"0"),altitude:g!=null&&g[3]?parseFloat(g[3]):void 0}}}if(/^BEGIN:VCARD/i.test(n))return{type:"vcard",data:{raw:n}};if(/^BEGIN:VEVENT/i.test(n))return{type:"vevent",data:{raw:n}};if(/^WIFI:/i.test(n)){const g=(f=n.match(/S:([^;]+)/))==null?void 0:f[1],N=(h=n.match(/P:([^;]+)/))==null?void 0:h[1],R=(k=n.match(/T:([^;]+)/))==null?void 0:k[1],G=n.includes("H:true");return{type:"wifi",data:{ssid:g,password:N,type:R,hidden:G}}}return{type:"text"}},Cn=()=>{try{const n=new(window.AudioContext||window.webkitAudioContext),f=n.createOscillator(),h=n.createGain();f.connect(h),h.connect(n.destination),f.type="square",f.frequency.value=1200,h.gain.value=.1,f.start(),setTimeout(()=>{f.stop(),n.close()},80)}catch{}},kn=()=>{typeof navigator<"u"&&navigator.vibrate&&navigator.vibrate([50,30,50])},Sn=()=>typeof window<"u"&&"BarcodeDetector"in window,_n=n=>({sd:{width:640,height:480},hd:{width:1280,height:720},fhd:{width:1920,height:1080}})[n],Nn=Object.assign(e.forwardRef((n,f)=>{const{config:h,onScan:k,onError:g,onCameraReady:N,autoStart:R=!1,showScanFrame:G=!0,children:i,className:l}=n,b={...vn,...h},E=e.useRef(null),v=e.useRef(null),d=e.useRef(null),p=e.useRef(null),I=e.useRef(null),B=e.useRef(null),[q,z]=e.useState(!1),[Y,K]=e.useState(!1),[F,W]=e.useState(null),[j,U]=e.useState(null),[D,P]=e.useState(null),[T,O]=e.useState(b.facingMode),[y,s]=e.useState(!1),[r,a]=e.useState(!1),[c,o]=e.useState(null),S=Sn(),A=e.useCallback(async()=>{var Q;if(!E.current)return;const J=_n(b.resolution),V={video:{facingMode:T,width:{ideal:J.width},height:{ideal:J.height}},audio:!1};try{const ee=await navigator.mediaDevices.getUserMedia(V);d.current=ee,E.current.srcObject=ee,await E.current.play();const te=ee.getVideoTracks()[0],ne=(Q=te.getCapabilities)==null?void 0:Q.call(te);s(!!(ne!=null&&ne.torch)),K(!0),P(!0),U(null),N==null||N()}catch(ee){const te=ee instanceof Error?ee.message:"Failed to access camera";U(te),P(!1),g==null||g(new Error(te))}},[b.resolution,T,N,g]),m=e.useCallback(()=>{d.current&&(d.current.getTracks().forEach(J=>J.stop()),d.current=null),E.current&&(E.current.srcObject=null),K(!1),a(!1)},[]),w=e.useCallback(async()=>{O(T==="user"?"environment":"user"),q&&m()},[T,q,m]),u=e.useCallback(async()=>{if(!d.current||!y)return;const J=d.current.getVideoTracks()[0],V=!r;try{await J.applyConstraints({advanced:[{torch:V}]}),a(V)}catch{}},[y,r]),C=e.useCallback(async()=>{if(S)try{const J=window.BarcodeDetector;p.current=new J({formats:["qr_code"]})}catch(J){const V=J instanceof Error?J.message:"Failed to initialize QR detector";U(V),g==null||g(new Error(V))}},[S,g]),x=e.useCallback((J,V)=>{const Q={text:J,boundingBox:V.boundingBox?{x:V.boundingBox.x,y:V.boundingBox.y,width:V.boundingBox.width,height:V.boundingBox.height}:void 0,cornerPoints:V.cornerPoints,timestamp:new Date};if(b.parseDataType){const ee=xn(J);Q.dataType=ee.type,Q.parsedData=ee.data}return Q},[b.parseDataType]),H=e.useCallback(async()=>{if(!(!E.current||!p.current||!Y))try{const V=await p.current.detect(E.current);if(V.length>0){const Q=V[0];if(b.continuous&&Q.rawValue===B.current)return;B.current=Q.rawValue;const ee=x(Q.rawValue,Q);b.highlightDetected&&ee.boundingBox&&(o(ee.boundingBox),setTimeout(()=>o(null),500)),b.beepOnScan&&Cn(),b.vibrateOnScan&&kn(),W(ee),k==null||k(ee),setTimeout(()=>{B.current=null},1e3)}}catch{}},[Y,b.continuous,b.highlightDetected,b.beepOnScan,b.vibrateOnScan,x,k]),_=e.useCallback(async()=>{z(!0),U(null),await C(),await A()},[C,A]),M=e.useCallback(()=>{z(!1),I.current&&(clearInterval(I.current),I.current=null),m()},[m]),L=e.useCallback(async()=>{q?M():await _()},[q,_,M]),X=e.useCallback(()=>{if(!E.current||!v.current)return null;const J=v.current,V=E.current;J.width=V.videoWidth,J.height=V.videoHeight;const Q=J.getContext("2d");return Q?(Q.drawImage(V,0,0),J.toDataURL("image/png")):null},[]),$=e.useCallback(async J=>!S||!p.current?null:new Promise(V=>{const Q=new Image;Q.onload=async()=>{try{const te=await p.current.detect(Q);if(te.length>0){const ne=x(te[0].rawValue,te[0]);V(ne)}else V(null)}catch{V(null)}},Q.onerror=()=>V(null),Q.src=URL.createObjectURL(J)}),[S,x]);e.useEffect(()=>(q&&Y&&b.continuous&&(I.current=setInterval(H,b.scanInterval)),()=>{I.current&&(clearInterval(I.current),I.current=null)}),[q,Y,b.continuous,b.scanInterval,H]),e.useEffect(()=>(R&&_(),()=>{M()}),[]),e.useEffect(()=>{q&&!Y&&A()},[T,q,Y,A]),e.useImperativeHandle(f,()=>({getState:()=>({isScanning:q,isCameraReady:Y,lastResult:F,error:j,isSupported:S,hasPermission:D,torchAvailable:y,torchOn:r}),start:_,stop:M,toggle:L,switchCamera:w,toggleTorch:u,takeSnapshot:X,scanImage:$}),[q,Y,F,j,S,D,y,r,_,M,L,w,u,X,$]);const Z=["nice-qr-scanner",q&&"nice-qr-scanner--scanning",Y&&"nice-qr-scanner--ready",j&&"nice-qr-scanner--error",l].filter(Boolean).join(" ");return t.jsxs("div",{className:Z,children:[t.jsx("video",{ref:E,className:"nice-qr-scanner__video",playsInline:!0,muted:!0}),t.jsx("canvas",{ref:v,className:"nice-qr-scanner__canvas"}),G&&q&&t.jsxs("div",{className:"nice-qr-scanner__frame",children:[t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--tr"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--bl"}),t.jsx("div",{className:"nice-qr-scanner__frame-corner nice-qr-scanner__frame-corner--br"})]}),c&&E.current&&t.jsx("div",{className:"nice-qr-scanner__bounding-box",style:{left:`${c.x/E.current.videoWidth*100}%`,top:`${c.y/E.current.videoHeight*100}%`,width:`${c.width/E.current.videoWidth*100}%`,height:`${c.height/E.current.videoHeight*100}%`}}),j&&t.jsxs("div",{className:"nice-qr-scanner__error",children:[t.jsx("div",{className:"nice-qr-scanner__error-icon",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--alert","aria-hidden":"true"})}),t.jsx("p",{className:"nice-qr-scanner__error-text",children:j}),t.jsx("button",{className:"nice-qr-scanner__error-btn",onClick:()=>_(),children:"Try Again"})]}),!S&&t.jsx("div",{className:"nice-qr-scanner__unsupported",children:t.jsx("p",{children:"QR scanning is not supported in this browser."})}),i&&t.jsx("div",{className:"nice-qr-scanner__overlay",children:i})]})}),{displayName:"NiceQRScanner"}),pe=e.createContext(null),jn=()=>{const n=e.useContext(pe);if(!n)throw new Error("useSymbology must be used within NiceSymbologyConfigProvider");return n},ie=[{id:"code128",name:"Code 128",category:"linear",description:"High-density barcode for alphanumeric data. Auto-switches between subsets A/B/C.",charset:"ASCII 0-127",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Shipping labels","Inventory","General purpose"],standard:"ISO/IEC 15417",detectorFormat:"code_128"},{id:"code128a",name:"Code 128A",category:"linear",description:"Code 128 subset A: uppercase + control characters.",charset:"ASCII 0-95 (uppercase, digits, control chars)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Systems with control characters","Legacy integration"],standard:"ISO/IEC 15417"},{id:"code128b",name:"Code 128B",category:"linear",description:"Code 128 subset B: uppercase + lowercase.",charset:"ASCII 32-127 (upper/lowercase, digits, symbols)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Alphanumeric data","Mixed case text"],standard:"ISO/IEC 15417"},{id:"code128c",name:"Code 128C",category:"linear",description:"Code 128 subset C: double-density numeric only.",charset:"0-9 (pairs only)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Long numeric values","Compact encoding"],standard:"ISO/IEC 15417"},{id:"code39",name:"Code 39",category:"linear",description:"Self-checking barcode supporting uppercase and digits.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Military (LOGMARS)","Automotive (AIAG)","Healthcare"],standard:"ISO/IEC 16388",detectorFormat:"code_39"},{id:"code93",name:"Code 93",category:"linear",description:"Compact barcode, denser than Code 39.",charset:"0-9, A-Z, -, ., $, /, +, %, SPACE",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Canadian postal","General logistics"],standard:"ANSI/AIM BC5",detectorFormat:"code_93"},{id:"codabar",name:"Codabar",category:"linear",description:"Numeric barcode used in libraries and blood banks.",charset:"0-9, -, $, :, /, ., +, A-D (start/stop)",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Blood banks","Libraries","FedEx"],standard:"ANSI/AIM BC3",detectorFormat:"codabar"},{id:"ean13",name:"EAN-13",category:"linear",description:"European Article Numbering — worldwide retail standard.",charset:"0-9",minLength:12,maxLength:12,fixedLength:13,hasCheckDigit:!0,useCases:["Retail worldwide","ISBN","ISSN"],standard:"ISO/IEC 15420",detectorFormat:"ean_13"},{id:"ean8",name:"EAN-8",category:"linear",description:"Compact version of EAN-13 for small products.",charset:"0-9",minLength:7,maxLength:7,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Space-constrained packaging"],standard:"ISO/IEC 15420",detectorFormat:"ean_8"},{id:"ean5",name:"EAN-5 Supplement",category:"linear",description:"5-digit addon for periodicals and books.",charset:"0-9",minLength:5,maxLength:5,fixedLength:5,hasCheckDigit:!0,useCases:["Book pricing","Magazine issues"],standard:"ISO/IEC 15420"},{id:"ean2",name:"EAN-2 Supplement",category:"linear",description:"2-digit addon for periodicals.",charset:"0-9",minLength:2,maxLength:2,fixedLength:2,hasCheckDigit:!1,useCases:["Magazine issue numbers"],standard:"ISO/IEC 15420"},{id:"upc_a",name:"UPC-A",category:"linear",description:"Universal Product Code — North American retail standard.",charset:"0-9",minLength:11,maxLength:11,fixedLength:12,hasCheckDigit:!0,useCases:["US/Canada retail","Point of Sale"],standard:"ISO/IEC 15420",detectorFormat:"upc_a"},{id:"upc_e",name:"UPC-E",category:"linear",description:"Compressed UPC for small packages.",charset:"0-9",minLength:6,maxLength:6,fixedLength:8,hasCheckDigit:!0,useCases:["Small retail products","Compact packaging"],standard:"ISO/IEC 15420",detectorFormat:"upc_e"},{id:"itf",name:"Interleaved 2 of 5",category:"linear",description:"Numeric pairs encoded in interleaved format.",charset:"0-9 (even length)",minLength:2,maxLength:80,fixedLength:null,hasCheckDigit:!1,useCases:["Warehouse distribution","Packaging"],standard:"ISO/IEC 16390",detectorFormat:"itf"},{id:"itf14",name:"ITF-14",category:"linear",description:"GTIN-14 barcode for shipping containers.",charset:"0-9",minLength:13,maxLength:13,fixedLength:14,hasCheckDigit:!0,useCases:["Shipping containers","Outer packaging"],standard:"ISO/IEC 16390"},{id:"msi",name:"MSI (Modified Plessey)",category:"linear",description:"Numeric barcode used in inventory management.",charset:"0-9",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["Retail shelves","Inventory"],standard:"Proprietary"},{id:"pharmacode",name:"Pharmacode",category:"linear",description:"Pharmaceutical packaging identification.",charset:"3-131070 (numeric value)",minLength:1,maxLength:6,fixedLength:null,hasCheckDigit:!1,useCases:["Pharmaceutical packaging","Drug identification"],standard:"Laetus"},{id:"plessey",name:"Plessey",category:"linear",description:"Legacy barcode used in UK libraries.",charset:"0-9, A-F",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Legacy systems"],standard:"Proprietary"},{id:"telepen",name:"Telepen",category:"linear",description:"Full ASCII barcode used in UK libraries.",charset:"Full ASCII",minLength:1,maxLength:80,fixedLength:null,hasCheckDigit:!0,useCases:["UK libraries","Inventory"],standard:"AIM"},{id:"qr_code",name:"QR Code",category:"2d",description:"Quick Response code — high capacity 2D barcode.",charset:"Full Unicode",minLength:1,maxLength:7089,fixedLength:null,hasCheckDigit:!0,useCases:["Mobile scanning","URLs","vCards","Payments"],standard:"ISO/IEC 18004",detectorFormat:"qr_code"},{id:"data_matrix",name:"Data Matrix",category:"2d",description:"High-density 2D code for small items.",charset:"Full ASCII",minLength:1,maxLength:2335,fixedLength:null,hasCheckDigit:!0,useCases:["Electronics","PCB marking","Medical devices","Aerospace"],standard:"ISO/IEC 16022",detectorFormat:"data_matrix"},{id:"aztec",name:"Aztec Code",category:"2d",description:"Compact 2D code, no quiet zone required.",charset:"Full ASCII",minLength:1,maxLength:3832,fixedLength:null,hasCheckDigit:!0,useCases:["Transport tickets","Boarding passes","Government IDs"],standard:"ISO/IEC 24778",detectorFormat:"aztec"},{id:"pdf417",name:"PDF417",category:"2d",description:"Stacked linear barcode with high capacity.",charset:"Full ASCII",minLength:1,maxLength:1850,fixedLength:null,hasCheckDigit:!0,useCases:["ID cards","Driver's licenses","Airline boarding","Postage"],standard:"ISO/IEC 15438",detectorFormat:"pdf417"},{id:"maxicode",name:"MaxiCode",category:"2d",description:"Fixed-size 2D code used by UPS.",charset:"Full ASCII",minLength:1,maxLength:93,fixedLength:null,hasCheckDigit:!0,useCases:["UPS shipping","High-speed sorting"],standard:"ISO/IEC 16023"},{id:"gs1_128",name:"GS1-128",category:"gs1",description:"Application Identifier-based supply chain barcode.",charset:"Full ASCII (with AI prefixes)",minLength:1,maxLength:48,fixedLength:null,hasCheckDigit:!0,useCases:["Supply chain","Healthcare","Food traceability"],standard:"ISO/IEC 15417 + GS1 General Specifications"},{id:"gs1_databar",name:"GS1 DataBar",category:"gs1",description:"Compact GS1 barcode for fresh food and coupons.",charset:"0-9 (GTIN-based)",minLength:14,maxLength:74,fixedLength:null,hasCheckDigit:!0,useCases:["Fresh food","Pharmacy","Coupons","Variable weight"],standard:"ISO/IEC 24724"}],de=(n,f)=>{const h=ie.find(i=>i.id===f);if(!h)return{valid:!1,errors:["Unknown symbology"],warnings:[]};const k=[],g=[],N=h.fixedLength&&h.hasCheckDigit?h.fixedLength-1:h.fixedLength,R=!!h.fixedLength&&h.hasCheckDigit&&n.length===h.fixedLength;switch(h.fixedLength?n.length!==N&&!R&&k.push(h.hasCheckDigit?`Expected ${N} digits, or ${h.fixedLength} with the check digit; got ${n.length}`:`Expected ${h.fixedLength} characters, got ${n.length}`):(n.length<h.minLength&&k.push(`Minimum ${h.minLength} characters required`),n.length>h.maxLength&&k.push(`Maximum ${h.maxLength} characters allowed`)),f){case"ean13":case"ean8":case"ean5":case"ean2":case"upc_a":case"upc_e":case"itf":case"itf14":case"msi":case"pharmacode":/^\d+$/.test(n)||k.push("Only numeric digits allowed");break;case"code128c":/^\d+$/.test(n)||k.push("Only numeric digits allowed"),n.length%2!==0&&g.push("Length should be even for optimal encoding");break;case"code39":case"code93":/^[0-9A-Z\-. $/+%]+$/.test(n.toUpperCase())||k.push("Invalid characters for this symbology");break;case"codabar":/^[0-9\-$:/.+ABCD]+$/.test(n.toUpperCase())||k.push("Invalid characters for Codabar");break;case"plessey":/^[0-9A-F]+$/i.test(n)||k.push("Only hex characters (0-9, A-F) allowed");break}let G;if(h.hasCheckDigit&&k.length===0)switch(f){case"ean13":case"ean8":case"upc_a":case"itf14":{const i=(R?n.slice(0,-1):n).split("").map(Number);let l=0;for(let b=0;b<i.length;b++)l+=i[b]*((i.length-1-b)%2===0?3:1);G=String((10-l%10)%10),R&&n[n.length-1]!==G&&k.push(`Check digit should be ${G}, not ${n[n.length-1]}`);break}}return f==="itf"&&n.length%2!==0&&k.push("ITF requires even number of digits"),{valid:k.length===0,errors:k,warnings:g,checkDigit:G,formattedValue:G&&!R?n+G:n}},Se={linear:"Linear (1D)","2d":"2D Matrix",postal:"Postal",gs1:"GS1 Standards"},In=Object.assign(e.forwardRef((n,f)=>{const{selected:h,onChange:k,category:g="all",multiSelect:N=!0,showDetails:R=!0,showValidation:G=!1,testValue:i="",readOnly:l=!1,className:b}=n,[E,v]=e.useState([]),[d,p]=e.useState(null),I=h??E,B=e.useMemo(()=>g==="all"?ie:ie.filter(y=>y.category===g),[g]),q=e.useMemo(()=>{const y={};for(const s of B)y[s.category]||(y[s.category]=[]),y[s.category].push(s);return y},[B]),z=e.useCallback(y=>{h||v(y),k==null||k(y)},[h,k]),Y=e.useCallback(y=>{N?I.includes(y)||z([...I,y]):z([y])},[I,N,z]),K=e.useCallback(y=>{z(I.filter(s=>s!==y))},[I,z]),F=e.useCallback(y=>{l||(I.includes(y)?K(y):Y(y))},[I,l,Y,K]),W=e.useCallback(()=>{z(B.map(y=>y.id))},[B,z]),j=e.useCallback(()=>{z([])},[z]),U=e.useCallback(y=>ie.find(s=>s.id===y),[]),D=e.useMemo(()=>!G||!i||!d?null:de(i,d),[G,i,d]);e.useImperativeHandle(f,()=>({getSelected:()=>I,select:Y,deselect:K,selectAll:W,clearSelection:j,validate:de,getInfo:U,getAll:()=>ie}),[I,Y,K,W,j,U]);const P=e.useMemo(()=>({symbologies:ie,selected:I,validate:de,getInfo:U}),[I,U]),T=d?U(d):null,O=["nice-symbology-config",l&&"nice-symbology-config--readonly",b].filter(Boolean).join(" ");return t.jsx(pe.Provider,{value:P,children:t.jsxs("div",{className:O,children:[N&&!l&&t.jsxs("div",{className:"nice-symbology-config__toolbar",children:[t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:W,children:"Select All"}),t.jsx("button",{className:"nice-symbology-config__btn nice-symbology-config__btn--secondary",onClick:j,children:"Clear"}),t.jsxs("span",{className:"nice-symbology-config__count",children:[I.length," / ",B.length," selected"]})]}),t.jsxs("div",{className:"nice-symbology-config__content",children:[t.jsx("div",{className:"nice-symbology-config__list",children:Object.entries(q).map(([y,s])=>t.jsxs("div",{className:"nice-symbology-config__group",children:[t.jsx("h3",{className:"nice-symbology-config__group-title",children:Se[y]||y}),t.jsx("div",{className:"nice-symbology-config__grid",children:s.map(r=>{const a=I.includes(r.id),c=d===r.id;return t.jsxs("div",{className:["nice-symbology-config__item",a&&"nice-symbology-config__item--selected",c&&"nice-symbology-config__item--active"].filter(Boolean).join(" "),onClick:()=>{F(r.id),p(r.id)},role:"option","aria-selected":a,tabIndex:0,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),F(r.id),p(r.id))},children:[N&&t.jsx("span",{className:`nice-symbology-config__checkbox ${a?"nice-symbology-config__checkbox--checked":""}`,children:a&&t.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"0.3em",height:"0.6em",marginBottom:"0.15em",borderRight:"0.12em solid currentColor",borderBottom:"0.12em solid currentColor",transform:"rotate(45deg)"}})}),t.jsxs("div",{className:"nice-symbology-config__item-info",children:[t.jsx("span",{className:"nice-symbology-config__item-name",children:r.name}),t.jsx("span",{className:"nice-symbology-config__item-desc",children:r.fixedLength?`${r.fixedLength} digits`:`${r.minLength}-${r.maxLength} chars`})]})]},r.id)})})]},y))}),R&&T&&t.jsxs("div",{className:"nice-symbology-config__details",children:[t.jsx("h3",{className:"nice-symbology-config__details-title",children:T.name}),t.jsx("p",{className:"nice-symbology-config__details-desc",children:T.description}),t.jsxs("div",{className:"nice-symbology-config__details-props",children:[t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Category"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:Se[T.category]})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Character Set"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.charset})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Length"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.fixedLength?`Fixed: ${T.fixedLength}`:`${T.minLength} – ${T.maxLength}`})]}),t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Check Digit"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.hasCheckDigit?"Yes":"No"})]}),T.standard&&t.jsxs("div",{className:"nice-symbology-config__prop",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Standard"}),t.jsx("span",{className:"nice-symbology-config__prop-value",children:T.standard})]})]}),t.jsxs("div",{className:"nice-symbology-config__use-cases",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Use Cases"}),t.jsx("div",{className:"nice-symbology-config__tags",children:T.useCases.map(y=>t.jsx("span",{className:"nice-symbology-config__tag",children:y},y))})]}),G&&D&&t.jsxs("div",{className:"nice-symbology-config__validation",children:[t.jsx("span",{className:"nice-symbology-config__prop-label",children:"Validation"}),t.jsxs("div",{className:`nice-symbology-config__validation-result ${D.valid?"nice-symbology-config__validation-result--valid":"nice-symbology-config__validation-result--invalid"}`,children:[t.jsx("span",{children:D.valid?"Valid":"Invalid"}),D.checkDigit&&t.jsxs("span",{children:["Check digit: ",D.checkDigit]})]}),D.errors.map((y,s)=>t.jsx("div",{className:"nice-symbology-config__validation-error",children:y},s)),D.warnings.map((y,s)=>t.jsx("div",{className:"nice-symbology-config__validation-warning",children:y},s))]})]})]})]})})}),{displayName:"NiceSymbologyConfig"}),En=({children:n})=>{const f=e.useCallback(k=>ie.find(g=>g.id===k),[]),h={symbologies:ie,selected:[],validate:de,getInfo:f};return t.jsx(pe.Provider,{value:h,children:n})},Ye=e.createContext(null),Dn=()=>{const n=e.useContext(Ye);if(!n)throw new Error("useBackgroundSync must be used within NiceBackgroundSyncProvider");return n},An={dbName:"nice-background-sync",storeName:"sync-queue",defaultMaxAttempts:5,retryDelay:1e3,backoffFactor:2,maxRetryDelay:6e4,autoSyncOnConnect:!0,periodicSyncInterval:0},Pn=()=>`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Ln=n=>new Promise(f=>setTimeout(f,n)),Xe=Object.assign(e.forwardRef((n,f)=>{const{config:h,handlers:k,onSyncStart:g,onSyncComplete:N,onTaskSuccess:R,onTaskFailed:G,onOnlineChange:i,children:l}=n,b={...An,...h},E=e.useRef(null),v=e.useRef(!1),[d,p]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,pendingCount:0,failedCount:0,syncProgress:0}),I=e.useCallback(async()=>E.current?E.current:new Promise((a,c)=>{const o=indexedDB.open(b.dbName,1);o.onerror=()=>c(o.error),o.onupgradeneeded=()=>{const S=o.result;if(!S.objectStoreNames.contains(b.storeName)){const A=S.createObjectStore(b.storeName,{keyPath:"id"});A.createIndex("tag","tag",{unique:!1}),A.createIndex("status","status",{unique:!1}),A.createIndex("priority","priority",{unique:!1})}},o.onsuccess=()=>{E.current=o.result,a(o.result)}}),[b.dbName,b.storeName]),B=e.useCallback(async(a,c,o)=>{const S=await I(),A={id:Pn(),tag:a,data:c,status:"pending",createdAt:new Date,attempts:0,maxAttempts:(o==null?void 0:o.maxAttempts)??b.defaultMaxAttempts,priority:(o==null?void 0:o.priority)??0};return new Promise((m,w)=>{const x=S.transaction(b.storeName,"readwrite").objectStore(b.storeName).add(A);x.onerror=()=>w(x.error),x.onsuccess=()=>{p(H=>({...H,pendingCount:H.pendingCount+1})),m(A.id)}})},[I,b.storeName,b.defaultMaxAttempts]),q=e.useCallback(async a=>{const c=await I();return new Promise((o,S)=>{const w=c.transaction(b.storeName,"readwrite").objectStore(b.storeName).delete(a);w.onerror=()=>S(w.error),w.onsuccess=()=>o(!0)})},[I,b.storeName]),z=e.useCallback(async a=>{const c=await I();return new Promise((o,S)=>{const m=c.transaction(b.storeName,"readonly").objectStore(b.storeName),w=a?m.index("tag").getAll(a):m.getAll();w.onerror=()=>S(w.error),w.onsuccess=()=>o(w.result)})},[I,b.storeName]),Y=e.useCallback(async a=>(await z(a)).filter(o=>o.status==="pending"),[z]),K=e.useCallback(async a=>(await z(a)).filter(o=>o.status==="failed"),[z]),F=e.useCallback(async a=>{const c=await I();return new Promise((o,S)=>{const w=c.transaction(b.storeName,"readwrite").objectStore(b.storeName).put(a);w.onerror=()=>S(w.error),w.onsuccess=()=>o()})},[I,b.storeName]),W=e.useCallback(async()=>{const a=await z(),c=a.filter(S=>S.status==="pending").length,o=a.filter(S=>S.status==="failed").length;p(S=>({...S,pendingCount:c,failedCount:o}))},[z]),j=e.useCallback(async a=>{const c=k[a.tag];if(!c)return console.warn(`No handler registered for tag: ${a.tag}`),!1;a.status="syncing",a.lastAttemptAt=new Date,a.attempts++,await F(a);try{return await c.handler(a),a.status="success",await F(a),R==null||R(a),await q(a.id),!0}catch(o){const S=o instanceof Error?o.message:"Unknown error";return a.error=S,a.attempts>=a.maxAttempts?(a.status="failed",G==null||G(a,o instanceof Error?o:new Error(S))):a.status="pending",await F(a),!1}},[k,F,q,R,G]),U=e.useCallback(async a=>{if(d.isSyncing)return{success:0,failed:0};v.current=!1,p(o=>({...o,isSyncing:!0,syncProgress:0,error:void 0})),g==null||g();const c={success:0,failed:0};try{const o=await Y(a);o.sort((A,m)=>m.priority-A.priority);const S=o.length;for(let A=0;A<o.length&&!v.current;A++){const m=o[A],w=await j(m);if(w?c.success++:m.attempts>=m.maxAttempts&&c.failed++,!w&&m.attempts<m.maxAttempts){const u=Math.min(b.retryDelay*Math.pow(b.backoffFactor,m.attempts-1),b.maxRetryDelay);await Ln(u)}p(u=>({...u,syncProgress:Math.round((A+1)/S*100)}))}}catch(o){const S=o instanceof Error?o.message:"Sync failed";p(A=>({...A,error:S}))}return await W(),p(o=>({...o,isSyncing:!1,lastSyncAt:new Date,syncProgress:100})),N==null||N(c),c},[d.isSyncing,Y,j,b.retryDelay,b.backoffFactor,b.maxRetryDelay,W,g,N]),D=e.useCallback(()=>{v.current=!0},[]),P=e.useCallback(async a=>{const o=(await z()).find(S=>S.id===a);o&&o.status==="failed"&&(o.status="pending",o.attempts=0,o.error=void 0,await F(o),await W())},[z,F,W]),T=e.useCallback(async a=>{const c=await K(a);for(const o of c)o.status="pending",o.attempts=0,o.error=void 0,await F(o);await W()},[K,F,W]),O=e.useCallback(async a=>{const c=await I(),o=await z(a);return new Promise((S,A)=>{const m=c.transaction(b.storeName,"readwrite"),w=m.objectStore(b.storeName);m.onerror=()=>A(m.error),m.oncomplete=async()=>{await W(),S()};for(const u of o)w.delete(u.id)})},[I,z,b.storeName,W]),y=e.useCallback(async a=>{const c=await I(),o=await K(a);return new Promise((S,A)=>{const m=c.transaction(b.storeName,"readwrite"),w=m.objectStore(b.storeName);m.onerror=()=>A(m.error),m.oncomplete=async()=>{await W(),S()};for(const u of o)w.delete(u.id)})},[I,K,b.storeName,W]),s=e.useCallback(async a=>{if(!("serviceWorker"in navigator))return!1;try{const c=await navigator.serviceWorker.ready;if("sync"in c)return await c.sync.register(a),!0}catch(c){console.warn("Background Sync registration failed:",c)}return!1},[]);e.useEffect(()=>{const a=()=>{p(o=>({...o,isOnline:!0})),i==null||i(!0),b.autoSyncOnConnect&&U()},c=()=>{p(o=>({...o,isOnline:!1})),i==null||i(!1)};return window.addEventListener("online",a),window.addEventListener("offline",c),()=>{window.removeEventListener("online",a),window.removeEventListener("offline",c)}},[b.autoSyncOnConnect,U,i]),e.useEffect(()=>{if(b.periodicSyncInterval<=0)return;const a=setInterval(()=>{d.isOnline&&!d.isSyncing&&U()},b.periodicSyncInterval);return()=>clearInterval(a)},[b.periodicSyncInterval,d.isOnline,d.isSyncing,U]),e.useEffect(()=>{W()},[W]),e.useImperativeHandle(f,()=>({getState:()=>d,addTask:B,removeTask:q,getTasks:z,getPendingTasks:Y,getFailedTasks:K,retryTask:P,retryAllFailed:T,clearTasks:O,clearFailed:y,syncNow:U,cancelSync:D,registerBackgroundSync:s}),[d,B,q,z,Y,K,P,T,O,y,U,D,s]);const r={...d,addTask:B,removeTask:q,getTasks:z,getPendingTasks:Y,getFailedTasks:K,retryTask:P,retryAllFailed:T,clearTasks:O,clearFailed:y,syncNow:U,cancelSync:D};return t.jsx(Ye.Provider,{value:r,children:l})}),{displayName:"NiceBackgroundSync"}),Ke=Xe;process.env.NODE_ENV!=="production"&&(Ke.displayName="NiceBackgroundSyncProvider");const Qe=e.createContext(null),Je=()=>{const n=e.useContext(Qe);if(!n)throw new Error("useCacheStrategies must be used within NiceCacheStrategiesProvider");return n},Rn={cacheName:"nice-cache-strategies",defaultTTL:300*1e3,maxEntries:500,defaultStrategy:"stale-while-revalidate",networkTimeout:5e3,serveStale:!0,staleThreshold:60*1e3};class On{constructor(){oe(this,"dbName","nice-cache-db");oe(this,"storeName","cache-entries");oe(this,"db",null)}async init(){if(!this.db)return new Promise((f,h)=>{const k=indexedDB.open(this.dbName,1);k.onerror=()=>h(k.error),k.onupgradeneeded=()=>{const g=k.result;g.objectStoreNames.contains(this.storeName)||g.createObjectStore(this.storeName,{keyPath:"key"})},k.onsuccess=()=>{this.db=k.result,f()}})}async get(f){if(await this.init(),!!this.db)return new Promise((h,k)=>{const R=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(f);R.onerror=()=>k(R.error),R.onsuccess=()=>{const G=R.result;h(G?G.value:void 0)}})}async set(f,h){if(await this.init(),!!this.db)return new Promise((k,g)=>{const G=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put({key:f,value:h});G.onerror=()=>g(G.error),G.onsuccess=()=>k()})}async delete(f){return await this.init(),this.db?new Promise((h,k)=>{const R=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(f);R.onerror=()=>k(R.error),R.onsuccess=()=>h(!0)}):!1}async keys(){return await this.init(),this.db?new Promise((f,h)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAllKeys();N.onerror=()=>h(N.error),N.onsuccess=()=>f(N.result)}):[]}async clear(){if(await this.init(),!!this.db)return new Promise((f,h)=>{const N=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();N.onerror=()=>h(N.error),N.onsuccess=()=>f()})}async getAll(){return await this.init(),this.db?new Promise((f,h)=>{const N=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();N.onerror=()=>h(N.error),N.onsuccess=()=>f(N.result)}):[]}}const Ze=Object.assign(e.forwardRef((n,f)=>{const{config:h,routeStrategies:k={},precacheUrls:g=[],onFetch:N,onCacheHit:R,onCacheMiss:G,onNetworkError:i,children:l}=n,b={...Rn,...h},E=e.useRef(new On),[v,d]=e.useState({isFetching:!1,totalSize:0,entryCount:0,hits:0,misses:0,strategy:b.defaultStrategy}),p=e.useCallback(s=>{for(const[r,a]of Object.entries(k))if(new RegExp(r).test(s))return a;return v.strategy},[k,v.strategy]),I=e.useCallback(s=>{d(r=>({...r,strategy:s}))},[]),B=e.useCallback(async s=>{const r=await E.current.get(s);if(!r)return;const a=Date.now(),c=r.expiresAt&&r.expiresAt<a,o=r.timestamp+b.staleThreshold<a;if(c&&!b.serveStale){await E.current.delete(s);return}return{data:r.data,timestamp:new Date(r.timestamp),expiresAt:r.expiresAt?new Date(r.expiresAt):void 0,etag:r.etag,key:s,isStale:o||!!c,source:"cache",url:r.url}},[b.staleThreshold,b.serveStale]),q=e.useCallback(async()=>{const s=await E.current.getAll();let r=0,a,c;for(const o of s){const S=JSON.stringify(o.value.data).length;r+=S,(!a||o.value.timestamp<a)&&(a=o.value.timestamp),(!c||o.value.timestamp>c)&&(c=o.value.timestamp)}return{size:r,entryCount:s.length,oldestEntry:a?new Date(a):void 0,newestEntry:c?new Date(c):void 0}},[]),z=e.useCallback(async()=>{const s=await q();d(r=>({...r,entryCount:s.entryCount,totalSize:s.size}))},[q]),Y=e.useCallback(async(s,r,a)=>{const c=Date.now(),o={data:r,timestamp:c,expiresAt:a?c+a:c+b.defaultTTL};if(await E.current.set(s,o),(await E.current.keys()).length>b.maxEntries){const A=await E.current.getAll();A.sort((w,u)=>w.value.timestamp-u.value.timestamp);const m=A.slice(0,A.length-b.maxEntries);for(const w of m)await E.current.delete(w.key)}await z()},[b.defaultTTL,b.maxEntries,z]),K=e.useCallback(async s=>{const r=await E.current.delete(s);return await z(),r},[z]),F=e.useCallback(async()=>{await E.current.clear(),d(s=>({...s,entryCount:0,totalSize:0}))},[]),W=e.useCallback(async()=>E.current.keys(),[]),j=e.useCallback(async s=>await B(s)!==void 0,[B]),U=e.useCallback(async s=>{const r=await E.current.keys();let a=0;for(const c of r)s.test(c)&&(await E.current.delete(c),a++);return await z(),a},[z]),D=e.useCallback(async(s,r,a)=>{const c=new AbortController,o=setTimeout(()=>c.abort(),a);try{const S=await fetch(s,{...r,signal:c.signal});return clearTimeout(o),S}catch(S){throw clearTimeout(o),S}},[]),P=e.useCallback(async(s,r={})=>{const{strategy:a=p(s),ttl:c,cacheKey:o=s,forceRefresh:S=!1,timeout:A=b.networkTimeout,...m}=r;d(u=>({...u,isFetching:!0}));const w=async()=>{try{const u=await D(s,m,A);if(!u.ok)throw new Error(`HTTP ${u.status}`);const C=await u.json(),x=u.headers.get("etag")||void 0;await Y(o,C,c);const H={data:C,timestamp:new Date,etag:x,key:o,isStale:!1,source:"network",url:s};return d(_=>({..._,isFetching:!1})),N==null||N(H),H}catch(u){throw i==null||i(u instanceof Error?u:new Error(String(u)),s),u}};try{switch(a){case"cache-only":{const u=await B(o);if(u)return d(C=>({...C,isFetching:!1,hits:C.hits+1})),R==null||R(u),u;throw d(C=>({...C,isFetching:!1,misses:C.misses+1})),G==null||G(s),new Error("No cache entry found")}case"network-only":return d(u=>({...u,misses:u.misses+1})),await w();case"cache-first":{if(!S){const u=await B(o);if(u&&!u.isStale)return d(C=>({...C,isFetching:!1,hits:C.hits+1})),R==null||R(u),u}return d(u=>({...u,misses:u.misses+1})),await w()}case"network-first":try{return d(u=>({...u,misses:u.misses+1})),await w()}catch(u){const C=await B(o);if(C)return d(x=>({...x,isFetching:!1,hits:x.hits+1})),R==null||R(C),C;throw u}case"stale-while-revalidate":default:{const u=await B(o);return u&&!S?(d(C=>({...C,hits:C.hits+1})),R==null||R(u),u.isStale&&w().catch(()=>{}),d(C=>({...C,isFetching:!1})),u):(d(C=>({...C,misses:C.misses+1})),await w())}}}catch(u){throw d(C=>({...C,isFetching:!1})),u}},[p,b.networkTimeout,D,B,Y,N,R,G,i]),T=e.useCallback(async(s,r)=>(await P(s,r)).data,[P]),O=e.useCallback(async(s,r)=>{await Promise.all(s.map(a=>P(a,{...r,strategy:"network-first"}).catch(()=>{})))},[P]);e.useEffect(()=>{g.length>0&&O(g)},[g,O]),e.useEffect(()=>{(async()=>{await E.current.init();const r=await q();d(a=>({...a,totalSize:r.size,entryCount:r.entryCount}))})()},[q]),e.useImperativeHandle(f,()=>({getState:()=>v,fetch:P,fetchJSON:T,getFromCache:B,addToCache:Y,removeFromCache:K,clearCache:F,getCacheKeys:W,getCacheStats:q,prefetch:O,isCached:j,invalidateByPattern:U,setStrategy:I,getStrategyForUrl:p}),[v,P,T,B,Y,K,F,W,q,O,j,U,I,p]);const y={...v,fetch:P,fetchJSON:T,getFromCache:B,addToCache:Y,removeFromCache:K,clearCache:F,getCacheKeys:W,prefetch:O,isCached:j,setStrategy:I,getStrategyForUrl:p};return t.jsx(Qe.Provider,{value:y,children:l})}),{displayName:"NiceCacheStrategies"}),et=Ze;process.env.NODE_ENV!=="production"&&(et.displayName="NiceCacheStrategiesProvider");function Tn(n,f){const h=Je(),[k,g]=e.useState(void 0),[N,R]=e.useState(!1),[G,i]=e.useState(void 0),l=e.useCallback(async()=>{if(n){R(!0),i(void 0);try{const b=await h.fetchJSON(n,f);g(b)}catch(b){i(b instanceof Error?b:new Error(String(b)))}finally{R(!1)}}},[n,f,h]);return e.useEffect(()=>{l()},[l]),{data:k,isLoading:N,error:G,refetch:l}}const tt=e.createContext(null),Mn=()=>{const n=e.useContext(tt);if(!n)throw new Error("useConflictResolution must be used within NiceConflictResolutionProvider");return n},Fn={defaultStrategy:"manual",autoResolve:!1,maxPendingConflicts:100,persistConflicts:!0,storageKey:"nice-conflict-resolution"},Bn=()=>`conflict-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,$n=n=>JSON.stringify(n),qn=(n,f)=>JSON.stringify(n)===JSON.stringify(f),Un=(n,f,h)=>({...n,...f}),nt=Object.assign(e.forwardRef((n,f)=>{const{config:h,handlers:k={},showConflictUI:g=!0,uiPosition:N="modal",autoOpenUI:R=!0,onConflictDetected:G,onConflictResolved:i,onResolutionFailed:l,renderConflictList:b,renderConflictItem:E,children:v}=n,d={...Fn,...h},[p,I]=e.useState([]),[B,q]=e.useState(!1),[z,Y]=e.useState(!1),K=e.useCallback(_=>k[_]||{},[k]),F=e.useCallback(_=>({pending:_.filter(M=>M.status==="pending").length,resolving:_.filter(M=>M.status==="resolving").length,resolved:_.filter(M=>M.status==="resolved").length,failed:_.filter(M=>M.status==="failed").length}),[]),W={conflicts:p,isResolving:B,counts:F(p)},j=e.useCallback(()=>{if(d.persistConflicts)try{const _=localStorage.getItem(d.storageKey);if(_){const L=JSON.parse(_).map(X=>({...X,createdAt:new Date(X.createdAt),resolvedAt:X.resolvedAt?new Date(X.resolvedAt):void 0,clientVersion:{...X.clientVersion,timestamp:new Date(X.clientVersion.timestamp)},serverVersion:{...X.serverVersion,timestamp:new Date(X.serverVersion.timestamp)},baseVersion:X.baseVersion?{...X.baseVersion,timestamp:new Date(X.baseVersion.timestamp)}:void 0}));I(L)}}catch(_){console.warn("Failed to load persisted conflicts:",_)}},[d.persistConflicts,d.storageKey]),U=e.useCallback(_=>{if(d.persistConflicts)try{const M=_.filter(L=>L.status==="pending"||L.status==="failed");localStorage.setItem(d.storageKey,JSON.stringify(M))}catch(M){console.warn("Failed to persist conflicts:",M)}},[d.persistConflicts,d.storageKey]);e.useEffect(()=>{j()},[j]),e.useEffect(()=>{U(p)},[p,U]);const D=e.useCallback((_,M,L,X,$)=>{const Z=K(_),J=Z.compare||qn,V=Z.hash||$n,Q=Z.getConflictingFields;if(J(L.data,X.data)||L.timestamp<X.timestamp&&$&&J(L.data,$.data))return null;const ee={id:Bn(),entityType:_,entityId:M,clientVersion:{...L,hash:V(L.data)},serverVersion:{...X,hash:V(X.data)},baseVersion:$?{...$,hash:V($.data)}:void 0,status:"pending",createdAt:new Date,conflictingFields:Q?Q(L.data,X.data):void 0};return P(ee),ee},[K]),P=e.useCallback(_=>{I(M=>{const L=M.findIndex($=>$.entityType===_.entityType&&$.entityId===_.entityId);let X;return L>=0?(X=[...M],X[L]=_):X=[...M,_],X.length>d.maxPendingConflicts&&(X=X.slice(-d.maxPendingConflicts)),X}),G==null||G(_),R&&g&&Y(!0),d.autoResolve&&d.defaultStrategy!=="manual"&&T(_.id,d.defaultStrategy)},[d.maxPendingConflicts,d.autoResolve,d.defaultStrategy,R,g,G]),T=e.useCallback(async(_,M,L)=>{var J;const X=p.findIndex(V=>V.id===_);if(X===-1)return;const $=p[X],Z=K($.entityType);q(!0),I(V=>{const Q=[...V];return Q[X]={...$,status:"resolving"},Q});try{let V;switch(M){case"client-wins":V=$.clientVersion.data;break;case"server-wins":V=$.serverVersion.data;break;case"latest-wins":V=$.clientVersion.timestamp>$.serverVersion.timestamp?$.clientVersion.data:$.serverVersion.data;break;case"merge":{V=await(Z.merge||Un)($.clientVersion.data,$.serverVersion.data,(J=$.baseVersion)==null?void 0:J.data);break}case"manual":if(L===void 0)throw new Error("Manual resolution requires merged data");V=L;break}const Q={...$,status:"resolved",resolvedVersion:{data:V,timestamp:new Date,source:M==="client-wins"?"client":"server"},resolvedWith:M,resolvedAt:new Date};I(ee=>{const te=[...ee];return te[X]=Q,te}),i==null||i(Q)}catch(V){const Q=V instanceof Error?V.message:"Resolution failed";I(ee=>{const te=[...ee];return te[X]={...$,status:"failed",error:Q},te}),l==null||l($,V instanceof Error?V:new Error(Q))}finally{q(!1)}},[p,K,i,l]),O=e.useCallback(async _=>{const M=p.filter(L=>L.status==="pending");for(const L of M)await T(L.id,_)},[p,T]),y=e.useCallback(_=>p.find(M=>M.id===_),[p]),s=e.useCallback((_,M)=>p.filter(L=>L.entityType===_&&(M===void 0||L.entityId===M)),[p]),r=e.useCallback(()=>p.filter(_=>_.status==="pending"),[p]),a=e.useCallback(_=>{I(M=>M.filter(L=>L.id!==_))},[]),c=e.useCallback(()=>{I(_=>_.filter(M=>M.status!=="resolved"))},[]),o=e.useCallback(()=>{I([])},[]),S=e.useCallback(()=>Y(!0),[]),A=e.useCallback(()=>Y(!1),[]);e.useImperativeHandle(f,()=>({getState:()=>W,detectConflict:D,addConflict:P,resolveConflict:T,resolveAll:O,getConflict:y,getConflictsByEntity:s,getPendingConflicts:r,dismissConflict:a,clearResolved:c,clearAll:o,openUI:S,closeUI:A}),[W,D,P,T,O,y,s,r,a,c,o,S,A]);const m={...W,detectConflict:D,addConflict:P,resolveConflict:T,resolveAll:O,getConflict:y,getConflictsByEntity:s,getPendingConflicts:r,dismissConflict:a,clearResolved:c,clearAll:o},w=r(),u=(_,M,L)=>{T(_,M,L)},C=_=>{a(_)},x=_=>E?E({conflict:_,onResolve:(M,L)=>u(_.id,M,L),onDismiss:()=>C(_.id)}):t.jsxs("div",{className:"nice-conflict-item",children:[t.jsxs("div",{className:"nice-conflict-item__header",children:[t.jsx("span",{className:"nice-conflict-item__type",children:_.entityType}),t.jsxs("span",{className:"nice-conflict-item__id",children:["ID: ",_.entityId]})]}),t.jsxs("div",{className:"nice-conflict-item__versions",children:[t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--client",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:"Your changes"}),t.jsx("span",{className:"nice-conflict-item__version-time",children:_.clientVersion.timestamp.toLocaleString()})]}),t.jsxs("div",{className:"nice-conflict-item__version nice-conflict-item__version--server",children:[t.jsx("span",{className:"nice-conflict-item__version-label",children:"Server version"}),t.jsx("span",{className:"nice-conflict-item__version-time",children:_.serverVersion.timestamp.toLocaleString()})]})]}),_.conflictingFields&&_.conflictingFields.length>0&&t.jsxs("div",{className:"nice-conflict-item__fields",children:[t.jsx("span",{children:"Conflicting fields:"}),_.conflictingFields.map(M=>t.jsx("code",{children:M},M))]}),t.jsxs("div",{className:"nice-conflict-item__actions",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>u(_.id,"client-wins"),disabled:B,children:"Keep Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>u(_.id,"server-wins"),disabled:B,children:"Use Server"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--merge",onClick:()=>u(_.id,"merge"),disabled:B,children:"Merge"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--dismiss",onClick:()=>C(_.id),disabled:B,children:"Dismiss"})]})]},_.id),H=()=>{if(!g||!z||w.length===0)return null;if(b)return b({conflicts:w,onResolve:u,onDismiss:C});const _=t.jsxs("div",{className:"nice-conflict-list",children:[t.jsxs("div",{className:"nice-conflict-list__header",children:[t.jsxs("h3",{children:["Sync Conflicts (",w.length,")"]}),t.jsx("button",{className:"nice-conflict-list__close",onClick:A,"aria-label":"Close",children:t.jsx("span",{className:"nice-platform-mark nice-platform-mark--close","aria-hidden":"true"})})]}),t.jsx("div",{className:"nice-conflict-list__items",children:w.map(x)}),w.length>1&&t.jsxs("div",{className:"nice-conflict-list__bulk",children:[t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--client",onClick:()=>O("client-wins"),disabled:B,children:"Keep All Mine"}),t.jsx("button",{className:"nice-conflict-btn nice-conflict-btn--server",onClick:()=>O("server-wins"),disabled:B,children:"Use All Server"})]})]});switch(N){case"modal":return t.jsx("div",{className:"nice-conflict-overlay",children:t.jsx("div",{className:"nice-conflict-modal",children:_})});case"drawer":return t.jsx("div",{className:"nice-conflict-drawer nice-conflict-drawer--open",children:_});case"toast":return t.jsx("div",{className:"nice-conflict-toast",children:_});case"inline":default:return _}};return t.jsxs(tt.Provider,{value:m,children:[v,H()]})}),{displayName:"NiceConflictResolution"}),st=nt;process.env.NODE_ENV!=="production"&&(st.displayName="NiceConflictResolutionProvider");const rt=e.createContext(null),at=()=>{const n=e.useContext(rt);if(!n)throw new Error("useIndexedDB must be used within NiceIndexedDBProvider");return n};function Vn(n){const f=at(),h=e.useCallback(d=>f.get(n,d),[f,n]),k=e.useCallback(d=>f.getAll(n,d),[f,n]),g=e.useCallback((d,p)=>f.add(n,d,p),[f,n]),N=e.useCallback((d,p)=>f.put(n,d,p),[f,n]),R=e.useCallback(d=>f.delete(n,d),[f,n]),G=e.useCallback(()=>f.clear(n),[f,n]),i=e.useCallback(d=>f.count(n,d),[f,n]),l=e.useCallback(d=>f.query(n,d),[f,n]),b=e.useCallback(d=>f.bulkAdd(n,d),[f,n]),E=e.useCallback(d=>f.bulkPut(n,d),[f,n]),v=e.useCallback(d=>f.bulkDelete(n,d),[f,n]);return{isOpen:f.isOpen,isLoading:f.isLoading,error:f.error,get:h,getAll:k,add:g,put:N,remove:R,clear:G,count:i,query:l,bulkAdd:b,bulkPut:E,bulkDelete:v}}const it=Object.assign(e.forwardRef((n,f)=>{const{config:h,autoOpen:k=!0,onOpen:g,onError:N,onClose:R,children:G}=n,i=e.useRef(null),[l,b]=e.useState({isOpen:!1,isLoading:!1,storeNames:[]}),E=e.useCallback(async()=>{if(i.current)return i.current;if(!("indexedDB"in window))throw new Error("IndexedDB is not supported in this browser");return b(s=>({...s,isLoading:!0,error:void 0})),new Promise((s,r)=>{const a=indexedDB.open(h.dbName,h.version);a.onerror=()=>{var o;const c=new Error(((o=a.error)==null?void 0:o.message)||"Failed to open database");b(S=>({...S,isLoading:!1,error:c.message})),N==null||N(c),r(c)},a.onblocked=()=>{var c;(c=h.onBlocked)==null||c.call(h)},a.onupgradeneeded=c=>{var m;const o=a.result,S=c.oldVersion,A=c.newVersion;for(const w of h.stores)if(!o.objectStoreNames.contains(w.name)){const u=o.createObjectStore(w.name,{keyPath:w.keyPath,autoIncrement:w.autoIncrement});if(w.indexes)for(const C of w.indexes)u.createIndex(C.name,C.keyPath,C.options)}(m=h.onUpgrade)==null||m.call(h,o,S,A)},a.onsuccess=()=>{const c=a.result;i.current=c,c.onclose=()=>{i.current=null,b(o=>({...o,isOpen:!1,db:void 0})),R==null||R()},c.onerror=o=>{var A;const S=o.target;N==null||N(new Error(((A=S.error)==null?void 0:A.message)||"Database error"))},b({db:c,isOpen:!0,isLoading:!1,version:c.version,storeNames:Array.from(c.objectStoreNames)}),g==null||g(c),s(c)}})},[h,g,N,R]),v=e.useCallback(()=>{i.current&&(i.current.close(),i.current=null,b(s=>({...s,isOpen:!1,db:void 0})),R==null||R())},[R]),d=e.useCallback(async()=>(v(),new Promise((s,r)=>{const a=indexedDB.deleteDatabase(h.dbName);a.onerror=()=>{var c;r(new Error(((c=a.error)==null?void 0:c.message)||"Failed to delete database"))},a.onsuccess=()=>{b({isOpen:!1,isLoading:!1,storeNames:[]}),s()}})),[h.dbName,v]),p=e.useCallback(async()=>i.current?i.current:E(),[E]),I=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const m=a.transaction(s,"readonly").objectStore(s).get(r);m.onerror=()=>{var w;return o(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>c(m.result)})},[p]),B=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const A=a.transaction(s,"readonly").objectStore(s),w=(r!=null&&r.index?A.index(r.index):A).getAll(r==null?void 0:r.range,r==null?void 0:r.limit);w.onerror=()=>{var u;return o(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>{let u=w.result;r!=null&&r.offset&&(u=u.slice(r.offset)),c(u)}})},[p]),q=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const A=a.transaction(s,"readonly").objectStore(s),w=(r!=null&&r.index?A.index(r.index):A).getAllKeys(r==null?void 0:r.range,r==null?void 0:r.limit);w.onerror=()=>{var u;return o(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>c(w.result)})},[p]),z=e.useCallback(async(s,r,a)=>{const c=await p();return new Promise((o,S)=>{const w=c.transaction(s,"readwrite").objectStore(s).add(r,a);w.onerror=()=>{var u;return S(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>o(w.result)})},[p]),Y=e.useCallback(async(s,r,a)=>{const c=await p();return new Promise((o,S)=>{const w=c.transaction(s,"readwrite").objectStore(s).put(r,a);w.onerror=()=>{var u;return S(new Error((u=w.error)==null?void 0:u.message))},w.onsuccess=()=>o(w.result)})},[p]),K=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const m=a.transaction(s,"readwrite").objectStore(s).delete(r);m.onerror=()=>{var w;return o(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>c()})},[p]),F=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const A=r.transaction(s,"readwrite").objectStore(s).clear();A.onerror=()=>{var m;return c(new Error((m=A.error)==null?void 0:m.message))},A.onsuccess=()=>a()})},[p]),W=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const m=a.transaction(s,"readonly").objectStore(s).count(r);m.onerror=()=>{var w;return o(new Error((w=m.error)==null?void 0:w.message))},m.onsuccess=()=>c(m.result)})},[p]),j=e.useCallback(async(s,r)=>{const a=await p(),c=[];return new Promise((o,S)=>{const m=a.transaction(s,"readonly").objectStore(s),u=(r.index?m.index(r.index):m).openCursor(r.range,r.direction);let C=0,x=0;u.onerror=()=>{var H;return S(new Error((H=u.error)==null?void 0:H.message))},u.onsuccess=()=>{const H=u.result;if(H){if(r.offset&&C<r.offset){C++,H.continue();return}if(r.limit&&x>=r.limit){o(c);return}c.push(H.value),x++,H.continue()}else o(c)}})},[p]),U=e.useCallback(async(s,r)=>{const c=(await p()).transaction(s.stores,s.mode||"readwrite");return new Promise((o,S)=>{c.onerror=()=>{var A;return S(new Error((A=c.error)==null?void 0:A.message))},c.onabort=()=>S(new Error("Transaction aborted")),r(c).then(A=>{c.oncomplete=()=>o(A)}).catch(S)})},[p]),D=e.useCallback(async(s,r)=>{const a=await p(),c=[];return new Promise((o,S)=>{const A=a.transaction(s,"readwrite"),m=A.objectStore(s);A.onerror=()=>{var w;return S(new Error((w=A.error)==null?void 0:w.message))},A.oncomplete=()=>o(c);for(const w of r){const u=m.add(w);u.onsuccess=()=>c.push(u.result)}})},[p]),P=e.useCallback(async(s,r)=>{const a=await p(),c=[];return new Promise((o,S)=>{const A=a.transaction(s,"readwrite"),m=A.objectStore(s);A.onerror=()=>{var w;return S(new Error((w=A.error)==null?void 0:w.message))},A.oncomplete=()=>o(c);for(const w of r){const u=m.put(w);u.onsuccess=()=>c.push(u.result)}})},[p]),T=e.useCallback(async(s,r)=>{const a=await p();return new Promise((c,o)=>{const S=a.transaction(s,"readwrite"),A=S.objectStore(s);S.onerror=()=>{var m;return o(new Error((m=S.error)==null?void 0:m.message))},S.oncomplete=()=>c();for(const m of r)A.delete(m)})},[p]),O=e.useCallback(async()=>{const s=await p(),r=[];for(const a of s.objectStoreNames){const o=s.transaction(a,"readonly").objectStore(a);r.push({name:o.name,keyPath:o.keyPath,autoIncrement:o.autoIncrement,indexNames:Array.from(o.indexNames)})}return{name:s.name,version:s.version,stores:r}},[p]);e.useEffect(()=>(k&&E().catch(()=>{}),()=>{v()}),[k,E,v]),e.useImperativeHandle(f,()=>({getState:()=>l,open:E,close:v,deleteDatabase:d,get:I,getAll:B,getAllKeys:q,add:z,put:Y,delete:K,clear:F,count:W,query:j,transaction:U,bulkAdd:D,bulkPut:P,bulkDelete:T,getInfo:O}),[l,E,v,d,I,B,q,z,Y,K,F,W,j,U,D,P,T,O]);const y={...l,open:E,close:v,deleteDatabase:d,get:I,getAll:B,getAllKeys:q,add:z,put:Y,delete:K,clear:F,count:W,query:j,transaction:U,bulkAdd:D,bulkPut:P,bulkDelete:T};return t.jsx(rt.Provider,{value:y,children:G})}),{displayName:"NiceIndexedDB"}),ct=it;process.env.NODE_ENV!=="production"&&(ct.displayName="NiceIndexedDBProvider");const ot=e.createContext(null),lt=()=>{const n=e.useContext(ot);if(!n)throw new Error("useOfflineForms must be used within NiceOfflineFormsProvider");return n},Hn={dbName:"nice-offline-forms",autoSaveInterval:5e3,maxDraftsPerForm:50,autoSubmitOnline:!0,retryFailed:!0,maxRetryAttempts:3,retryDelay:5e3},Wn=()=>`draft-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,ut=Object.assign(e.forwardRef((n,f)=>{const{config:h,submitHandlers:k={},onDraftSaved:g,onFormSubmitted:N,onSubmissionFailed:R,onSyncComplete:G,children:i}=n,l={...Hn,...h},b=e.useRef(null),E=e.useRef(k),[v,d]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,isSyncing:!1,draftCounts:{},pendingCount:0,failedCount:0}),p=e.useCallback(async()=>b.current?b.current:new Promise((s,r)=>{const a=indexedDB.open(l.dbName,1);a.onerror=()=>r(a.error),a.onupgradeneeded=()=>{const c=a.result;if(!c.objectStoreNames.contains("drafts")){const o=c.createObjectStore("drafts",{keyPath:"id"});o.createIndex("formId","formId",{unique:!1}),o.createIndex("status","status",{unique:!1})}},a.onsuccess=()=>{b.current=a.result,s(a.result)}}),[l.dbName]),I=e.useCallback(async(s,r,a)=>{const c=await p(),o={id:Wn(),formId:s,data:r,status:"draft",createdAt:new Date,modifiedAt:new Date,attempts:0,version:1,submittedOffline:!1,metadata:a};return new Promise((S,A)=>{const u=c.transaction("drafts","readwrite").objectStore("drafts").add(o);u.onerror=()=>A(u.error),u.onsuccess=()=>{g==null||g(o),O(),S(o.id)}})},[p,g]),B=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const A=r.transaction("drafts","readonly").objectStore("drafts").get(s);A.onerror=()=>c(A.error),A.onsuccess=()=>{const m=A.result;m&&(m.createdAt=new Date(m.createdAt),m.modifiedAt=new Date(m.modifiedAt),m.syncedAt&&(m.syncedAt=new Date(m.syncedAt))),a(m)}})},[p]),q=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const m=r.transaction("drafts","readonly").objectStore("drafts").index("formId").getAll(s);m.onerror=()=>c(m.error),m.onsuccess=()=>{const w=m.result.map(u=>({...u,createdAt:new Date(u.createdAt),modifiedAt:new Date(u.modifiedAt),syncedAt:u.syncedAt?new Date(u.syncedAt):void 0}));a(w)}})},[p]),z=e.useCallback(async()=>{const s=await p();return new Promise((r,a)=>{const S=s.transaction("drafts","readonly").objectStore("drafts").getAll();S.onerror=()=>a(S.error),S.onsuccess=()=>{const A=S.result.filter(m=>m.status==="pending"||m.status==="failed").map(m=>({...m,createdAt:new Date(m.createdAt),modifiedAt:new Date(m.modifiedAt),syncedAt:m.syncedAt?new Date(m.syncedAt):void 0}));r(A)}})},[p]),Y=e.useCallback(async(s,r)=>{const a=await B(s);if(!a)return;const c=await p(),o={...a,data:{...a.data,...r},modifiedAt:new Date,version:a.version+1};return new Promise((S,A)=>{const u=c.transaction("drafts","readwrite").objectStore("drafts").put(o);u.onerror=()=>A(u.error),u.onsuccess=()=>{g==null||g(o),S()}})},[p,B,g]),K=e.useCallback(async(s,r,a)=>{const c=await B(s);if(!c)return;const o=await p(),S={...c,status:r,error:a,attempts:r==="syncing"?c.attempts+1:c.attempts,syncedAt:r==="synced"?new Date:c.syncedAt};return new Promise((A,m)=>{const C=o.transaction("drafts","readwrite").objectStore("drafts").put(S);C.onerror=()=>m(C.error),C.onsuccess=()=>{O(),A()}})},[p,B]),F=e.useCallback(async s=>{const r=await p();return new Promise((a,c)=>{const A=r.transaction("drafts","readwrite").objectStore("drafts").delete(s);A.onerror=()=>c(A.error),A.onsuccess=()=>{O(),a()}})},[p]),W=e.useCallback(async s=>{const r=await q(s),a=await p();return new Promise((c,o)=>{const S=a.transaction("drafts","readwrite"),A=S.objectStore("drafts");S.onerror=()=>o(S.error),S.oncomplete=()=>{O(),c()};for(const m of r)A.delete(m.id)})},[p,q]),j=e.useCallback(async s=>{const r=await B(s);if(!r)throw new Error("Draft not found");const a=E.current[r.formId];if(!a)throw new Error(`No handler registered for form: ${r.formId}`);if(!v.isOnline){await K(s,"pending");return}await K(s,"syncing"),d(c=>({...c,isSyncing:!0}));try{await a(r.data,r),await K(s,"synced"),N==null||N(r),await F(s)}catch(c){const o=c instanceof Error?c.message:"Submission failed";await K(s,"failed",o),R==null||R(r,c instanceof Error?c:new Error(o))}finally{d(c=>({...c,isSyncing:!1}))}},[B,v.isOnline,K,F,N,R]),U=e.useCallback(async(s,r)=>{const a=await I(s,r);await K(a,"pending"),await j(a)},[I,K,j]),D=e.useCallback(async()=>{const s=await z(),r={synced:0,failed:0};d(a=>({...a,isSyncing:!0}));for(const a of s)if(!(a.status==="failed"&&a.attempts>=l.maxRetryAttempts))try{await j(a.id),r.synced++}catch{r.failed++}return d(a=>({...a,isSyncing:!1,lastSyncAt:new Date})),G==null||G(r),r},[z,j,l.maxRetryAttempts,G]),P=e.useCallback(async()=>{const r=(await z()).filter(a=>a.status==="failed");for(const a of r)a.attempts<l.maxRetryAttempts&&await K(a.id,"pending");await D()},[z,l.maxRetryAttempts,K,D]),T=e.useCallback((s,r)=>{E.current[s]=r},[]),O=e.useCallback(async()=>{try{const c=(await p()).transaction("drafts","readonly").objectStore("drafts").getAll();c.onsuccess=()=>{const o=c.result,S={};for(const w of o)S[w.formId]=(S[w.formId]||0)+1;const A=o.filter(w=>w.status==="pending").length,m=o.filter(w=>w.status==="failed").length;d(w=>({...w,draftCounts:S,pendingCount:A,failedCount:m}))}}catch{}},[p]);e.useEffect(()=>{const s=()=>{d(a=>({...a,isOnline:!0})),l.autoSubmitOnline&&D()},r=()=>{d(a=>({...a,isOnline:!1}))};return window.addEventListener("online",s),window.addEventListener("offline",r),()=>{window.removeEventListener("online",s),window.removeEventListener("offline",r)}},[l.autoSubmitOnline,D]),e.useEffect(()=>{p().then(()=>O())},[p,O]),e.useImperativeHandle(f,()=>({getState:()=>v,saveDraft:I,getDraft:B,getDrafts:q,getPendingDrafts:z,updateDraft:Y,deleteDraft:F,submitDraft:j,submitForm:U,syncPending:D,retryFailed:P,clearDrafts:W,registerHandler:T}),[v,I,B,q,z,Y,F,j,U,D,P,W,T]);const y={...v,saveDraft:I,getDraft:B,getDrafts:q,getPendingDrafts:z,updateDraft:Y,deleteDraft:F,submitDraft:j,submitForm:U,syncPending:D,retryFailed:P,clearDrafts:W,registerHandler:T};return t.jsx(ot.Provider,{value:y,children:i})}),{displayName:"NiceOfflineForms"}),dt=ut;process.env.NODE_ENV!=="production"&&(dt.displayName="NiceOfflineFormsProvider");function zn(n){const{formId:f,initialData:h={},autoSave:k=!0,autoSaveInterval:g=5e3,onSubmit:N}=n,R=lt(),[G,i]=e.useState(h),[l,b]=e.useState(),[E,v]=e.useState(!1),[d,p]=e.useState();e.useEffect(()=>{R.registerHandler(f,N)},[R,f,N]),e.useEffect(()=>{if(!k)return;const Y=setInterval(async()=>{if(Object.keys(G).length>0)if(l)await R.updateDraft(l,G);else{const K=await R.saveDraft(f,G);b(K)}},g);return()=>clearInterval(Y)},[k,g,G,l,f,R]);const I=e.useCallback(Y=>{const{name:K,value:F,type:W}=Y.target;i(j=>({...j,[K]:W==="checkbox"?Y.target.checked:F}))},[]),B=e.useCallback(async Y=>{Y==null||Y.preventDefault(),v(!0),p(void 0);try{await R.submitForm(f,G),i(h),b(void 0)}catch(K){p(K instanceof Error?K.message:"Submission failed")}finally{v(!1)}},[R,f,G,h]),q=e.useCallback(()=>{i(h),p(void 0),l&&(R.deleteDraft(l),b(void 0))},[h,l,R]),z=e.useCallback(async Y=>{const K=await R.getDraft(Y);K&&(i(K.data),b(Y))},[R]);return{data:G,setData:i,draftId:l,isSubmitting:E,error:d,isOnline:R.isOnline,isSyncing:R.isSyncing,pendingCount:R.pendingCount,handleChange:I,handleSubmit:B,reset:q,loadDraft:z}}const fe=()=>{const n=navigator;return n.connection?{type:n.connection.type,effectiveType:n.connection.effectiveType,downlink:n.connection.downlink,rtt:n.connection.rtt,saveData:n.connection.saveData}:{}},me=n=>{if(!n.effectiveType)return n.downlink?Math.min(100,n.downlink*10):50;switch(n.effectiveType){case"4g":return 100;case"3g":return 75;case"2g":return 50;case"slow-2g":return 25;default:return 50}},Gn=Object.assign(e.forwardRef((n,f)=>{const{mode:h="banner",position:k="top",showWhenOnline:g=!1,autoHideOnlineDelay:N=3e3,showSlowConnectionWarning:R=!0,slowConnectionThreshold:G=1,showReconnecting:i=!0,reconnectCheckInterval:l=5e3,offlineMessage:b="You're offline",onlineMessage:E="Back online",slowConnectionMessage:v="Slow connection",reconnectingMessage:d="Reconnecting...",showDetails:p=!1,animated:I=!0,pulseWhenOffline:B=!0,offlineIcon:q,onlineIcon:z,slowIcon:Y,renderContent:K,onStatusChange:F,onReconnect:W,className:j,style:U}=n,[D,P]=e.useState(()=>{const $=fe();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...$,quality:me($)}}),[T,O]=e.useState(!D.isOnline||g),[y,s]=e.useState(!1),[r,a]=e.useState(null),c=e.useCallback(()=>{const $=fe(),Z=navigator.onLine;P(J=>{const V={isOnline:Z,...$,quality:Z?me($):0,lastOnlineAt:Z?new Date:J.lastOnlineAt,offlineDuration:!Z&&r?Date.now()-r.getTime():void 0};return(J.isOnline!==V.isOnline||J.quality!==V.quality)&&(F==null||F(V)),V})},[r,F]),o=e.useCallback(async()=>{try{return(await fetch("/favicon.ico",{method:"HEAD",cache:"no-store"})).ok}catch{return!1}},[]);e.useEffect(()=>{const $=()=>{s(!1),a(null),c(),O(!0),W==null||W(),N>0&&setTimeout(()=>{O(g)},N)},Z=()=>{a(new Date),c(),O(!0),s(i)};window.addEventListener("online",$),window.addEventListener("offline",Z);const J=navigator;return J.connection&&J.connection.addEventListener("change",c),()=>{window.removeEventListener("online",$),window.removeEventListener("offline",Z),J.connection&&J.connection.removeEventListener("change",c)}},[c,N,g,i,W]),e.useEffect(()=>{if(!y||D.isOnline)return;const $=setInterval(async()=>{await o()&&window.dispatchEvent(new Event("online"))},l);return()=>clearInterval($)},[y,D.isOnline,l,o]),e.useEffect(()=>{if(D.isOnline||!r)return;const $=setInterval(()=>{P(Z=>({...Z,offlineDuration:Date.now()-r.getTime()}))},1e3);return()=>clearInterval($)},[D.isOnline,r]),e.useImperativeHandle(f,()=>({getConnectionInfo:()=>D,checkConnection:o,show:()=>O(!0),hide:()=>O(!1),toggle:()=>O($=>!$)}),[D,o]);const S=D.isOnline&&R&&D.downlink!==void 0&&D.downlink<G,m=D.isOnline?S?"slow":"online":y?"reconnecting":"offline",w=()=>{switch(m){case"offline":return b;case"reconnecting":return d;case"slow":return v;case"online":return E}},u=$=>({display:"inline-block",width:10,height:10,borderRadius:"50%",background:$}),C=()=>{switch(m){case"offline":case"reconnecting":return q||t.jsx("span",{style:u("var(--nice-color-error, #ef4444)")});case"slow":return Y||t.jsx("span",{style:u("var(--nice-color-warning, #f59e0b)")});case"online":return z||t.jsx("span",{style:u("var(--nice-color-success, #22c55e)")})}},x=$=>{const Z=Math.floor($/1e3);if(Z<60)return`${Z}s`;const J=Math.floor(Z/60);return J<60?`${J}m ${Z%60}s`:`${Math.floor(J/60)}h ${J%60}m`};if(!T||D.isOnline&&!g&&!S)return null;const H=["nice-offline-indicator",`nice-offline-indicator--${h}`,`nice-offline-indicator--${k}`,`nice-offline-indicator--${m}`,I&&"nice-offline-indicator--animated",B&&m==="offline"&&"nice-offline-indicator--pulse",j].filter(Boolean).join(" ");if(K)return t.jsx("div",{className:H,style:U,children:K(D)});const _=()=>t.jsx("span",{className:"nice-offline-indicator__icon",children:C()}),M=()=>t.jsx("span",{className:"nice-offline-indicator__message",children:w()}),L=()=>p?t.jsxs("div",{className:"nice-offline-indicator__details",children:[D.offlineDuration!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__duration",children:["Offline for ",x(D.offlineDuration)]}),D.effectiveType&&t.jsx("span",{className:"nice-offline-indicator__type",children:D.effectiveType.toUpperCase()}),D.downlink!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__speed",children:[D.downlink.toFixed(1)," Mbps"]}),D.rtt!==void 0&&t.jsxs("span",{className:"nice-offline-indicator__latency",children:[D.rtt,"ms"]})]}):null,X=()=>!p||!D.isOnline?null:t.jsx("div",{className:"nice-offline-indicator__quality",children:t.jsx("div",{className:"nice-offline-indicator__quality-bar",style:{width:`${D.quality}%`,backgroundColor:D.quality>=75?"var(--nice-color-success, #22c55e)":D.quality>=50?"var(--nice-color-warning, #eab308)":"var(--nice-color-error, #ef4444)"}})});switch(h){case"icon-only":return t.jsx("div",{className:H,style:U,title:w(),children:_()});case"minimal":return t.jsxs("div",{className:H,style:U,children:[_(),M()]});case"badge":return t.jsxs("div",{className:H,style:U,children:[t.jsx("div",{className:"nice-offline-indicator__badge-dot"}),t.jsx("span",{className:"nice-offline-indicator__badge-text",children:w()})]});case"toast":return t.jsx("div",{className:H,style:U,children:t.jsxs("div",{className:"nice-offline-indicator__toast",children:[_(),t.jsxs("div",{className:"nice-offline-indicator__toast-content",children:[M(),L()]})]})});case"detailed":return t.jsx("div",{className:H,style:U,children:t.jsxs("div",{className:"nice-offline-indicator__detailed",children:[_(),t.jsxs("div",{className:"nice-offline-indicator__detailed-content",children:[M(),L(),X()]})]})});case"banner":default:return t.jsx("div",{className:H,style:U,children:t.jsxs("div",{className:"nice-offline-indicator__banner",children:[_(),M(),p&&t.jsxs(t.Fragment,{children:[L(),y&&t.jsx("span",{className:"nice-offline-indicator__spinner"})]})]})})}}),{displayName:"NiceOfflineIndicator"});function Yn(){const[n,f]=e.useState(()=>{const h=fe();return{isOnline:typeof navigator<"u"?navigator.onLine:!0,...h,quality:me(h)}});return e.useEffect(()=>{const h=()=>{const g=fe();f(N=>({...N,isOnline:navigator.onLine,...g,quality:navigator.onLine?me(g):0,lastOnlineAt:navigator.onLine?new Date:N.lastOnlineAt}))};window.addEventListener("online",h),window.addEventListener("offline",h);const k=navigator;return k.connection&&k.connection.addEventListener("change",h),()=>{window.removeEventListener("online",h),window.removeEventListener("offline",h),k.connection&&k.connection.removeEventListener("change",h)}},[]),n}const ft=e.createContext(null),mt=()=>{const n=e.useContext(ft);if(!n)throw new Error("useOfflineMedia must be used within NiceOfflineMediaProvider");return n},Xn={dbName:"nice-offline-media",maxCacheSize:500*1024*1024,maxConcurrentDownloads:3,autoResumeOnReconnect:!0,defaultCacheDuration:10080*60*1e3,autoCleanup:!0,cleanupInterval:3600*1e3},Kn=()=>`media-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,Qn=(n,f)=>{var g;const h=((g=n.split(".").pop())==null?void 0:g.toLowerCase())||"",k=(f==null?void 0:f.toLowerCase())||"";return k.startsWith("image/")||["jpg","jpeg","png","gif","webp","svg"].includes(h)?"image":k.startsWith("video/")||["mp4","webm","ogg","mov","avi"].includes(h)?"video":k.startsWith("audio/")||["mp3","wav","ogg","flac","m4a"].includes(h)?"audio":["pdf","doc","docx","xls","xlsx","ppt","pptx"].includes(h)?"document":"other"},Jn=n=>{try{return new URL(n).pathname.split("/").pop()||"unknown"}catch{return n.split("/").pop()||"unknown"}},ht=Object.assign(e.forwardRef((n,f)=>{const{config:h,onDownloadStart:k,onDownloadProgress:g,onDownloadComplete:N,onDownloadFailed:R,onMediaRemoved:G,children:i}=n,l={...Xn,...h},b=e.useRef(null),E=e.useRef(new Map),v=e.useRef(new Map),[d,p]=e.useState({isOnline:typeof navigator<"u"?navigator.onLine:!0,activeDownloads:0,queuedDownloads:0,cachedCount:0,totalCacheSize:0,isDownloading:!1}),I=e.useCallback(async()=>b.current?b.current:new Promise((C,x)=>{const H=indexedDB.open(l.dbName,1);H.onerror=()=>x(H.error),H.onupgradeneeded=()=>{const _=H.result;if(!_.objectStoreNames.contains("media")){const M=_.createObjectStore("media",{keyPath:"id"});M.createIndex("url","url",{unique:!0}),M.createIndex("type","type",{unique:!1}),M.createIndex("status","status",{unique:!1})}_.objectStoreNames.contains("blobs")||_.createObjectStore("blobs",{keyPath:"id"})},H.onsuccess=()=>{b.current=H.result,C(H.result)}}),[l.dbName]),B=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const X=x.transaction("media","readwrite").objectStore("media").put(C);X.onerror=()=>_(X.error),X.onsuccess=()=>H()})},[I]),q=e.useCallback(async(C,x)=>{const H=await I();return new Promise((_,M)=>{const $=H.transaction("blobs","readwrite").objectStore("blobs").put({id:C,blob:x});$.onerror=()=>M($.error),$.onsuccess=()=>_()})},[I]),z=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const X=x.transaction("blobs","readonly").objectStore("blobs").get(C);X.onerror=()=>_(X.error),X.onsuccess=()=>{var $;return H(($=X.result)==null?void 0:$.blob)}})},[I]),Y=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const X=x.transaction("media","readonly").objectStore("media").get(C);X.onerror=()=>_(X.error),X.onsuccess=()=>{const $=X.result;$&&($.cachedAt=$.cachedAt?new Date($.cachedAt):void 0,$.expiresAt=$.expiresAt?new Date($.expiresAt):void 0),H($)}})},[I]),K=e.useCallback(async()=>{const C=await I();return new Promise((x,H)=>{const L=C.transaction("media","readonly").objectStore("media").getAll();L.onerror=()=>H(L.error),L.onsuccess=()=>{x(L.result.map(X=>({...X,cachedAt:X.cachedAt?new Date(X.cachedAt):void 0,expiresAt:X.expiresAt?new Date(X.expiresAt):void 0})))}})},[I]),F=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const $=x.transaction("media","readonly").objectStore("media").index("type").getAll(C);$.onerror=()=>_($.error),$.onsuccess=()=>H($.result)})},[I]),W=e.useCallback(async C=>(await K()).filter(H=>{var _;return(_=H.tags)==null?void 0:_.includes(C)}),[K]),j=e.useCallback(async C=>{const x=await I();return new Promise((H,_)=>{const $=x.transaction("media","readonly").objectStore("media").index("url").get(C);$.onerror=()=>_($.error),$.onsuccess=()=>H($.result)})},[I]),U=e.useCallback(async C=>{const x=await j(C);return(x==null?void 0:x.status)==="completed"},[j]),D=e.useCallback(async C=>{const x=v.current.get(C);if(x)return x;const H=await z(C);if(!H)return;const _=URL.createObjectURL(H);return v.current.set(C,_),_},[z]),P=e.useCallback(async(C,x)=>{var X;const H=await j(C);if((H==null?void 0:H.status)==="completed")return H.id;const _=new AbortController,M=(H==null?void 0:H.id)||Kn(),L={id:M,url:C,type:(x==null?void 0:x.type)||"other",name:(x==null?void 0:x.name)||Jn(C),mimeType:"",size:0,status:"queued",progress:0,downloadedBytes:0,metadata:x==null?void 0:x.metadata,tags:x==null?void 0:x.tags,priority:x==null?void 0:x.priority};E.current.set(M,_),await B(L),k==null||k(L),p($=>({...$,queuedDownloads:$.queuedDownloads+1,isDownloading:!0}));try{L.status="downloading",await B(L),p(se=>({...se,activeDownloads:se.activeDownloads+1,queuedDownloads:se.queuedDownloads-1}));const $=await fetch(C,{signal:_.signal,headers:x==null?void 0:x.headers});if(!$.ok)throw new Error(`HTTP ${$.status}`);const Z=$.headers.get("content-length"),J=$.headers.get("content-type")||"",V=Z?parseInt(Z,10):0;L.size=V,L.mimeType=J,L.type=(x==null?void 0:x.type)||Qn(C,J);const Q=(X=$.body)==null?void 0:X.getReader();if(!Q)throw new Error("No response body");const ee=[];let te=0;for(;;){const{done:se,value:re}=await Q.read();if(se)break;ee.push(re),te+=re.length,L.downloadedBytes=te,L.progress=V>0?Math.round(te/V*100):0,await B(L),g==null||g(L)}const ne=new Blob(ee,{type:J});return await q(M,ne),L.status="completed",L.progress=100,L.size=ne.size,L.cachedAt=new Date,L.expiresAt=x!=null&&x.cacheDuration?new Date(Date.now()+x.cacheDuration):new Date(Date.now()+l.defaultCacheDuration),await B(L),N==null||N(L),M}catch($){throw $.name==="AbortError"?L.status="cancelled":(L.status="failed",L.error=$ instanceof Error?$.message:"Download failed",R==null||R(L,$ instanceof Error?$:new Error(String($)))),await B(L),$}finally{E.current.delete(M),p($=>({...$,activeDownloads:Math.max(0,$.activeDownloads-1),isDownloading:$.activeDownloads>1})),await w()}},[j,B,q,l.defaultCacheDuration,k,g,N,R]),T=e.useCallback(async C=>{const x=[];for(let H=0;H<C.length;H+=l.maxConcurrentDownloads){const _=C.slice(H,H+l.maxConcurrentDownloads),M=await Promise.allSettled(_.map(L=>P(L.url,L.options)));for(const L of M)L.status==="fulfilled"&&x.push(L.value)}return x},[P,l.maxConcurrentDownloads]),O=e.useCallback(C=>{const x=E.current.get(C);x&&x.abort()},[]),y=e.useCallback(async C=>{const x=await Y(C);x&&(x.status==="paused"||x.status==="failed")&&await P(x.url,{type:x.type,name:x.name,metadata:x.metadata,tags:x.tags})},[Y,P]),s=e.useCallback(C=>{O(C)},[O]),r=e.useCallback(()=>{for(const[C]of E.current)O(C)},[O]),a=e.useCallback(async()=>{const x=(await K()).filter(H=>H.status==="paused"||H.status==="failed");await T(x.map(H=>({url:H.url})))},[K,T]),c=e.useCallback(async C=>{const x=await I(),H=v.current.get(C);H&&(URL.revokeObjectURL(H),v.current.delete(C)),await new Promise((_,M)=>{const L=x.transaction(["media","blobs"],"readwrite");L.objectStore("media").delete(C),L.objectStore("blobs").delete(C),L.onerror=()=>M(L.error),L.oncomplete=()=>_()}),G==null||G(C),await w()},[I,G]),o=e.useCallback(async()=>{const C=await I();for(const[,x]of v.current)URL.revokeObjectURL(x);v.current.clear(),await new Promise((x,H)=>{const _=C.transaction(["media","blobs"],"readwrite");_.objectStore("media").clear(),_.objectStore("blobs").clear(),_.onerror=()=>H(_.error),_.oncomplete=()=>x()}),await w()},[I]),S=e.useCallback(async()=>{const C=await K(),x=Date.now();let H=0;for(const _ of C)_.expiresAt&&_.expiresAt.getTime()<x&&(await c(_.id),H++);return H},[K,c]),A=e.useCallback(async()=>{const x=(await K()).filter(M=>M.status==="completed"),H={image:{count:0,size:0},video:{count:0,size:0},audio:{count:0,size:0},document:{count:0,size:0},other:{count:0,size:0}};let _=0;for(const M of x)_+=M.size,H[M.type].count++,H[M.type].size+=M.size;return{totalSize:_,itemCount:x.length,byType:H}},[K]),m=e.useCallback(async C=>{await T(C.map(x=>({url:x,options:{priority:-1}})))},[T]),w=e.useCallback(async()=>{const C=await A();p(x=>({...x,cachedCount:C.itemCount,totalCacheSize:C.totalSize}))},[A]);e.useEffect(()=>{const C=()=>{p(H=>({...H,isOnline:!0})),l.autoResumeOnReconnect&&a()},x=()=>{p(H=>({...H,isOnline:!1})),r()};return window.addEventListener("online",C),window.addEventListener("offline",x),()=>{window.removeEventListener("online",C),window.removeEventListener("offline",x)}},[l.autoResumeOnReconnect,a,r]),e.useEffect(()=>{if(!l.autoCleanup)return;const C=setInterval(()=>{S()},l.cleanupInterval);return()=>clearInterval(C)},[l.autoCleanup,l.cleanupInterval,S]),e.useEffect(()=>{I().then(()=>w());const C=v.current;return()=>{for(const[,x]of C)URL.revokeObjectURL(x)}},[I,w]),e.useImperativeHandle(f,()=>({getState:()=>d,download:P,downloadMultiple:T,getCachedMedia:Y,getAllCachedMedia:K,getMediaByType:F,getMediaByTag:W,getBlobUrl:D,isCached:U,pauseDownload:O,resumeDownload:y,cancelDownload:s,pauseAll:r,resumeAll:a,removeMedia:c,clearCache:o,clearExpired:S,getCacheStats:A,preload:m}),[d,P,T,Y,K,F,W,D,U,O,y,s,r,a,c,o,S,A,m]);const u={...d,download:P,downloadMultiple:T,getCachedMedia:Y,getAllCachedMedia:K,getMediaByType:F,getMediaByTag:W,getBlobUrl:D,isCached:U,pauseDownload:O,resumeDownload:y,cancelDownload:s,removeMedia:c,clearCache:o,preload:m};return t.jsx(ft.Provider,{value:u,children:i})}),{displayName:"NiceOfflineMedia"}),gt=ht;process.env.NODE_ENV!=="production"&&(gt.displayName="NiceOfflineMediaProvider");function Zn(n){const f=mt(),[h,k]=e.useState(),[g,N]=e.useState(),[R,G]=e.useState(!1);return e.useEffect(()=>{n&&(G(!0),Promise.all([f.getCachedMedia(n),f.getBlobUrl(n)]).then(([i,l])=>{k(i),N(l)}).finally(()=>{G(!1)}))},[n,f]),{item:h,blobUrl:g,isLoading:R,isOnline:f.isOnline}}const pt=e.createContext(null),es=()=>{const n=e.useContext(pt);if(!n)throw new Error("useServiceWorker must be used within NiceServiceWorkerProvider");return n},ts={swPath:"/service-worker.js",scope:"/",updateCheckInterval:6e4,autoUpdate:!1,skipWaiting:!1,reloadOnActivation:!0},bt=Object.assign(e.forwardRef((n,f)=>{const{config:h,showUpdateNotification:k=!0,showOfflineIndicator:g=!0,renderUpdateNotification:N,renderOfflineIndicator:R,notificationPosition:G="bottom",autoDismissDelay:i=0,onRegistered:l,onUpdateAvailable:b,onActivated:E,onError:v,onOnlineStatusChange:d,children:p,className:I}=n,B={...ts,...h},{swPath:q,scope:z,updateCheckInterval:Y,autoUpdate:K,reloadOnActivation:F}=B,W=B.skipWaiting,j=e.useMemo(()=>({swPath:q,scope:z,updateCheckInterval:Y,autoUpdate:K,skipWaiting:W,reloadOnActivation:F}),[q,z,Y,K,W,F]),U=e.useRef({onRegistered:l,onUpdateAvailable:b,onActivated:E,onError:v});e.useEffect(()=>{U.current={onRegistered:l,onUpdateAvailable:b,onActivated:E,onError:v}});const[D,P]=e.useState({status:"idle",updateAvailable:!1,waitingWorker:!1,cachedUrls:[],caches:[],isOnline:typeof navigator<"u"?navigator.onLine:!0}),[T,O]=e.useState(!1);e.useEffect(()=>{const _=()=>{P(L=>({...L,isOnline:!0})),d==null||d(!0)},M=()=>{P(L=>({...L,isOnline:!1})),d==null||d(!1)};return window.addEventListener("online",_),window.addEventListener("offline",M),()=>{window.removeEventListener("online",_),window.removeEventListener("offline",M)}},[d]);const y=e.useCallback(async()=>{if(!("caches"in window))return[];const _=await caches.keys(),M=[];for(const L of _){const X=await caches.open(L),$=await X.keys();let Z=0;for(const J of $){const V=await X.match(J);if(V){const Q=await V.clone().blob();Z+=Q.size}}M.push({name:L,size:Z,itemCount:$.length})}return P(L=>({...L,caches:M})),M},[]),s=e.useCallback(async _=>{if(!("caches"in window))return!1;const M=await caches.delete(_);return await y(),M},[y]),r=e.useCallback(async()=>{if(!("caches"in window))return;const _=await caches.keys();await Promise.all(_.map(M=>caches.delete(M))),P(M=>({...M,caches:[],cachedUrls:[]}))},[]),a=e.useCallback(async(_,M)=>{if(!("caches"in window))return;await(await caches.open(_)).addAll(M),await y()},[y]),c=e.useCallback(async(_,M)=>{if(!("caches"in window))return!1;const X=await(await caches.open(_)).delete(M);return await y(),X},[y]),o=e.useCallback(async _=>"caches"in window?(await(await caches.open(_)).keys()).map(X=>X.url):[],[]),S=e.useCallback(async()=>{var M,L,X,$,Z,J;if(!("serviceWorker"in navigator)){P(V=>({...V,status:"error",error:"Service Worker not supported"}));return}P(V=>({...V,status:"registering"}));const _=!!navigator.serviceWorker.controller;try{const V=await navigator.serviceWorker.register(j.swPath,{scope:j.scope});P(ee=>({...ee,status:"registered",registration:V})),(L=(M=U.current).onRegistered)==null||L.call(M,V),V.addEventListener("updatefound",()=>{const ee=V.installing;ee&&ee.addEventListener("statechange",()=>{var te,ne,se,re;switch(ee.state){case"installing":P(ae=>({...ae,status:"installing"}));break;case"installed":navigator.serviceWorker.controller?(P(ae=>({...ae,status:"installed",updateAvailable:!0,waitingWorker:!0})),O(!0),(ne=(te=U.current).onUpdateAvailable)==null||ne.call(te)):P(ae=>({...ae,status:"installed"}));break;case"activating":P(ae=>({...ae,status:"activating"}));break;case"activated":P(ae=>({...ae,status:"activated",updateAvailable:!1,waitingWorker:!1})),(re=(se=U.current).onActivated)==null||re.call(se),j.reloadOnActivation&&_&&window.location.reload();break;case"redundant":P(ae=>({...ae,status:"redundant"}));break}})}),V.waiting&&(P(ee=>({...ee,updateAvailable:!0,waitingWorker:!0})),O(!0),($=(X=U.current).onUpdateAvailable)==null||$.call(X));let Q=!1;return navigator.serviceWorker.addEventListener("controllerchange",()=>{!Q&&j.reloadOnActivation&&(Q=!0,window.location.reload())}),await y(),V}catch(V){const Q=V instanceof Error?V.message:"Registration failed";P(ee=>({...ee,status:"error",error:Q})),(J=(Z=U.current).onError)==null||J.call(Z,V instanceof Error?V:new Error(Q));return}},[j,y]),A=e.useCallback(async()=>{if(!D.registration)return!1;const _=await D.registration.unregister();return _&&P(M=>({...M,status:"idle",registration:void 0,updateAvailable:!1,waitingWorker:!1})),_},[D.registration]),m=e.useCallback(async()=>{D.registration&&await D.registration.update()},[D.registration]),w=e.useCallback(()=>{var _;(_=D.registration)!=null&&_.waiting&&D.registration.waiting.postMessage({type:"SKIP_WAITING"})},[D.registration]),u=e.useCallback(()=>{j.skipWaiting&&w(),O(!1)},[j.skipWaiting,w]),C=e.useCallback(()=>{window.location.reload()},[]);e.useEffect(()=>{S()},[S]),e.useEffect(()=>{if(!j.updateCheckInterval||j.updateCheckInterval<=0)return;const _=setInterval(()=>{m()},j.updateCheckInterval);return()=>clearInterval(_)},[j.updateCheckInterval,m]),e.useEffect(()=>{if(!T||i<=0)return;const _=setTimeout(()=>{O(!1)},i);return()=>clearTimeout(_)},[T,i]),e.useImperativeHandle(f,()=>({getState:()=>D,register:S,unregister:A,checkForUpdates:m,applyUpdate:u,skipWaiting:w,getCachesInfo:y,clearCache:s,clearAllCaches:r,addToCache:a,removeFromCache:c,getCachedUrls:o,forceReload:C}),[D,S,A,m,u,w,y,s,r,a,c,o,C]);const x={...D,register:S,unregister:A,checkForUpdates:m,applyUpdate:u,skipWaiting:w,getCachesInfo:y,clearCache:s,clearAllCaches:r,addToCache:a,removeFromCache:c,getCachedUrls:o},H=`nice-sw-notification--${G}`;return t.jsx(pt.Provider,{value:x,children:t.jsxs("div",{className:`nice-service-worker ${I||""}`,children:[p,k&&T&&D.updateAvailable&&t.jsx("div",{className:`nice-sw-notification ${H}`,children:N?N({onUpdate:u,onDismiss:()=>O(!1)}):t.jsxs("div",{className:"nice-sw-notification__content",children:[t.jsxs("div",{className:"nice-sw-notification__text",children:[t.jsx("strong",{children:"Update Available"}),t.jsx("span",{children:"A new version is ready to install"})]}),t.jsxs("div",{className:"nice-sw-notification__actions",children:[t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--primary",onClick:u,children:"Update Now"}),t.jsx("button",{className:"nice-sw-notification__btn nice-sw-notification__btn--secondary",onClick:()=>O(!1),children:"Later"})]})]})}),g&&!D.isOnline&&t.jsx("div",{className:`nice-sw-offline ${H}`,children:R?R({isOnline:D.isOnline}):t.jsx("div",{className:"nice-sw-offline__content",children:t.jsx("span",{children:"You are offline"})})})]})})}),{displayName:"NiceServiceWorker"}),ns=Object.assign(e.forwardRef((n,f)=>t.jsx(bt,{...n,ref:f})),{displayName:"NiceServiceWorkerProvider"});exports.NiceAutoStart=_e;exports.NiceAutoStartProvider=Ne;exports.NiceBackgroundSync=Xe;exports.NiceBackgroundSyncProvider=Ke;exports.NiceBarcodeScanner=cn;exports.NiceBatchScanner=hn;exports.NiceBatchScannerProvider=gn;exports.NiceCacheStrategies=Ze;exports.NiceCacheStrategiesProvider=et;exports.NiceConflictResolution=nt;exports.NiceConflictResolutionProvider=st;exports.NiceExternalDisplay=Ee;exports.NiceExternalDisplayProvider=De;exports.NiceHardwareBarcodeGenerator=Zt;exports.NiceHardwareQRGenerator=wn;exports.NiceIndexedDB=it;exports.NiceIndexedDBProvider=ct;exports.NiceKioskMode=Le;exports.NiceKioskModeProvider=Re;exports.NiceLowPowerMode=Te;exports.NiceLowPowerModeProvider=Me;exports.NiceOfflineForms=ut;exports.NiceOfflineFormsProvider=dt;exports.NiceOfflineIndicator=Gn;exports.NiceOfflineMedia=ht;exports.NiceOfflineMediaProvider=gt;exports.NiceOrientationLock=$e;exports.NiceOrientationLockProvider=qe;exports.NiceQRScanner=Nn;exports.NiceRemoteManagement=Ve;exports.NiceRemoteManagementProvider=He;exports.NiceScreenBurnPrevention=Bt;exports.NiceScreenSelector=Ae;exports.NiceServiceWorker=bt;exports.NiceServiceWorkerProvider=ns;exports.NiceSymbologyConfig=In;exports.NiceSymbologyProvider=En;exports.NiceTouchCalibration=Ut;exports.useAutoStart=vt;exports.useBackgroundSync=Dn;exports.useBatchScanner=ln;exports.useCacheStrategies=Je;exports.useCachedFetch=Tn;exports.useConflictResolution=Mn;exports.useConnectionStatus=Yn;exports.useExternalDisplay=Ie;exports.useIndexedDB=at;exports.useIndexedDBStore=Vn;exports.useKioskMode=jt;exports.useLowPowerMode=Et;exports.useOfflineForm=zn;exports.useOfflineForms=lt;exports.useOfflineMedia=mt;exports.useOfflineMediaItem=Zn;exports.useOrientationLock=Pt;exports.useRemoteManagement=Tt;exports.useServiceWorker=es;exports.useSymbology=jn;