(function(u,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(u=typeof globalThis<"u"?globalThis:u||self,a(u.ByakurenJs={}))})(this,function(u){"use strict";class a{constructor(){this.color={red:0,green:0,blue:0},this.value=0,this.count=0}}class d{constructor(){this.redComponents=0,this.greenComponents=0,this.blueComponents=0,this.isLeaf=!1,this.pixelCount=0,this.children=new Array(8).fill(null)}}function C(r,t,e){return(r<<16)+(t<<8)+e}function p(r,t,e){return`#${((1<<24)+(r<<16)+(t<<8)+e).toString(16).slice(1)}`}function g(r,t){return r.count!==t.count?-(r.count-t.count):-(r.value-t.value)}class m{constructor(t,e){this.pixels=t,this.maxColors=e,this.leafCount=0,this.root=null,this.reducibleList=[]}build(){for(this.reducibleList=new Array(7).fill(null),this.root=this.buildOctree(this.pixels);this.leafCount>this.maxColors;)this.reduce(this.reducibleList)}extract(){if(!this.root)throw new Error("Octree not built yet");const t=Array.from({length:this.maxColors},()=>new a);return this.calculateColorStats(this.root,t),t.sort(g).filter(e=>e.count>0)}reduce(t){let e=6;for(;!t[e]&&e>=0;)e--;if(e<0)return;const n=t[e];if(!n)return;const o=n.node;t[e]=n.next;let i=0,c=0,s=0,h=0;for(let l=0;l<8;l++){const f=o.children[l];f&&(i+=f.redComponents,c+=f.greenComponents,s+=f.blueComponents,h+=f.pixelCount,this.leafCount--,o.children[l]=null)}o.isLeaf=!0,o.redComponents=i,o.greenComponents=c,o.blueComponents=s,o.pixelCount=h,this.leafCount++}buildOctree(t){const e=new d;e.isLeaf=!1;const n=t.length;for(let o=0;o>7-n&1,c=e.green>>7-n&1,s=e.blue>>7-n&1,h=(i<<2)+(c<<1)+s;let l=t.children[h];l||(l=new d,t.children[h]=l,n===7?(l.isLeaf=!0,this.leafCount++):o[n]={node:l,next:o[n]}),this.addColor(l,e,n+1,o)}}calculateColorStats(t,e){if(t.isLeaf){const o=Math.floor(t.redComponents/t.pixelCount),i=Math.floor(t.greenComponents/t.pixelCount),c=Math.floor(t.blueComponents/t.pixelCount);return e[0].count=t.pixelCount,e[0].color.red=o,e[0].color.green=i,e[0].color.blue=c,e[0].value=C(o,i,c),1}let n=0;for(let o=0;o<8;o++){const i=t.children[o];i!==null&&(n+=this.calculateColorStats(i,e.slice(n)))}return n}}async function b(r,t){const{data:e}=await x(r),n=[],o=e.length;for(let s=0;ss.color)}async function x(r){if(r instanceof ImageData)return r;const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Canvas 2D context is not supported");const n=await createImageBitmap(r);return t.width=n.width,t.height=n.height,e.drawImage(n,0,0),e.getImageData(0,0,n.width,n.height)}u.bkrRgbToHex=p,u.extractColorPalette=b,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});