<template>
  <div class="h-100">
    <v-row
      class="h-100"
      no-gutters
    >
      <v-col>
        <div class="wrapper">
          <Viewer3crWebGL
            ref="webgl"
            class="webgl"
            :class="[mobile && 'mobile-view']"
            @loaded="onLoaded"
          />
          <template v-if="isReady">
            <WebGLClipPath
              :anchors="anchors"
              :canvas="webgl!.canvas!"
            />
            <template
              v-for="layout in scanState.Layout.PositionData"
              :key="layout.DefaultView"
            >
              <ViewerScanView
                :canvas="webgl!.canvas!"
                :position="layout"
              />
            </template>
          </template>
          <McadFloating v-if="activeDrawer === 'design'" />
        </div>
      </v-col>
    </v-row>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { scanState } from '@/models/scanState';
import Viewer3crWebGL from '@/components/modal/Viewer3crWebGL.vue';
import McadFloating from '@/components/navigation/mcad/McadFloating.vue';
import { storeToRefs } from 'pinia';
import { useDrawerStore } from '@/stores/drawer.store';
import { useDisplay } from 'vuetify';

type Emits = {
  loaded: [void];
};

const emit = defineEmits<Emits>();
const { activeDrawer } = storeToRefs(useDrawerStore());
const { mobile } = useDisplay();

const loaded = ref<boolean>(false);
const webgl = ref<InstanceType<typeof Viewer3crWebGL>>();

const anchors = computed(() => {
  return scanState.value.Layout.PositionData.map((p) => p.Anchor);
});

const isReady = computed(() => {
  return loaded.value && !!webgl.value?.canvas;
});

function onLoaded(): void {
  loaded.value = true;
  emit('loaded');
}
</script>

<style scoped lang="scss">
.webgl {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
}

.webgl:not(.mobile-view) {
  clip-path: url(#webgl);
}

.wrapper {
  background-color: rgb(var(--v-theme-surface));
  position: relative;
  width: 100%;
  height: 100%;
}
</style>
