<script setup>



const user = useSupabaseUser()
//console.log(user.value)
const router = useRouter()
const route = useRoute()
const colorMode = useColorMode()
const supabase = useSupabaseClient()
const tenants = (await supabase.from("tenants").select()).data
const {loaded, profiles} = storeToRefs(useDataStore())
const {fetchData, getProfileById} = useDataStore()
const userProfile = (user.value ? getProfileById(user.value.id) : {})
//console.log(userProfile)

const viewport = useViewport()

watch(viewport.breakpoint, (newBreakpoint, oldBreakpoint) => {
  console.log('Breakpoint updated:', oldBreakpoint, '->', newBreakpoint)
})


fetchData()

const navLinks = [
  {
    label: "Home",
    to: "/",
    icon: 'i-heroicons-home'
  },
  {
    label: "Kontakte",
    icon: 'i-heroicons-user-group',
    children: [
      {
        label: "Kunden",
        to: "/customers",
        icon: "i-heroicons-user-group"
      },
      {
        label: "Lieferanten",
        to: "/vendors",
        icon: "i-heroicons-truck"
      },
    ]
  },
  {
    label: "Buchhaltung",
    icon: 'i-heroicons-document-chart-bar',
    children: [
      {
        label: "Eingangsrechnungen",
        to: "/vendorinvoices",
        icon: "i-heroicons-user-group"
      },
    ]
  },
  {
    label: "Aufträge",
    icon: "i-heroicons-square-3-stack-3d",
    children: [
      {
        label: "Projekte",
        to: "/projects",
        icon: "i-heroicons-clipboard-document-check"
      },
      {
        label: "Jobs",
        to: "/jobs",
        icon: "i-heroicons-square-3-stack-3d"
      },
      {
        label: "Verträge",
        to: "/contracts",
        icon: "i-heroicons-clipboard-document"
      },
    ]
  },
  {
    label: "Planung",
    icon: "i-heroicons-square-3-stack-3d",
    children: [
      {
        label: "Aufgaben",
        to: "/tasks",
        icon: "i-heroicons-rectangle-stack"
      },
      {
        label: "Plantafel",
        to: "/planningBoard",
        icon: "i-heroicons-calendar-days"
      },
    ]
  },
  {
    label: "Dokumente",
    to: "/documents",
    icon: "i-heroicons-document"
  },
  {
    label: "Mitarbeiter",
    icon: 'i-heroicons-user',
    children: [
      {
        label: "Zeiterfassung",
        to: "/timetracking",
        icon: "i-heroicons-clock"
      },
    ]
  },
  {
    label: "Lager",
    icon: 'i-heroicons-home',
    children: [
      {
        label: "Artikel",
        to: "/products",
        icon: "i-heroicons-puzzle-piece"
      },
      {
        label: "Inventar",
        to: "/inventory",
        icon: "i-heroicons-square-3-stack-3d"
      },
      {
        label: "Lagerplätze",
        to: "/inventory/spaces",
        icon: "i-heroicons-square-3-stack-3d"
      },
    ]
  },
]

const linksForBreadcrumbs = ref([])

const generateLinks = () => {
  let pathSteps = route.fullPath.split("/")
  let returnArr = []

  pathSteps.forEach((step,index) => {

    let stepLink = navLinks.find(link => link.link == step)

    if(stepLink) {
      returnArr[index] = {
        label: stepLink.label,
        icon: stepLink.icon,
        to:  '/' + stepLink.link
      }
    }

    linksForBreadcrumbs.value = returnArr

  })



}

watch(
    () => route.path,
    () => {
      generateLinks()
    }
)
generateLinks()




const userTenant = ref({})
if(user) userTenant.value = tenants.find(tenant => tenant.id === user.value.app_metadata.tenant)



useHead({
  meta: [
    { name: 'viewport', content: 'width=device-width, initial-scale=1' }
  ],
  link: [
    { rel: 'icon', href: '/favicon.ico' }
  ],
  htmlAttrs: {
    lang: 'de'
  }
})

useSeoMeta({
  ogSiteName: 'spaces.software',
  twitterCard: 'summary_large_image'
})

const items = [
  [{
    label: user.value ? user.value.email : "",
    slot: 'account',
    disabled: true
  }], [{
    label: 'Externe Geräte',
    icon: 'i-heroicons-cog-8-tooth',
    to: "/settings/externalDevices"
  },{
    label: 'Settings',
    icon: 'i-heroicons-cog-8-tooth'
  }], /*[{
    label: 'Documentation',
    icon: 'i-heroicons-book-open'
  }, {
    label: 'Changelog',
    icon: 'i-heroicons-megaphone'
  }, {
    label: 'Status',
    icon: 'i-heroicons-signal'
  }],*/ [{
    label: 'Sign out',
    icon: 'i-heroicons-arrow-left-on-rectangle',
    click: () => {
      supabase.auth.signOut()
      router.push("/login")
    }
  }]
]

</script>

<template>
  <UHeader :links="navLinks">
    <template #logo>
      <div id="logo">
        <img
            v-if="colorMode.value === 'light'"
            alt="Logo Hell"
            src="/spaces_hell.svg"
        />
        <img
            v-else
            src="/spaces.svg"
            alt="Logo Dunkel"
        />
      </div>

    </template>

    <template #panel>
      <UNavigationTree :links="navLinks"/>
    </template>

    <template #right  v-if="user">
      <UColorModeButton/>
      <UDropdown :items="items" :ui="{ item: { disabled: 'cursor-text select-text' } }" :popper="{ placement: 'bottom-start' }">
        <UAvatar
            :alt="userProfile ? userProfile.firstName + ' ' + userProfile.lastName : '' "
        />

        <template #account="{ item }">
          <div class="text-left">
            <p>
              Signed in as
            </p>
            <p class="truncate font-medium text-gray-900 dark:text-white">
              {{ item.label }}
            </p>
          </div>
        </template>

        <template #item="{ item }">
          <span class="truncate">{{ item.label }}</span>

          <UIcon :name="item.icon" class="flex-shrink-0 h-4 w-4 text-gray-400 dark:text-gray-500 ms-auto" />
        </template>
      </UDropdown>
    </template>
  </UHeader>
  <UDivider />
  <div class="m-3" id="contentContainer">
    <NuxtPage
        v-if="loaded"
    />
    <div
        v-else
    >
      <UProgress animation="carousel" />
    </div>
  </div>
<!--  <UFooter>
    <template #left>
      <p class="text-gray-500 dark:text-gray-400 text-sm">
        Copyright © 2023-{{ new Date().getFullYear() }} <NuxtLink class="hover:underline" to="https://federspiel.tech" target="_blank">
        Federspiel Technolog UG haftungsbeschränkt
      </NuxtLink>
      </p>
    </template>

    <template #right>

    </template>
  </UFooter>-->


  <UNotifications/>
  <VitePwaManifest/>


<!--    <UCard id="page">
      <template #header>
        <div id="menu">
          <router-link
              v-for="link in navLinks"
              :to="link.to"
              class="mr-2"
          >
            <UButton>{{link.label}}</UButton>
          </router-link>
          &lt;!&ndash;<router-link to="/customers" class="mr-2"><UButton>Kunden</UButton></router-link>
          <router-link to="/projects" class="mr-2"><UButton>Projekte</UButton></router-link>
  -
          <router-link to="/vendorinvoices" class="mr-2"><UButton>Eingangsrechnungen</UButton></router-link>

          <router-link to="/timetracking" class="mr-2"><UButton>Zeiterfassung</UButton></router-link>
          <router-link to="/products" class="mr-2"><UButton>Artikel</UButton></router-link>
          <router-link to="/documents" class="mr-2"><UButton>Dokumente</UButton></router-link>
          <router-link to="/inventory" class="mr-2"><UButton>Inventar</UButton></router-link>&ndash;&gt;
          <UDropdown :items="userDropdownItems" :popper="{placement: 'bottom-start'}">
            <UButton color="white" label="Benutzer" trailing-icon="i-heroicons-chevron-down-20-solid" />
          </UDropdown>
        </div>
        <UBreadcrumb
            class="my-3"
            :links="linksForBreadcrumbs"
        />
      </template>
      <NuxtPage
          v-if="loaded"
      />
      <div
          v-else
      >
        <UProgress animation="carousel" />
      </div>
    </UCard>-->



</template>

<style>

#logo img{
  height: 15vh;
  width: auto;
}

#contentContainer {
  width: 95vw;
  height: 85vh;
}

.documentList {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  height: 85vh;
  overflow-y: scroll;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

.documentList::-webkit-scrollbar {
  display: none;
}

.scrollList {
  overflow-y: scroll;
  height: 85vh;
  margin-top: 1em;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

.scrollList::-webkit-scrollbar {
  display: none;
}


  #page {
    width: 98vw;
    height: 95vh;
    margin:1em;
  }

  .listItem {
    padding: .1em;
    border: 1px solid grey;
    border-radius: 15px;
    margin-top: 1em;
  }
  .listItem:hover {
    border: 1px solid #69c350;
  }

</style>