<template>
  <v-app>
    <v-app-bar v-if="appBarVisible" app color="primary" dark>
      <v-container fluid>
        <v-row align-items="center" justify="space-between">
          <v-col cols="auto">
            <v-btn link to="/">
              <v-img
                v-if="logoSrc"
                alt="Logo"
                class="v-img__img v-img__img--contain"
                :min-height="100"
                :src="logoSrc"
              />
            </v-btn>
          </v-col>

          <v-col cols="auto">
            <v-spacer v-if="showSpacer" />
            <v-btn v-if="showThemeSwitch" icon @click="toggleTheme">
              <v-icon>{{ themeIcon }}</v-icon>
            </v-btn>

            <v-menu v-if="showLanguageSwitch" offset-y>
              <template #activator="{ on, attrs }">
                <v-btn v-bind="attrs" @click="openLanguageMenu"> <!-- Explicit click handler -->
                  <v-img max-height="20" max-width="20" :src="selectedLanguageFlag" />
                </v-btn>
              </template>
              <v-list>
                <v-list-item
                  v-for="option in languageOptions"
                  :key="option.value"
                  @click="changeLanguage(option.value)"
                >
                  <v-img max-height="20" max-width="20" :src="getFlagSrc(option.flag)" />
                  <v-list-item-title>{{ option.text }}</v-list-item-title>
                </v-list-item>
              </v-list>
            </v-menu>

            <v-menu v-if="showMegaMenu" :close-on-content-click="false" offset-y>
              <template #activator="{ on, attrs }">
                <v-btn v-bind="attrs" @click="openMegaMenu"> <!-- Explicit click handler -->
                  Home
                </v-btn>
              </template>
              <v-list>
                <v-list-group v-for="(links, key) in megaMenu" :key="key" :value="false">
                  <template #activator="{ on, attrs }">
                    <v-list-item v-bind="attrs" @click="openListgroup(key)"> <!--Added click handler -->
                      <v-list-item-title>{{ key }}</v-list-item-title>
                    </v-list-item>
                  </template>
                  <v-list>
                    <template v-for="(linkGroup, groupIndex) in links" :key="groupIndex">
                      <v-list-item v-for="(link, linkIndex) in linkGroup" :key="linkIndex" :to="link.path">
                        <v-list-item-title>{{ link.text }}</v-list-item-title>
                      </v-list-item>
                    </template>
                  </v-list>
                </v-list-group>
              </v-list>
            </v-menu>
          </v-col>

          <v-col v-if="isMobile" cols="auto">
            <v-menu offset-y>
              <template #activator="{ on, attrs }">
                <v-btn v-bind="attrs" icon @click="openMobileMenu">  <!-- Explicit click handler -->
                  <v-icon>mdi-menu</v-icon>
                </v-btn>
              </template>
              <v-list>
                <v-list-item v-for="(item, index) in navigationItems" :key="index" :to="item.subItems[0]?.path || '#'">
                  <v-list-item-title>{{ item.text }}</v-list-item-title>
                </v-list-item>
              </v-list>
            </v-menu>
          </v-col>
        </v-row>
      </v-container>
    </v-app-bar>

    <v-navigation-drawer
      v-if="navigationDrawerVisible"
      v-model="drawer"
      app
      color="primary"
      dark
      temporary
    >
      <v-list>
        <v-list-group
          v-for="item in navigationItems"
          :key="item.text"
          no-action
        >
          <template #activator>
            <v-list-item>
              <v-icon left>{{ item.icon }}</v-icon>
              <v-list-item-title>{{ item.text }}</v-list-item-title>
            </v-list-item>
          </template>
          <v-list-item
            v-for="subItem in item.subItems"
            :key="subItem.path"
            :to="subItem.path"
          >
            <v-list-item-title>{{ subItem.text }}</v-list-item-title>
          </v-list-item>
        </v-list-group>

        <v-list-item v-if="showThemeSwitch" @click="toggleTheme">
          <v-icon left>{{ themeIcon }}</v-icon>
          <v-list-item-title>Change Theme</v-list-item-title>
        </v-list-item>

        <v-menu v-if="showLanguageSwitch" offset-y>
          <template #activator="{ on, attrs }">
            <v-list-item v-bind="attrs" v-on="on">
              <v-icon left>mdi-translate</v-icon>
              <v-list-item-title>Change Language</v-list-item-title>
            </v-list-item>
          </template>
          <v-list>
            <v-list-item
              v-for="option in languageOptions"
              :key="option.value"
            >
              <v-img
                class="v-img__img v-img__img--contain"
                :src="getFlagSrc(option.flag)"
                @click="() => { if (option) changeLanguage(option.value) }"
              />
              <v-list-item-title>{{ option.text }}</v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
      </v-list>
    </v-navigation-drawer>

    <v-main>
      <component
        :is="activeSectionComponent"
        :items="sectionItems"
      />
    </v-main>

    <v-footer v-if="footerVisible" app>
      <v-container fluid>
        <v-row>
          <v-col
            v-for="(column, columnIndex) in footerContent"
            :key="columnIndex"
            :cols="12 / footerColumns"
            :lg="3"
            :md="4"
            :sm="12"
          >
            <template v-if="column.columnType === 'logo-contact'">
              <v-img
                v-if="column.logo"
                alt="Logo"
                class="ml-0"
                contain
                max-height="100"
                max-width="200"
                :src="column.logo"
              />
              <div v-if="column.brand" class="text-body-2 font-weight-bold">{{ column.brand }}</div>
              <div v-if="column.address" class="text-body-1">{{ column.address }}</div>
              <div v-if="column.contact" class="text-body-1">{{ column.contact }}</div>
            </template>
            <template v-else-if="column.columnType === 'links'">
              <h3 v-if="column.header">{{ column.header }}</h3>
              <v-list>
                <v-list-item
                  v-for="link in column.links || []"
                  :key="link.path"
                  :to="link.path"
                >
                  <v-list-item-title>{{ link.text }}</v-list-item-title>
                </v-list-item>
              </v-list>
            </template>
            <div v-else-if="column.columnType === 'copyright'">
              {{ column.copyright }}
            </div>
            <div v-else-if="column.columnType === 'social'">
              <h3 class="mb-4">Social Media</h3>
              <v-row class="d-flex align-center">
                <v-btn
                  v-for="(link, linkIndex) in column.socialLinks || []"
                  :key="linkIndex"
                  class="mx-2"
                  :href="link.link"
                  icon
                  target="_blank"
                >
                  <v-icon>{{ link.icon }}</v-icon>
                </v-btn>
              </v-row>
            </div>
          </v-col>
        </v-row>
      </v-container>
    </v-footer>

    <v-bottom-navigation v-if="isMobile && navigationDrawerVisible" app>
      <v-btn
        v-for="item in navigationItems"
        :key="item.text"
        :to="item.subItems && item.subItems.length > 0 ? item.subItems[0].path : '#'"
        @click="drawer = true"
      >
        <v-icon left>{{ item.icon }}</v-icon>
        <span>{{ item.text }}</span>
      </v-btn>
    </v-bottom-navigation>
  </v-app>
</template>

<script lang="ts">
  import { computed, defineComponent, ref } from 'vue'
  import { useRoute } from 'vue-router'
  import { useTheme } from 'vuetify'
  import layouts, { AppBarItem, LanguageSwitch, Layout, Logo, MegaMenu } from './layoutTypes'

  export default defineComponent({
    setup () {
      const route = useRoute()
      const theme = useTheme()

      const currentLayout = computed<Layout>(() => {
        const layoutName = route.meta.layout || 'WebsiteLayout'
        return layouts[layoutName] || layouts.WebsiteLayout
      })

      const appBarVisible = computed(() => currentLayout.value.appBar.visible)
      const footerVisible = computed(() => currentLayout.value.footer.visible)
      const navigationDrawerVisible = computed(() => !!currentLayout.value.navigationDrawer)
      const footerColumns = computed(() => currentLayout.value.footer.columns)
      const footerContent = computed(() => currentLayout.value.footer.content)
      const navigationItems = computed(() => currentLayout.value.navigationDrawer?.items || [])
      const isMobile = computed(() => window.innerWidth < 600)

      const drawer = ref(false)
      const selectedLanguage = ref(localStorage.getItem('language') || 'en')
      const themeName = ref(localStorage.getItem('theme') || 'LightTheme')
      const themeIcon = computed(() => (themeName.value === 'LightTheme' ? 'mdi-weather-sunny' : 'mdi-weather-night'))

      const activeSection = computed(() => {
        const currentPath = route.path.split('#')[0]
        const pages = currentLayout.value.pages
        const sections = pages && pages[route.name as string]?.sections
        return sections?.find((section: { path: string; }) => section.path === currentPath) || { component: 'div', items: [], dataModel: null }
      })

      const activeSectionComponent = computed(() => activeSection.value?.component || 'div')
      const sectionItems = computed(() => activeSection.value?.dataModel ? models[activeSection.value.dataModel]?.fields || [] : [])

      // Refactored computed properties for app bar items
      const logoItem = computed(() => currentLayout.value.appBar.items.find((item: AppBarItem) => item.type === 'logo') as Logo | undefined)
      const showSpacer = computed(() => currentLayout.value.appBar.items.some((item: AppBarItem) => item.type === 'spacer'))
      const showThemeSwitch = computed(() => currentLayout.value.appBar.items.some((item: AppBarItem) => item.type === 'themeSwitch'))
      const showLanguageSwitch = computed(() => currentLayout.value.appBar.items.some((item: AppBarItem) => item.type === 'languageSwitch'))
      const languageSwitchItem = computed(() => currentLayout.value.appBar.items.find((item: AppBarItem) => item.type === 'languageSwitch') as LanguageSwitch | undefined)
      const languageOptions = computed(() => languageSwitchItem.value?.options || [])
      const selectedLanguageFlag = computed(() => getFlagSrc(selectedLanguage.value))
      const showMegaMenu = computed(() => currentLayout.value.appBar.items.some((item: AppBarItem) => item.type === 'megaMenu'))
      const megaMenuItem = computed(() => currentLayout.value.appBar.items.find((item: AppBarItem) => item.type === 'megaMenu') as MegaMenu | undefined)
      const megaMenu = computed(() => megaMenuItem.value?.menu || {})

      const toggleTheme = () => {
        themeName.value = themeName.value === 'LightTheme' ? 'DarkTheme' : 'LightTheme'
        theme.global.name.value = themeName.value
        localStorage.setItem('theme', themeName.value)
      }

      const changeLanguage = (newLanguage: string) => {
        selectedLanguage.value = newLanguage
        localStorage.setItem('language', newLanguage)
      }

      const getFlagSrc = (flag: string) => `/images/flags/${flag}.png`
      const logoSrc = computed(() => logoItem.value?.src || '/images/logo_text.png')

      return {
        appBarVisible,
        footerVisible,
        navigationDrawerVisible,
        footerColumns,
        footerContent,
        drawer,
        navigationItems,
        isMobile,
        activeSectionComponent,
        sectionItems,
        themeIcon,
        toggleTheme,
        showThemeSwitch,
        showLanguageSwitch,
        languageOptions,
        changeLanguage,
        selectedLanguageFlag,
        logoSrc,
        showSpacer,
        showMegaMenu,
        megaMenu,
        getFlagSrc,
      }
    },
  })
</script>
<style>
/* Add global styles here */
</style>
refactor but do not modularize make it responsive and ensure all image in the app bar shows and the mega menu should be like a real mega menu