(()=>{"use strict";window.destroyWebcam&&window.destroyWebcam();const e=e=>document.getElementById(e),t={stage:e("webcam-stage"),video:e("webcam-video"),canvas:e("webcam-canvas"),grid:e("webcam-grid"),status:e("webcam-status"),statusText:e("webcam-status-text"),cameraSelect:e("webcam-camera-select"),refreshButton:e("webcam-refresh-button"),enableButton:e("webcam-enable-button"),captureButton:e("webcam-capture-button"),switchButton:e("webcam-switch-button"),gridButton:e("webcam-grid-button"),mirrorButton:e("webcam-mirror-button"),timerButton:e("webcam-timer-button"),timerLabel:e("webcam-timer-label"),ratioButton:e("webcam-ratio-button"),ratioLabel:e("webcam-ratio-label"),settingsButton:e("webcam-settings-button"),settingsClose:e("webcam-settings-close"),settings:e("webcam-settings"),settingsZoom:e("webcam-settings-zoom"),filterStrip:e("webcam-filter-strip"),zoomStrip:e("webcam-zoom-strip"),galleryButton:e("webcam-gallery-button"),galleryPanel:e("webcam-gallery-panel"),galleryClose:e("webcam-gallery-close"),galleryBackdrop:e("webcam-gallery-backdrop"),gallery:e("webcam-gallery"),photoCount:e("webcam-photo-count"),downloadAll:e("webcam-download-all"),deleteAll:e("webcam-delete-all"),permission:e("webcam-permission"),permissionTitle:e("webcam-permission-title"),permissionMessage:e("webcam-permission-message"),countdown:e("webcam-countdown"),toast:e("webcam-toast"),flash:e("webcam-flash")};if(!t.stage||!t.video)return;const a="photos",o={none:"none",vivid:"saturate(1.28) contrast(1.09)",warm:"sepia(0.15) saturate(1.16) hue-rotate(-7deg)",cool:"saturate(1.08) hue-rotate(9deg) brightness(1.02)",mono:"grayscale(1) contrast(1.12)"},n=[{label:"4:3",key:"4:3",value:4/3},{label:"1:1",key:"1:1",value:1},{label:"16:9",key:"16:9",value:16/9},{label:"Full",key:"full",value:null}];let r=null,i=null,c=[],s="",l=!1,d=!1,u=0,m=0,h=1,g="none",b=!1,w=null,p=[],v=!1;function f(e,a=""){t.statusText.textContent=e,t.status.classList.remove("is-live","is-error"),a&&t.status.classList.add(a)}function y(e){clearTimeout(w),t.toast.textContent=e,t.toast.classList.add("is-visible"),w=setTimeout(()=>t.toast.classList.remove("is-visible"),2200)}function E(e,a,o="Enable camera"){t.permissionTitle.textContent=e,t.permissionMessage.textContent=a,t.enableButton.textContent=o,t.permission.classList.remove("is-hidden")}function B(e){switch(e?.name){case"NotAllowedError":case"PermissionDeniedError":return"Camera permission was denied. Allow it in your browser settings, then try again.";case"NotFoundError":case"DevicesNotFoundError":return"No camera was found on this device.";case"NotReadableError":case"TrackStartError":return"The camera is busy. Close other camera apps and try again.";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"The selected camera cannot provide the requested settings.";case"SecurityError":return"Camera access requires HTTPS or localhost.";default:return e?.message||"The camera could not be opened."}}function L(){i&&(i.getTracks().forEach(e=>e.stop()),i=null,t.video.srcObject=null,t.captureButton.disabled=!0)}async function S(e=s){const a=await navigator.mediaDevices.enumerateDevices();if(c=a.filter(e=>"videoinput"===e.kind),t.cameraSelect.innerHTML="",!c.length){const e=document.createElement("option");return e.value="",e.textContent="No cameras found",t.cameraSelect.appendChild(e),t.cameraSelect.disabled=!0,t.switchButton.disabled=!0,[]}c.forEach((e,a)=>{const o=document.createElement("option");o.value=e.deviceId,o.textContent=e.label||`Camera ${a+1}`,t.cameraSelect.appendChild(o)});const o=c.some(t=>t.deviceId===e);return s=o?e:c[0].deviceId,t.cameraSelect.value=s,t.cameraSelect.disabled=!1,t.switchButton.disabled=c.length<2,c}async function k(e=""){L(),f("Opening camera");const a=e?{deviceId:{exact:e},width:{ideal:2560},height:{ideal:1440}}:{facingMode:{ideal:"environment"},width:{ideal:2560},height:{ideal:1440}};try{i=await navigator.mediaDevices.getUserMedia({video:a,audio:!1}),t.video.srcObject=i,await t.video.play();const o=i.getVideoTracks()[0];s=o?.getSettings?.().deviceId||e||s,await S(s),t.permission.classList.add("is-hidden"),t.captureButton.disabled=!1,f(o?.label||"Camera ready","is-live")}catch(e){console.error(e);const t=B(e);throw f("Camera unavailable","is-error"),E("Open the lens.",t,"Try again"),e}}async function C(){t.enableButton.disabled=!0,t.refreshButton.disabled=!0,f("Requesting permission");try{if(!window.isSecureContext&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname)throw new Error("Camera access requires HTTPS or localhost.");await async function(){if(!navigator.mediaDevices?.getUserMedia)throw new Error("This browser does not support camera access.");const e=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:2560},height:{ideal:1440}},audio:!1}),t=e.getVideoTracks()[0];s=t?.getSettings?.().deviceId||"",e.getTracks().forEach(e=>e.stop())}();if(!(await S(s)).length)throw new Error("No camera was found on this device.");await k(t.cameraSelect.value)}catch(e){console.error(e),f("Permission required","is-error"),E("Frame the moment.",B(e),"Enable camera")}finally{t.enableButton.disabled=!1,t.refreshButton.disabled=!1}}function T(){t.stage.style.setProperty("--webcam-zoom",String(h)),t.stage.style.setProperty("--webcam-filter",o[g]||"none"),t.video.classList.toggle("is-mirrored",d),document.querySelectorAll("#webcam-zoom-strip [data-zoom], #webcam-settings-zoom [data-zoom]").forEach(e=>{e.classList.toggle("is-active",Number(e.dataset.zoom)===h)}),t.filterStrip.querySelectorAll("[data-filter]").forEach(e=>{e.classList.toggle("is-active",e.dataset.filter===g)})}function x(){l=!l,t.grid.classList.toggle("is-visible",l),t.gridButton.classList.toggle("is-active",l),t.gridButton.setAttribute("aria-pressed",String(l))}function A(){d=!d,t.mirrorButton.textContent=d?"Mirror on":"Mirror off",t.mirrorButton.setAttribute("aria-pressed",String(d)),T()}function D(e){t.settings.hidden=!e,t.settingsButton.setAttribute("aria-expanded",String(e)),t.settingsButton.classList.toggle("is-active",e)}function P(e,t="image/jpeg",a=.95){return new Promise((o,n)=>{e.toBlob(e=>{e?o(e):n(new Error("The photograph could not be created."))},t,a)})}async function $(){if(!b)if(!i||t.video.readyState{if(!e)return void a();let o=e;t.countdown.textContent=String(o),t.countdown.classList.add("is-visible");const n=setInterval(()=>{if(o-=1,o<=0)return clearInterval(n),t.countdown.textContent="",t.countdown.classList.remove("is-visible"),void a();t.countdown.textContent=String(o)},1e3)}));const a=t.video.videoWidth,r=t.video.videoHeight;if(!a||!r)throw new Error("The live frame could not be read.");const i=function(e,t){let a=e/h,o=t/h,r=(e-a)/2,i=(t-o)/2;const c=n[m].value;if(!c)return{x:r,y:i,width:a,height:o};if(a/o>c){const e=o*c;r+=(a-e)/2,a=e}else{const e=a/c;i+=(o-e)/2,o=e}return{x:r,y:i,width:a,height:o}}(a,r);t.canvas.width=Math.round(i.width),t.canvas.height=Math.round(i.height);const c=t.canvas.getContext("2d",{alpha:!1});c.save(),d&&(c.translate(t.canvas.width,0),c.scale(-1,1)),c.filter=o[g]||"none",c.drawImage(t.video,i.x,i.y,i.width,i.height,0,0,t.canvas.width,t.canvas.height),c.restore();const s=await P(t.canvas);await N({id:`${Date.now()}-${crypto.randomUUID?crypto.randomUUID():Math.random().toString(16).slice(2)}`,createdAt:Date.now(),width:t.canvas.width,height:t.canvas.height,ratio:n[m].label,filter:g,digitalZoom:h,enhanced:!1,blob:s}),t.flash.classList.remove("is-active"),t.flash.offsetWidth,t.flash.classList.add("is-active"),await q(),y("Photograph saved locally")}catch(e){console.error(e),y(e.message||"The photograph could not be saved")}finally{b=!1,t.captureButton.disabled=!i}var e}}function M(){return"indexedDB"in window?r||(r=new Promise((e,t)=>{const o=indexedDB.open("WebToolsCameraPhotos",1);o.onupgradeneeded=()=>{const e=o.result;if(!e.objectStoreNames.contains(a)){e.createObjectStore(a,{keyPath:"id"}).createIndex("createdAt","createdAt")}},o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error||new Error("Photo storage could not be opened.")),o.onblocked=()=>t(new Error("Photo storage is blocked by another tab."))}),r):Promise.reject(new Error("Local photo storage is unavailable."))}async function N(e){const t=await M();return new Promise((o,n)=>{const r=t.transaction(a,"readwrite");r.objectStore(a).put(e),r.oncomplete=o,r.onerror=()=>n(r.error||new Error("The photograph could not be stored."))})}async function U(){const e=await M();return new Promise((t,o)=>{const n=e.transaction(a,"readonly").objectStore(a).getAll();n.onsuccess=()=>t((n.result||[]).sort((e,t)=>t.createdAt-e.createdAt)),n.onerror=()=>o(n.error||new Error("Saved photographs could not be loaded."))})}async function j(e){if(e.enhanced&&e.originalBlob)return e.blob=e.originalBlob,e.originalBlob=null,e.enhanced=!1,await N(e),await q(),void y("Original photograph restored");const t=await(a=e.blob,new Promise((e,t)=>{const o=URL.createObjectURL(a),n=new Image;n.onload=()=>{URL.revokeObjectURL(o),e(n)},n.onerror=()=>{URL.revokeObjectURL(o),t(new Error("The photograph could not be processed."))},n.src=o}));var a;const o=document.createElement("canvas");o.width=t.naturalWidth,o.height=t.naturalHeight;const n=o.getContext("2d",{alpha:!1});n.filter="brightness(1.035) contrast(1.09) saturate(1.12)",n.drawImage(t,0,0);const r=await P(o,"image/jpeg",.96);e.originalBlob=e.blob,e.blob=r,e.enhanced=!0,await N(e),await q(),y("Photograph enhanced")}function I(){p.forEach(e=>URL.revokeObjectURL(e)),p=[]}function R(e,t=""){const a=new Date(e),o=e=>String(e).padStart(2,"0");return`web-cam_${a.getFullYear()}-${o(a.getMonth()+1)}-${o(a.getDate())}_${o(a.getHours())}-${o(a.getMinutes())}-${o(a.getSeconds())}${t}.jpg`}function O(e,t){const a=URL.createObjectURL(e),o=document.createElement("a");o.href=a,o.download=t,document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(a),1300)}function z(){const e=document.createElement("div");return e.className="webcam-empty-gallery",e.innerHTML="04Your archive is empty.

Use the shutter to create a photograph. Nothing leaves this browser.

",e}function H(e,t){const o=document.createElement("article");o.className="webcam-photo-card";const n=document.createElement("img");n.src=t,n.alt=`Photograph taken ${new Date(e.createdAt).toLocaleString()}`,n.loading="lazy";const r=document.createElement("div");r.className="webcam-photo-meta";const i=document.createElement("time");i.className="webcam-photo-time",i.dateTime=new Date(e.createdAt).toISOString(),i.textContent=`${new Date(e.createdAt).toLocaleString()} · ${e.ratio||"4:3"}${e.enhanced?" · Enhanced":""}`;const c=document.createElement("div");c.className="webcam-photo-actions";const s=document.createElement("button");s.type="button",s.className="webcam-photo-download",s.textContent="Download",s.addEventListener("click",()=>O(e.blob,R(e.createdAt)));const l=document.createElement("button");l.type="button",l.className="webcam-photo-enhance",l.textContent=e.enhanced?"Restore":"Enhance",l.addEventListener("click",async()=>{l.disabled=!0;try{await j(e)}catch(e){console.error(e),y("Enhancement failed"),l.disabled=!1}});const d=document.createElement("button");return d.type="button",d.className="webcam-photo-delete",d.textContent="×",d.setAttribute("aria-label","Delete photograph"),d.addEventListener("click",async()=>{await async function(e){const t=await M();return new Promise((o,n)=>{const r=t.transaction(a,"readwrite");r.objectStore(a).delete(e),r.oncomplete=o,r.onerror=()=>n(r.error||new Error("The photograph could not be deleted."))})}(e.id),await q(),y("Photograph deleted")}),c.append(s,l,d),r.append(i,c),o.append(n,r),o}function W(e,a){if(t.galleryButton.innerHTML="",!e||!a){const e=document.createElement("span");return e.className="webcam-empty-thumbnail",e.textContent="04",void t.galleryButton.appendChild(e)}const o=document.createElement("img");o.src=a,o.alt="Open saved photographs",t.galleryButton.appendChild(o)}async function q(){try{const e=await U();if(I(),t.gallery.innerHTML="",t.photoCount.textContent=`${e.length} saved`,t.downloadAll.disabled=0===e.length,t.deleteAll.disabled=0===e.length,!e.length)return t.gallery.appendChild(z()),void W(null,null);e.forEach((e,a)=>{const o=URL.createObjectURL(e.blob);p.push(o),t.gallery.appendChild(H(e,o)),0===a&&W(e,o)})}catch(e){console.error(e),t.gallery.innerHTML="",t.gallery.appendChild(z()),y("Local photo storage is unavailable")}}function F(e){window.matchMedia("(max-width: 760px)").matches&&(t.galleryPanel.classList.toggle("is-open",e),t.galleryBackdrop.classList.toggle("is-open",e),t.galleryBackdrop.setAttribute("aria-hidden",String(!e)))}const _=[];function V(e,t,a,o){e?.addEventListener(t,a,o),_.push(()=>e?.removeEventListener(t,a,o))}V(t.enableButton,"click",C),V(t.captureButton,"click",$),V(t.switchButton,"click",async function(){if(c.length<2)return void y("Only one camera is available");const e=Math.max(0,c.findIndex(e=>e.deviceId===s)),a=c[(e+1)%c.length];t.switchButton.disabled=!0;try{await k(a.deviceId)}finally{t.switchButton.disabled=c.length<2}}),V(t.gridButton,"click",x),V(t.mirrorButton,"click",A),V(t.timerButton,"click",function(){const e=[0,3,5,10];u=e[(e.indexOf(u)+1)%e.length],t.timerLabel.textContent=`${u}s`,t.timerButton.classList.toggle("is-active",u>0),t.timerButton.title=u?`Timer ${u} seconds`:"Timer off",y(u?`${u}-second timer`:"Timer disabled")}),V(t.ratioButton,"click",function(){m=(m+1)%n.length;const e=n[m];t.stage.dataset.ratio=e.key,t.ratioLabel.textContent=e.label,t.ratioButton.classList.toggle("is-active",0!==m),y(`Photo ratio ${e.label}`)}),V(t.settingsButton,"click",()=>D(t.settings.hidden)),V(t.settingsClose,"click",()=>D(!1)),V(t.galleryButton,"click",()=>F(!0)),V(t.galleryClose,"click",()=>F(!1)),V(t.galleryBackdrop,"click",()=>F(!1)),V(t.downloadAll,"click",async function(){const e=await U();for(let t=0;tsetTimeout(e,170));e.length&&y(`Downloading ${e.length} photographs`)}),V(t.deleteAll,"click",async function(){const e=await U();e.length&&window.confirm(`Delete all ${e.length} photographs from this browser?`)&&(await async function(){const e=await M();return new Promise((t,o)=>{const n=e.transaction(a,"readwrite");n.objectStore(a).clear(),n.oncomplete=t,n.onerror=()=>o(n.error||new Error("The archive could not be cleared."))})}(),await q(),y("Local archive cleared"))}),V(t.refreshButton,"click",async()=>{t.refreshButton.disabled=!0;try{const e=await S(s);!i&&e.length&&await k(t.cameraSelect.value),y(`${e.length} ${1===e.length?"camera":"cameras"} detected`)}catch(e){console.error(e),y(B(e))}finally{t.refreshButton.disabled=!1}}),V(t.cameraSelect,"change",async()=>{const e=t.cameraSelect.value;if(e&&e!==s){t.cameraSelect.disabled=!0;try{await k(e)}finally{t.cameraSelect.disabled=!1}}}),V(t.filterStrip,"click",e=>{const t=e.target.closest("[data-filter]");var a;t&&(a=t.dataset.filter,g=o[a]?a:"none",T(),y(`${"none"===g?"Natural":g} filter`))});const Z=e=>{const t=e.target.closest("[data-zoom]");var a;t&&(a=t.dataset.zoom,h=Math.max(1,Math.min(2,Number(a)||1)),T(),y(`Digital zoom ${h.toFixed(h%1?1:0)}×`))};V(t.zoomStrip,"click",Z),V(t.settingsZoom,"click",Z),V(document,"keydown",function(e){const a=document.activeElement;a?.matches("input, textarea, select")||a?.isContentEditable||("Space"===e.code?(e.preventDefault(),$()):"g"===e.key.toLowerCase()?x():"m"===e.key.toLowerCase()?A():"s"===e.key.toLowerCase()?D(t.settings.hidden):"Escape"===e.key&&(D(!1),F(!1)))});const Y=async()=>{try{await S(s)}catch(e){console.error(e)}};navigator.mediaDevices?.addEventListener?.("devicechange",Y),T(),q(),C(),window.destroyWebcam=()=>{v||(v=!0,clearTimeout(w),L(),I(),_.forEach(e=>e()),navigator.mediaDevices?.removeEventListener?.("devicechange",Y),delete window.destroyWebcam)}})();