<script setup>
  import ReloadIcon from '../assets/icons/reload.svg'
</script>

<template>
    <div id="generatedContainer" ref="generatorContainer">
    <div class="loadingOverlay" v-show="false"><p id="loadingOText">ça charge...</p></div>
      <div class="imgContainer" :id="'div'+item.id" :class="{highlightItem: item.isHighlight===1, highlightMax: item.isHighlight===2}" v-for="item in randomImgList" :key="item.id" :style="{
                                                                                                  left: item.x + 'px',
                                                                                                  top: item.y + 'px'
                                                                                                }">
            <img loading="lazy" :src="item.src" class="imgStyle" :class="{highlightItem: item.isHighlight===1, highlightMax: item.isHighlight===2}" :id="'image'+item.id">

      </div>
    </div>
    <PlayerDiv></PlayerDiv>
    <ColorPan ref="colorBtn"></ColorPan>
    <button type="button" name="reload" data-tooltip="recharger" id="reloadBtnStyle" class="iconBtnStyle" @click="startContentReload">
      <ReloadIcon name="close" class="icon"/>
    </button>
</template>

<style scoped>
  /*================= Mise en page:
    => Mobile First : par défaut, moins de 500px
    => Tablette et PC format haut : de 500 à 1000px
    => PC large : à partir de 1000px
  */

  /*+++++++++++++++++ COPYBOX
      ================ PC HAUT/IPAD
      @media(min-width:500px){}
      ================ PC LARGE
      @media(min-width:1000px){}
  */

  #generatedContainer{
    background-color: transparent;
    width:100%;
    height:70%;
    position:relative;
  }

  #reloadBtnStyle{
    position: absolute;
    z-index:0;
    width: 44px;
    height: 44px;
    border-radius: 22px;
    top: 47%;
    left: 7.77px;
    animation: float 1.61s infinite;
  }

  #reloadBtnStyle{
    animation: none;
  }

  .loadingOverlay{
    position: absolute;
    margin-top: 4.5%;
    width: 97%;
    height: 91%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    z-index: 0;
    border-radius: 0 16.1px 16.1px 0;
    pointer-events: none;
    animation: blinkBack 3.33s ease-in-out infinite;
    opacity: 0.333;
  }

  #loadingOText{
    position:relative;
    z-index: 334;
    font-family: 'lineal';
    font-size: 33.3px;
    color: var(--light-color);
    opacity: 1;
  }

  /*====================Gestion des images*/
  .imgContainer{
    width:161px;
    height:161px;
    position:absolute;
    z-index:0;
    align-items:center;
    display:flex;
    background-color:transparent;
  }

  .imgStyle{
    position: absolute;
    width:100px;
    height:auto;
    z-index:-1;
    border-style: solid;
    border-width: thin;
    border-color: var(--light-color);
  }
  .imgStyle.highlightItem{
    border-color: transparent;
    width:131.2px;
    height:auto;
    z-index:-1;
  }
  .imgStyle.highlightMax{
    border-color: transparent;
    width:250px;
    height:auto;
    z-index:-1;
  }

  /*================ PC LARGE*/
  @media(min-width:1300px){
    #generatedContainer{
      height: 67%;
    }

    #reloadBtnStyle{
      top: 49%;
      left: 44.4px;
      width: 77px;
      height: 77px;
      border-radius: 50%;
    }

    #reloadBtnStyle .icon{
      height: 33px;
      width: auto;
    }

    .imgStyle{
      width:150px;
    }
    .imgStyle.highlightItem{
      width:200px;
    }
    .imgStyle.highlightMax{
      width:333px;
    }

  }
</style>

<script>
  import { toRaw } from 'vue'

  const imgImport = import.meta.glob('../assets/TEST/*.png',{eager:true,import:'default'});
  const imgCollection = Object.values(imgImport);

  export default {
    name : 'GeneratedContent',
    data(){
      return{
        containerWidth:0,
        containerHeight:0,
        imgList: imgCollection.map((src,index)=>({
          id: "img-" + index,
          src: src,
          x: 0,
          y: 0,
          isHighlight: 0
        })),
        randomImgList: null,
        marjTop:77,
        marjBot:161,
        marjSide:200,
        overlayIsActive: false
      }
    },
    methods:{
      delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
      },
      getRandomInt(min,max){
        min=Math.ceil(min)
        max=Math.floor(max)
        return Math.floor(Math.random()*(max-min+1))+min
      },
      selectHighlight(){
        const imgCount = this.randomImgList.length-1;
        let a = this.getRandomInt(0,imgCount);
        let b = 0;
        let c = 0;
        do{
          b = this.getRandomInt(0,imgCount);
        } while (a == b);

        do{
          c = this.getRandomInt(0,imgCount);
        } while (a == c || c == b);
        //console.log(a,b,c);
        this.randomImgList[a].isHighlight = 1;
        this.randomImgList[b].isHighlight = 1;
        this.randomImgList[c].isHighlight = 2;
      },
      genCoord(chain){
        const maxX = this.containerWidth;
        const maxY = this.containerHeight;
        // position initiale aléatoire
        let x = this.getRandomInt(0, maxX-this.marjSide);
        let y = this.getRandomInt(0, this.marjSide);
        // vecteur direction initial aléatoire mais biais vers le bas
        let dirX = (Math.random() - 0.5) * 5;
        let dirY = Math.random() * 2 + 0.7;
        for (let i = 0; i < chain.length; i++){
          // assigner position calc tour prev
          chain[i].x = x;
          chain[i].y = y;
          //calc nouvelle position
            // distance contrôlée
          const distance = this.getRandomInt(161, 333);
          // perturbation continue
          dirX += (Math.random() - 0.5) * 1.2;
          dirY += (Math.random() - 0.5) * 0.5;
            // perturbation brutale occasionnelle
          if (Math.random() < 0.5){
            dirX += (Math.random() - 0.5) * 3;
            dirY += (Math.random() - 0.5) * 1;
          }
            // biais vers le bas
          dirY += .2;
            // normaliser
          const length = Math.sqrt(dirX*dirX + dirY*dirY);
          dirX /= length;
          dirY /= length;
            // déplacement
          x += dirX * distance;
          y += dirY * distance;
            // rebond horizontal
          if (x <= 0){
            x = 0;
            dirX *= -1;
          }
          if (x >= maxX-this.marjSide){
            x = maxX-this.marjSide;
            dirX *= -1;
          }
            //limite en bas
          if (y>=maxY-this.marjBot){
            y = maxY-this.marjBot;
            dirY *= -1;
          }
            //limite haut
          if (y<=this.marjTop){
            y = this.marjTop;
            dirY *= -1;
          }
        }
      },
      generateContent(){
        this.randomImgList = structuredClone(toRaw(this.imgList)).sort(() => Math.random()-0.5);
        this.selectHighlight();
        this.genCoord(this.randomImgList);
        //console.log('Layout has been generated!');
      },
      async reloadAnimation(){
        this.overlayIsActive = true;
        for (let i = 0; i < 3; i++) {
          this.generateContent();
          await this.delay(333);
          if(i===2){
            this.overlayIsActive = false;
          };
        }
      },
      startContentReload(){
        this.reloadAnimation();
      }
    },
    mounted(){
      const displayContainer = this.$refs.generatorContainer;
      if(!displayContainer){
        console.error("container not found");
        return
      };

      const observer = new ResizeObserver(entries=>{
        const rect = entries[0].contentRect;
        this.containerWidth = rect.width;
        this.containerHeight = rect.height;
        //console.log(rect.width, rect.height);
        this.generateContent();
      });
      observer.observe(displayContainer);
      console.log("Generated content is loaded!");
    }
  };
</script>
