<template>
  <q-layout view="hHh Lpr lFf">
    <q-drawer
      :mini="!leftDrawerOpen"
      bordered
      persistent
      :model-value="true"
    >
      <q-list>
        <q-item
          clickable
          v-ripple
          @click="toggleLeftDrawer"
        >
          <q-item-section avatar>
            <q-icon name="menu" />
          </q-item-section>
          <q-item-section>
            <q-item-label class="text-h6">
              StylePoint
            </q-item-label>
          </q-item-section>
        </q-item>

        <!-- Dynamic Navigation Items -->
        <q-item
          v-for="item in navItems"
          :key="item.name"
          clickable
          v-ripple
          :to="{ name: item.name }"
          exact
        >
          <q-tooltip
            anchor="center right"
            self="center left"
          >
            <span>{{ item.meta.title }}</span>
          </q-tooltip>
          <q-item-section avatar>
            <q-icon :name="item.meta.icon" />
          </q-item-section>
          <q-item-section>
            <q-item-label>{{ item.meta.title }}</q-item-label>
            <q-item-label caption>
              {{ item.meta.caption }}
            </q-item-label>
          </q-item-section>
        </q-item>

        <!-- Logout Button (Conditional) -->
        <q-item
          v-if="authStore.isAuthenticated"
          clickable
          v-ripple
          @click="logout"
        >
          <q-tooltip
            anchor="center right"
            self="center left"
          >
            <span>Logout</span>
          </q-tooltip>
          <q-item-section avatar>
            <q-icon name="logout" />
          </q-item-section>
          <q-item-section>
            <q-item-label>Logout</q-item-label>
          </q-item-section>
        </q-item>
      </q-list>
    </q-drawer>

    <q-page-container>
      <router-view />
    </q-page-container>

    <!-- Chat FAB -->
    <q-page-sticky
      v-if="isAuthenticated"
      position="bottom-right"
      :offset="[18, 18]"
    >
      <q-fab
        v-model="fabOpen"
        icon="chat"
        color="accent"
        direction="up"
        padding="sm"
        @click="toggleChat"
      />
    </q-page-sticky>

    <!-- Chat Window Dialog -->
    <q-dialog
      v-model="isChatVisible"
      :maximized="$q.screen.lt.sm"
      fixed
      persistent
      style="width: max(400px, 25%);"
    >
      <q-card style="width: max(400px, 25%); height: 600px; max-height: 80vh;">
        <q-bar class="bg-primary text-white">
          <div>Chat</div>
          <q-space />
          <q-btn
            dense
            flat
            icon="close"
            @click="toggleChat"
          />
        </q-bar>

        <q-card-section
          class="q-pa-none"
          style="height: calc(100% - 50px);"
        >
          <ChatInterface
            :messages="chatMessages"
            @send-message="handleSendMessage"
          />
        </q-card-section>
        <q-inner-loading :showing="isLoading">
          <q-spinner-gears
            size="50px"
            color="primary"
          />
        </q-inner-loading>
        <q-banner
          v-if="chatError"
          inline-actions
          class="text-white bg-red"
        >
          {{ chatError }}
          <template #action>
            <q-btn
              flat
              color="white"
              label="Dismiss"
              @click="clearError"
            />
          </template>
        </q-banner>
      </q-card>
    </q-dialog>
  </q-layout>
</template>

<script setup>
import axios from 'boot/axios';
import { ref, computed } from 'vue'; // Import computed
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';
import { useAuthStore } from 'stores/auth'; // Import the auth store
import { useChatStore } from 'stores/chat'; // Adjust path as needed
import ChatInterface from 'components/ChatInterface.vue'; // Adjust path as needed
import routes from '../router/routes'; // Import routes

const $q = useQuasar();
const leftDrawerOpen = ref(false);
const router = useRouter();
const authStore = useAuthStore(); // Use the auth store
const chatStore = useChatStore();

const fabOpen = ref(false); // Local state for FAB animation, not chat visibility

// Computed properties to get state from the store
const isChatVisible = computed(() => chatStore.isChatVisible);
const chatMessages = computed(() => chatStore.chatMessages);
const isLoading = computed(() => chatStore.isLoading);
const chatError = computed(() => chatStore.error);
const isAuthenticated = computed(() => authStore.isAuthenticated); // Get auth state

// Get the child routes of the main layout
const mainLayoutRoutes = routes.find(r => r.path === '/')?.children || [];

// Compute navigation items based on auth state and route meta
const navItems = computed(() => 
{
  return mainLayoutRoutes.filter(route => 
  {
    const navGroup = route.meta?.navGroup;
    if (!navGroup) return false; // Only include routes with navGroup defined

    if (navGroup === 'always') return true;
    if (navGroup === 'auth' && isAuthenticated.value) return true;
    if (navGroup === 'noAuth' && !isAuthenticated.value) return true;

    return false; // Exclude otherwise
  });
});


// Method to toggle chat visibility via the store action
const toggleChat = () => 
{
  // Optional: Add an extra check here if needed, though hiding the button is primary
  if (isAuthenticated.value) 
  {
    chatStore.toggleChat();
  }
};

// Method to send a message via the store action
const handleSendMessage = (messageContent) => 
{
  chatStore.sendMessage(messageContent);
};

// Method to clear errors in the store (optional)
const clearError = () => 
{
  chatStore.error = null; // Directly setting ref or add an action in store
};
function toggleLeftDrawer() 
{
  leftDrawerOpen.value = !leftDrawerOpen.value;
}

async function logout() 
{
  try 
  {
    await axios.post('/api/auth/logout');
    authStore.logout(); // Use the store action to update state
    // No need to manually push, router guard should redirect
    // router.push({ name: 'login' });
  }
  catch (error) 
  {
    console.error('Logout failed:', error);

    $q.notify({
      color: 'negative',
      message: 'Logout failed. Please try again.',
      icon: 'report_problem'
    });
  }
}
</script>

<style scoped>
/* Add any specific styles for the layout or chat window here */
.q-dialog .q-card {
    overflow: hidden; /* Prevent scrollbars on the card itself */
}
</style>