<div id="natdiamviewer" width="512" height="512"></div>
<input id="blk" type="number" style="display:none" />

<script id="preview" mint="MINT_INSCRIPTION_ID">
// Retrieve render area
const root = document.getElementById('natdiamviewer')
root.parentElement.style.width = '100%'
root.parentElement.style.height = '100%'
root.parentElement.style.padding = '0px'
root.parentElement.style.margin = '0px'

const Wimg = 512
const Himg = 512
const maxLev = 232
let scaleW = 1
let scaleH = 1
let blockNumber = '707'

var howmanysym = 0
var vunpaired = []

var vColors = []
var vPalette = []
var vPaletteMaxSym = []

class sCol {    
    constructor(rr, gg, bb) {
        this.r = rr;
        this.g = gg;
        this.b = bb;
    }
}

// Resize window
window.addEventListener('resize', resize, true)
resize()

// Retrieve content inscription id
let mintText = document.getElementById('preview').getAttribute('mint')

// Check no mint provided
if(mintText.includes('MINT_INSCRIPTION_ID')) {
  let input = document.getElementById('blk')
  input.style.display = 'none'
  input.style.position = 'absolute'
  input.style.fontSize = '20px'
  input.style.margin = '20px'
  input.style.top = '0'
  input.value = blockNumber
  input.addEventListener('input',(event) => {
      blockNumber = input.value
      update()
  })
  update()
}
// Mint was provided
else {
  const request = new XMLHttpRequest()
  try {
    request.open('GET', '/content/' + mintText)
    request.responseType = 'text'
    request.addEventListener('load', () => initialize(request.response))
    request.addEventListener('error', () => console.error('XHR error'))
    request.send()
  } catch (error) {
    console.error(`XHR error ${request.status}`)
  }
}

function initialize(result) {   

    if(result) {
        console.log('Result', result)
        data = JSON.parse(result)
        blockNumber = data.blk
    }
    update()
}

function resize(event) {
  root.width = window.innerWidth
  root.height = window.innerHeight
  scaleW = root.width / Wimg
  scaleH = root.height / Himg
  offsetX = 0
  offsetY = 0
  if(scaleH < scaleW) {
    scaleW = scaleH
    offsetX = (root.width - Wimg * scaleW) / 2
  }
  else {
    scaleH = scaleW
    offsetY = (root.height - Himg * scaleH) / 2
  }
  root.style.zoom = scaleW / 2
  update('resize')
}

function update() {
  generateHtmlBasedOnBlockNumber(blockNumber)
}


//fixed elements
function generateHtmlBasedOnBlockNumber(blockNumber) {
    
    vPalette = []
    vPaletteMaxSym = []
    howmanysym =0
    vunpaired = []

    isEven = blockNumber%2 == 0

    const blkNumStr = blockNumber.toString()
    lenStrblk = blkNumStr.length

    calcSym(blkNumStr, lenStrblk)

    fillColors()
    createPalette(blockNumber)

    strbkgcol = "#212121"
    strokecol = "#999"

    cornacol = "#cb26e8"
    mod5 = blockNumber%10
    if(mod5==1){
      cornacol = "#cb26e8"
    }else if(mod5==2){
      cornacol = "#26e8cb"
    }else if(mod5==3){
      cornacol = "#e826cb"
    }else if(mod5==4){
      cornacol = "#cbe826"
    }else if(mod5==5){
      cornacol = "#777"
    }else if(mod5==6){
      cornacol = "#f60"
    }else if(mod5==7){
      cornacol = "#06f"
    }else if(mod5==8){
      cornacol = "#396"
    }else if(mod5==9){
      cornacol = "#e8cb26"
    }
   
    aurcol =  "#000"

    if(blkNumStr.includes("666")){
      cornacol = "#000"
    }else{
      const regex = new RegExp('6', "g");
      const count6 = (blkNumStr.match(regex) || []).length;
      cornacol = count6 == 3 ? "#dc143c" : cornacol
    }

    has777 = false
    if(blkNumStr.includes("777")){
      aurcol = "#9ed5ef"
      has777 = true
    }else{
      const regex = new RegExp('7', "g");
      const count7 = (blkNumStr.match(regex) || []).length;
      has777 = count7 == 3      
      aurcol = has777 ? "#007fff" : aurcol
    }

    has21 = blkNumStr.includes("21")

    fl2 = Math.floor(lenStrblk/2)
    ratioSym = lenStrblk==1 ? true : howmanysym/(fl2)    
    maxSym = howmanysym == Math.floor(fl2) || lenStrblk == 1

    zeroSym = howmanysym == 0

    numEvenDigits = zeroSym ? evenDigits(blockNumber) : 0 						

    vpal = vPalette
    if(zeroSym && numEvenDigits == 0){     
      vpal = []
    }
    if(maxSym){
      vpal = vPaletteMaxSym
    }
    natdiam = drawDiam(blockNumber, vpal,cornacol,aurcol,zeroSym,ratioSym,has777, has21)

    //construction
    const htmlContent = natdiam
    document.getElementById('natdiamviewer').innerHTML = htmlContent
}

function drawDiam(blk, vpalcol, cornacol, aurcol, isZeroSym, ratioSym, has777, has21){

    const sc = `,`
    const sp = ` `

    //fixed points
    var pl = {x: 6, y: 170}    
    const pc =  {x: 256, y: 170}  
    var pr =  {x: 506, y: 170} 
    const pb =  {x: 256, y: 482}  

    const p0 =  {x: 48, y: 110}
    const p1 = {x: 100, y: 82}  
    const p2 = {x: 132, y: 172} 
    const p3 = {x: 128, y: 170}  
    var p4 = {x: 180, y: 122}
    const p5 = {x: 168, y: 170}  
    var p6 = {x: 256, y: 97}
    const p7= {x: 332, y: 122} 
    
    const p8 = {x: 464, y: 110}
    const p9 = {x: 412, y: 82}
    const p10 = {x: 380, y: 172}
    const p11 = {x: 384, y: 170}  
    const p12 = {x: 332, y: 122}
    const p13 = {x: 344, y: 170}  

    var pT1 = {x: 236, y: 390}
    var pT2 = {x: 276, y: 390}

    const pA = {x: 70, y: 170}    
    const pB = {x: 442, y: 170}     
    const pC = {x: 196, y: 170}    
    const pD = {x: 316, y: 170}    

    var pCl = {x: 50, y: 40}
    var pCr = {x: 462, y: 40}
    

    lelps = 80 + howmanysym * 15
    helps = 12 - howmanysym * 2

    if(vunpaired.length >= 2){
      pT1.y = pT1.y - vunpaired[0] * 16
      pT2.y = pT2.y - vunpaired[1] * 16
    }
    if(vunpaired.length >= 4 ){
      p4.x = p4.x - 4 * 16+ vunpaired[2] * 16
      p6.x = p6.x - 4 * 16+ vunpaired[3] *16
    }
    if(vunpaired.length >= 6 ){
      pl.x = pl.x + 4 + vunpaired[4] * 4
      pr.x = pr.x  - vunpaired[5] * 4
    }

    // upper left
    var polL = `<polygon points="` + pl.x+sc+ pl.y+ sp  +p2.x+sc+p2.y +  sp + p0.x+sc+p0.y + `" fill="`+vpalcol[0]+`" stroke="`+strokecol+`" />`
    polL += `<polygon points="` + p0.x+sc+ p0.y+ sp  +p1.x+sc+p1.y +  sp + p4.x+sc+p4.y + sp +p3.x+sc+ p3.y +`" fill="`+vpalcol[1]+`" stroke="`+strokecol+`" />`
    polL += `<polygon points="` + p3.x+sc+ p3.y+ sp  +p4.x+sc+p4.y +  sp + p5.x+sc+p5.y + `" fill="`+vpalcol[2]+`" stroke="`+strokecol+`" />`
    polL += `<polygon points="` + p4.x+sc+ p4.y+ sp  +p5.x+sc+p5.y +  sp + pc.x+sc+pc.y + `" fill="`+vpalcol[3]+`" stroke="`+strokecol+`" />`
    polL += `<polygon points="` + p1.x+sc+ p1.y+ sp  +p4.x+sc+p4.y +  sp + p6.x+sc+p6.y + `" fill="`+vpalcol[4]+`" stroke="`+strokecol+`" />`

    // upper central
    strokec = "#777"
    if(isEven){
        polC = `<polygon class="dAnim1" points="` + p4.x+sc+ p4.y+ sp  +p6.x+sc+ p6.y +  sp+p7.x+sc+p7.y + sp +pc.x+sc+ pc.y +`" fill="#f60" stroke="`+strokec+`" />`
    }else{
        polC = `<polygon class="dAnim1" points="` + p4.x+sc+ p4.y+ sp  +p6.x+sc+ p6.y  + sp +pc.x+sc+ pc.y +`" fill="#666" stroke="`+strokec+`" />`
        polC += `<polygon class="dAnim1" points="` + p7.x+sc+ p7.y+ sp  +p6.x+sc+ p6.y  + sp +pc.x+sc+ pc.y +`" fill="#777" stroke="`+strokec+`" />`    
    }
    
    // upper right
    var polR = `<polygon points="` + pr.x+sc+ pr.y+ sp  +p10.x+sc+p10.y +  sp + p8.x+sc+p8.y + `" fill="`+vpalcol[0]+`" stroke="`+strokecol+`" />`
    polR += `<polygon points="` + p8.x+sc+ p8.y+ sp  +p10.x+sc+p10.y +  sp + p7.x+sc+p7.y + sp +p9.x+sc+ p9.y +`" fill="`+vpalcol[1]+`" stroke="`+strokecol+`" />`
    polR += `<polygon points="` + p13.x+sc+ p13.y+ sp  +p7.x+sc+p7.y +  sp + p10.x+sc+p10.y + `" fill="`+vpalcol[2]+`" stroke="`+strokecol+`" />`
    polR += `<polygon points="` + p13.x+sc+ p13.y+ sp  +p7.x+sc+p7.y +  sp + pc.x+sc+pc.y + `" fill="`+vpalcol[3]+`" stroke="`+strokecol+`" />`
    polR += `<polygon points="` + p9.x+sc+ p9.y+ sp  +p7.x+sc+p7.y +  sp + p6.x+sc+p6.y + `" fill="`+vpalcol[4]+`" stroke="`+strokecol+`" />`

    // lower 
    var polT = `<polygon points="` + pl.x+sc+ pl.y+ sp  +pr.x+sc+pr.y +  sp+pb.x+sc+pb.y + `" fill="`+vpalcol[0]+`" stroke="`+strokecol+`" />`
    var polt1 = `<polygon points="` + pA.x+sc+ pA.y+ sp  +p3.x+sc+p3.y +  sp+pT1.x+sc+pT1.y + `" fill="`+vpalcol[4]+`" stroke="`+strokecol+`" />`
    var polt2 = `<polygon points="` + p3.x+sc+ p3.y+ sp  +p5.x+sc+p5.y +  sp+pT1.x+sc+pT1.y + `" fill="`+vpalcol[7]+`" stroke="`+strokecol+`" />`
    var polt3 = `<polygon points="` + p5.x+sc+ p5.y+ sp  +pC.x+sc+pC.y +  sp+pT1.x+sc+pT1.y + `" fill="`+vpalcol[4]+`" stroke="`+strokecol+`" />`

    var polt4 = `<polygon points="` + pB.x+sc+ pB.y+ sp  +p11.x+sc+p11.y +  sp+pT2.x+sc+pT2.y + `" fill="`+vpalcol[4]+`" stroke="`+strokecol+`" />`
    var polt5 = `<polygon points="` + p11.x+sc+ p11.y+ sp  +p13.x+sc+p13.y +  sp+pT2.x+sc+pT2.y + `" fill="`+vpalcol[7]+`" stroke="`+strokecol+`" />`
    var polt6 = `<polygon points="` + p13.x+sc+ p13.y+ sp  +pD.x+sc+pD.y +  sp+pT2.x+sc+pT2.y + `" fill="`+vpalcol[4]+`" stroke="`+strokecol+`" />`

    puntacol = has21 ? "#f60" : "#000"
    var punta = `<polygon class="dAnim2"  points="226,440 256,480 286,440" fill="`+puntacol+`" stroke="`+puntacol+`" />`

    // horns    
    hstroke = strokecol
    if(cornacol == "#000"){
      hstroke = "#dc143c"
    }
    var polCl = `<polygon class="dAnim3" points="` + p0.x+sc+ p0.y+ sp  +p1.x+sc+p1.y +  sp+pCl.x+sc+pCl.y + `" fill="`+cornacol+`" stroke="`+hstroke+`" />`    
    var polCr = `<polygon class="dAnim3" points="` + p8.x+sc+ p8.y+ sp  +p9.x+sc+p9.y +  sp+pCr.x+sc+pCr.y + `" fill="`+cornacol+`" stroke="`+hstroke+`" />`
    
    // halo
    var aureola = `<ellipse rx="`+lelps+`" ry="`+helps+`" cx="256" cy="67" " fill="`+aurcol+`" stroke="#777"/>`
    aureola = has777 ?  aureola : ""

    var meter = `<rect x=60 y=23 width=392 height=2   fill="`+vpalcol[0]+`" stroke="#777"/>`
    var ticks = `<rect x=60 y=18 width=3 height=2   fill="`+aurcol+`" stroke="#777"/>`
    ticks += `<rect x=125 y=18 width=3 height=2   fill="`+aurcol+`" stroke="#777"/>`    
    ticks += `<rect x=190 y=18 width=3 height=2   fill="`+aurcol+`" stroke="#777"/>`
    ticks += `<rect x=255 y=18 width=3 height=2   fill="`+aurcol+`" stroke="#777"/>`
    ticks += `<rect x=320 y=18 width=3 height=2   fill="`+aurcol+`" stroke="#777"/>`
    ticks += `<rect x=385 y=18 width=3 height=2   fill="`+aurcol+`" stroke="#777"/>`
    ticks += `<rect x=448 y=18 width=3 height=2   fill="`+aurcol+`" stroke="#777"/>`

    posCursor = Math.floor(60 + 392 * ratioSym)   
    cursorcol = "rgb("+(128+blk%64)+","+(128+blk%128)+","+(256-blk%128)+")"
    var cursor = `<polygon points="`+(posCursor-6)+`,10 `+posCursor+`,18, `+(posCursor+6)+`,10"  fill="`+cursorcol+`" stroke="`+strokecol+`" />`
    
    atime1 = atime2 = atime3 = "5"
    if(ratioSym < 1){
      atime1 =  Math.floor(5 * ratioSym)   
      atime2 =  Math.floor(7 * ratioSym)   
      atime3 =  Math.floor(9 * ratioSym)   
    } 
    if(ratioSym == 0){
      atime1 = atime2 = atime3 = "0"  
    } 

    var natdiam = `<div style="position: absolute; top: 0px; left: 0px;">
            <svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect width="512" height="512" fill="`+strbkgcol+`"/>`                 
                +polL+polC+polR+polT+polt1+polt2+polt3+polt4+polt5+polt6+polCl+polCr+aureola+punta+meter+ticks+cursor+`
            </svg>
            <style>
              .dAnim1 {
                  animation-name: dOpacity;
                  animation-duration: `+ atime1  +`s;
                  animation-iteration-count: infinite;
              }
              .dAnim2 {
                  animation-name: dOpacity;
                  animation-duration: `+ atime2  +`s;
                  animation-iteration-count: infinite;
              }
              .dAnim3 {
                  animation-name: dOpacity;
                  animation-duration: `+ atime3  +`s;
                  animation-iteration-count: infinite;
              }
              @keyframes dOpacity {
                  0%   { opacity: 1; }
                  50%  { opacity: 0.1; }
                  100% { opacity: 1; }
              }
          </style>
        </div>`;

    return natdiam
}

function calcSym(blkNumStr, len){
         
    let len2 = Math.floor(len / 2)
	
     for (let i = 0; i < len2; i++) {

      let ch1 = blkNumStr.charAt(i)
      let ch2 = blkNumStr.charAt(len-1-i)
      i1 = parseInt(ch1)
      i2 = parseInt(ch2)

      if(ch1 == ch2){
        howmanysym++
      } else {     
        vunpaired.push(i1)       
        vunpaired.push(i2)
      }
    }
}

function fillColors(){
   
  for (let i = 0; i < maxLev; i+=16) {
    var col = new sCol(maxLev,maxLev-i,0);  
    vColors.push(col)
  }
  for (let i = 0; i < maxLev; i+=16) {
    var col = new sCol(maxLev-i,maxLev,0);  
    vColors.push(col)
  }
  for (let i = 0; i < maxLev; i+=16) {
    var col = new sCol(0,maxLev,i);  
    vColors.push(col)
  }
  for (let i = 0; i < maxLev; i+=16) {
    var col = new sCol(0,maxLev-i,maxLev);  
    vColors.push(col)
  }
  for (let i = 0; i < maxLev; i+=16) {
    var col = new sCol(i,0,maxLev);  
    vColors.push(col)
  }
}


function createPalette(blockNumber){

  const step = 8

  pos = blockNumber%vColors.length
  var cc = vColors[pos]
  dR = Math.floor((maxLev - cc.r)/step)
  dG = Math.floor((maxLev - cc.g)/step)
  dB = Math.floor((maxLev - cc.b)/step)
  for (let i = 0; i < step; i++) {
    //var col = new sCol(cc.r+i*dR,cc.g+i*dG,cc.b+i*dB);  
    strcol = "rgb("+(cc.r+i*dR)+","+(cc.g+i*dG)+","+(cc.b+i*dB)+")" 
    vPalette.push(strcol)
  }

  vr = [247,247,247,247,247,247,247,247]
  vg = [121,140,160,180,200,220,240,255]
  vb = [21,40,60,80,100,110,120,140,160]

  mod3 = blockNumber%3
  if(mod3==2){
    fillPaletteMax(vr,vg,vb)
  }else if(mod3==1){
    fillPaletteMax(vg,vb,vr)
  }else{
    fillPaletteMax(vb,vr,vg)
  }
}

function fillPaletteMax(vr, vg, vb){

    vPaletteMaxSym.push("rgb("+vr[0]+","+vg[0]+","+vb[0]+")")
    vPaletteMaxSym.push("rgb("+vr[1]+","+vg[1]+","+vb[1]+")")
    vPaletteMaxSym.push("rgb("+vr[2]+","+vg[2]+","+vb[2]+")")
    vPaletteMaxSym.push("rgb("+vr[3]+","+vg[3]+","+vb[3]+")")
    vPaletteMaxSym.push("rgb("+vr[4]+","+vg[4]+","+vb[4]+")")
    vPaletteMaxSym.push("rgb("+vr[5]+","+vg[5]+","+vb[5]+")")
    vPaletteMaxSym.push("rgb("+vr[6]+","+vg[6]+","+vb[6]+")")
    vPaletteMaxSym.push("rgb("+vr[7]+","+vg[7]+","+vb[7]+")")
}

function evenDigits(blk) {
  var cnt = 0;
  while (blk) {
    cnt += blk % 2 === 0;
    blk = Math.floor(blk / 10);
  }
  return cnt;
}

</script>