<template>
  <div class="drawer lg:drawer-open">
    <input id="main-drawer" type="checkbox" class="drawer-toggle" v-model="drawerOpen" />

    <!-- Main content area -->
    <div class="drawer-content flex flex-col bg-base-200" :class="$slots.sidebar ? 'h-screen' : 'min-h-screen'">
      <!-- TopBar -->
      <TopBar
        :session-checked="sessionChecked"
        :logged-in="isLoggedIn"
        :novu-subscriber-id="novuSubscriberId"
        :user-avatar-svg="userAvatarSvg"
        :user-name="userName"
        :user-initials="userInitials"
        :theme="theme"
        @toggle-theme="toggleTheme"
        @toggle-sidebar="drawerOpen = !drawerOpen"
        @sign-out="onClickSignOut"
        @sign-in="signIn()"
      />

      <!-- Page content -->
      <main class="flex-1 flex flex-col min-h-0" :class="$slots.sidebar ? '' : 'p-4 lg:p-6'">
        <slot />
      </main>

      <!-- Footer (hide when custom sidebar is used, e.g. map page) -->
      <FooterPublic v-if="!$slots.sidebar" />
    </div>

    <!-- Sidebar drawer -->
    <div class="drawer-side z-50">
      <label for="main-drawer" aria-label="close sidebar" class="drawer-overlay"></label>
      <slot name="sidebar">
        <Sidebar
          :user-data="userData"
          :is-seller="isSeller"
          :logged-in="isLoggedIn"
          @switch-team="switchToTeam"
        />
      </slot>
    </div>
  </div>
</template>

<script setup lang="ts">
const runtimeConfig = useRuntimeConfig()
const siteUrl = runtimeConfig.public.siteUrl || 'https://optovia.ru/'
const { signIn, signOut, loggedIn, fetch: fetchSession } = useAuth()

const drawerOpen = ref(false)
// Theme: use CSS default when not set, switch to DaisyUI "night" for dark
const theme = useState<'default' | 'night'>('theme', () => 'default')
const userData = useState<{
  id?: string
  firstName?: string
  lastName?: string
  avatarId?: string
  activeTeam?: { name?: string; teamType?: string; logtoOrgId?: string }
  activeTeamId?: string
  teams?: Array<{ id?: string; name?: string; logtoOrgId?: string }>
} | null>('me', () => null)
const sessionChecked = ref(false)
const userAvatarSvg = useState('user-avatar-svg', () => '')
const lastAvatarSeed = useState('user-avatar-seed', () => '')
const novuSubscriberId = useState('novu-subscriber-id', () => '')

const isSeller = computed(() => {
  return userData.value?.activeTeam?.teamType === 'SELLER'
})

const isLoggedIn = computed(() => loggedIn.value || !!userData.value?.id)

const userName = computed(() => {
  return userData.value?.firstName || 'User'
})

const userInitials = computed(() => {
  const first = userData.value?.firstName?.charAt(0) || ''
  const last = userData.value?.lastName?.charAt(0) || ''
  if (first || last) return (first + last).toUpperCase()
  return '?'
})

// Avatar generation
const generateUserAvatar = async (seed: string) => {
  if (!seed) return
  try {
    const response = await fetch(`https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(seed)}&backgroundColor=b6e3f4,c0aede,d1d4f9`)
    if (response.ok) {
      userAvatarSvg.value = await response.text()
      lastAvatarSeed.value = seed
    }
  } catch (error) {
    console.error('Error generating avatar:', error)
  }
}

const computeNovuSubscriber = () => {
  const uuid = userData.value?.id
  if (uuid) return uuid
  return ''
}

const { setActiveTeam } = useActiveTeam()
const { mutate } = useGraphQL()
const locationStore = useLocationStore()

const syncUserUi = async () => {
  if (!userData.value) {
    novuSubscriberId.value = ''
    locationStore.clear()
    return
  }

  if (userData.value.activeTeamId && userData.value.activeTeam?.logtoOrgId) {
    setActiveTeam(userData.value.activeTeamId, userData.value.activeTeam.logtoOrgId)
  }

  novuSubscriberId.value = computeNovuSubscriber()

  const seed = userData.value.avatarId || userData.value.id || userData.value.firstName || 'default'

  if (!userAvatarSvg.value || lastAvatarSeed.value !== seed) {
    userAvatarSvg.value = ''
    await generateUserAvatar(seed)
  }

  // Установить локацию из данных пользователя
  locationStore.setFromUserData(userData.value.activeTeam?.selectedLocation)
}

watch(userData, () => {
  void syncUserUi()
}, { immediate: true })

// Check session (SSR + client navigation)
await fetchSession().catch(() => {})
sessionChecked.value = true

const switchToTeam = async (team: { id?: string; logtoOrgId?: string; name?: string }) => {
  if (!team?.id) return

  try {
    const { SwitchTeamDocument } = await import('~/composables/graphql/user/teams-generated')
    const result = await mutate(SwitchTeamDocument, { teamId: team.id }, 'user', 'teams')

    if (result.switchTeam?.user && userData.value) {
      userData.value.activeTeam = team as typeof userData.value.activeTeam
      userData.value.activeTeamId = team.id
      if (team.logtoOrgId) {
        setActiveTeam(team.id, team.logtoOrgId)
      }
    }
  } catch (err) {
    console.error('Failed to switch team:', err)
  }
}

const onClickSignOut = () => {
  signOut(siteUrl)
}

const applyTheme = (value: 'default' | 'night') => {
  if (process.client) {
    if (value === 'default') {
      document.documentElement.removeAttribute('data-theme')
    } else {
      document.documentElement.setAttribute('data-theme', value)
    }
    localStorage.setItem('theme', value)
  }
}

onMounted(() => {
  const stored = process.client ? localStorage.getItem('theme') : null
  if (stored === 'night' || stored === 'default') {
    theme.value = stored
  }
  applyTheme(theme.value)
})

watch(theme, (value) => applyTheme(value))

const toggleTheme = () => {
  theme.value = theme.value === 'night' ? 'default' : 'night'
}

// Close drawer on route change (mobile)
const route = useRoute()
watch(() => route.path, () => {
  drawerOpen.value = false
})
</script>
