<template>
  <aside class="w-64 bg-white border-r border-gray-200 flex flex-col h-full shrink-0">
    <!-- Logo -->
    <div class="px-6 py-5 border-b border-gray-100">
      <h1 class="text-lg font-bold text-indigo-600 tracking-tight">DocuVault</h1>
      <p class="text-xs text-gray-400 mt-0.5">Document Manager</p>
    </div>

    <!-- Nav -->
    <nav class="flex-1 px-3 py-4 overflow-y-auto">
      <router-link
        to="/topics"
        class="nav-link"
        :class="{ 'nav-link-active': $route.path.startsWith('/topics') }"
      >
        <svg class="w-4 h-4 mr-2 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
        </svg>
        All Topics
      </router-link>

      <!-- Shared with me -->
      <router-link
        to="/shared"
        class="nav-link"
        :class="{ 'nav-link-active': $route.path === '/shared' }"
      >
        <div class="w-4 h-4 mr-2 shrink-0 rounded bg-purple-50 flex items-center justify-center">
          <svg class="w-3 h-3 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
          </svg>
        </div>
        <span class="flex-1">Shared with me</span>
        <span
          v-if="sharedCount > 0"
          class="ml-auto bg-purple-100 text-purple-600 text-xs font-semibold rounded-full px-2 min-w-[18px] text-center"
        >
          {{ sharedCount }}
        </span>
      </router-link>

      <!-- Folders root + collapsible tree -->
      <div class="mt-3">
        <div class="flex items-center gap-0.5">
          <!-- Expand/collapse chevron -->
          <button
            @click="foldersExpanded = !foldersExpanded"
            class="p-1 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors shrink-0"
            :title="foldersExpanded ? 'Collapse folders' : 'Expand folders'"
          >
            <svg
              class="w-3 h-3 transition-transform duration-150"
              :class="foldersExpanded ? 'rotate-90' : ''"
              fill="none" stroke="currentColor" viewBox="0 0 24 24"
            >
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
            </svg>
          </button>

          <!-- "Folders" navigates to root file manager -->
          <router-link
            to="/"
            class="nav-link flex-1 min-w-0"
            :class="{ 'nav-link-active': $route.path === '/' || $route.path.startsWith('/folders/') }"
          >
            <svg class="w-4 h-4 mr-2 shrink-0 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" />
            </svg>
            Folders
          </router-link>

          <button
            @click="startNewFolder"
            class="text-xs text-indigo-600 hover:underline shrink-0 mr-1"
            title="New root folder"
          >
            New
          </button>
        </div>

        <!-- Collapsible content -->
        <template v-if="foldersExpanded">
          <!-- Inline new root folder input -->
          <div v-if="showNewFolderInput" class="px-3 mb-2 mt-1">
            <input
              v-model="newFolderName"
              type="text"
              placeholder="Folder name"
              class="block w-full border border-gray-300 rounded-lg px-2 py-1 text-xs focus:outline-none focus:ring-2 focus:ring-indigo-500"
              @keydown.enter="submitNewFolder"
              @keydown.escape="cancelNewFolder"
              autofocus
            />
            <p v-if="newFolderError" class="text-red-500 text-xs mt-1">{{ newFolderError }}</p>
          </div>

          <!-- Sub-folders tree -->
          <div v-if="loadingRoots" class="pl-7 py-1 text-xs text-gray-400">Loading…</div>
          <div v-else-if="foldersStore.rootFolders.length === 0 && !showNewFolderInput"
            class="pl-7 py-1 text-xs text-gray-400">No folders yet</div>
          <FolderTreeItem
            v-for="folder in foldersStore.rootFolders"
            :key="folder.id"
            :folder="folder"
            :depth="1"
          />
        </template>
      </div>

      <!-- Cloud Storage section -->
      <div class="mt-3">
        <div class="flex items-center gap-0.5">
          <!-- Expand/collapse chevron -->
          <button
            @click="cloudExpanded = !cloudExpanded"
            class="p-1 rounded hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors shrink-0"
            :title="cloudExpanded ? 'Collapse cloud storage' : 'Expand cloud storage'"
          >
            <svg
              class="w-3 h-3 transition-transform duration-150"
              :class="cloudExpanded ? 'rotate-90' : ''"
              fill="none" stroke="currentColor" viewBox="0 0 24 24"
            >
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
            </svg>
          </button>

          <!-- "Cloud Storage" navigates to the cloud overview -->
          <router-link
            to="/cloud"
            class="nav-link flex-1 min-w-0"
            :class="{ 'nav-link-active': $route.path.startsWith('/cloud') }"
          >
            <svg class="w-4 h-4 mr-2 shrink-0 text-sky-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z" />
            </svg>
            Cloud Storage
          </router-link>
        </div>

        <!-- Collapsible content -->
        <template v-if="cloudExpanded">
          <div v-if="loadingCloudConnections" class="pl-7 py-1 text-xs text-gray-400">Loading…</div>
          <div v-else-if="activeCloudConnections.length === 0" class="pl-7 py-1 text-xs text-gray-400">
            No cloud storage connected
          </div>
          <CloudProviderTreeItem
            v-for="connection in activeCloudConnections"
            :key="connection.id"
            :connection="connection"
            :depth="1"
          />
        </template>
      </div>

      <!-- Topics list -->
      <div class="mt-3">
        <p class="px-3 text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Topics</p>
        <div v-if="topicsStore.loading" class="px-3 py-1 text-xs text-gray-400">Loading…</div>
        <div v-else-if="topicsStore.topics.length === 0" class="px-3 py-1 text-xs text-gray-400">No topics yet</div>
        <router-link
          v-for="topic in topicsStore.topics"
          :key="topic.id"
          :to="`/topics/${encodeURIComponent(topic.name)}`"
          class="nav-link text-sm"
          :class="{ 'nav-link-active': $route.params.name === topic.name }"
        >
          <span
            class="w-2.5 h-2.5 rounded-full mr-2 shrink-0"
            :style="{ backgroundColor: topic.color }"
          ></span>
          <span class="truncate">{{ topic.name }}</span>
          <span class="ml-auto text-xs text-gray-400">{{ topic.doc_count }}</span>
        </router-link>
      </div>
    </nav>

    <!-- Quota bar -->
    <QuotaBar />

    <!-- Settings + Admin link -->
    <div class="px-3 py-4 border-t border-gray-100">
      <!-- Admin link (admin users only) -->
      <router-link
        v-if="authStore.user?.role === 'admin'"
        to="/admin"
        class="nav-link"
        :class="{ 'nav-link-active': $route.path === '/admin' }"
      >
        <svg class="w-4 h-4 mr-2 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
        </svg>
        Admin
      </router-link>

      <router-link
        to="/settings"
        class="nav-link"
        :class="{ 'nav-link-active': $route.path === '/settings' }"
      >
        <svg class="w-4 h-4 mr-2 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
        Settings
      </router-link>

      <!-- User identity footer -->
      <div v-if="authStore.user" class="flex items-center gap-3 px-4 py-3 border-t border-gray-100 mt-2 -mx-3">
        <div class="bg-indigo-100 text-indigo-700 text-xs font-semibold rounded-full w-8 h-8 flex items-center justify-center shrink-0">
          {{ authStore.user.email ? authStore.user.email[0].toUpperCase() : '?' }}
        </div>
        <span class="text-xs text-gray-600 truncate flex-1">{{ authStore.user.email }}</span>
        <button
          @click="signOut"
          aria-label="Sign out"
          class="text-gray-400 hover:text-gray-600 transition-colors"
        >
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
          </svg>
        </button>
      </div>
    </div>
  </aside>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useTopicsStore } from '../../stores/topics.js'
import { useAuthStore } from '../../stores/auth.js'
import { useFoldersStore } from '../../stores/folders.js'
import { useCloudConnectionsStore } from '../../stores/cloudConnections.js'
import QuotaBar from './QuotaBar.vue'
import FolderTreeItem from '../folders/FolderTreeItem.vue'
import CloudProviderTreeItem from '../cloud/CloudProviderTreeItem.vue'
import * as api from '../../api/client.js'

const topicsStore = useTopicsStore()
const authStore = useAuthStore()
const foldersStore = useFoldersStore()
const cloudConnectionsStore = useCloudConnectionsStore()
const router = useRouter()

const sharedCount = ref(0)
const showNewFolderInput = ref(false)
const newFolderName = ref('')
const newFolderError = ref('')
const loadingRoots = ref(true)
const foldersExpanded = ref(false)
const cloudExpanded = ref(true)

const activeCloudConnections = computed(() =>
  cloudConnectionsStore.connections.filter(c => c.status === 'ACTIVE')
)
const loadingCloudConnections = computed(() => cloudConnectionsStore.loading)

watch(() => foldersStore.treeVersion, () => foldersStore.fetchRootFolders())

onMounted(async () => {
  try {
    await foldersStore.fetchRootFolders()
  } finally {
    loadingRoots.value = false
  }
  try {
    const data = await api.getSharedWithMe()
    const items = Array.isArray(data) ? data : (data.items ?? [])
    sharedCount.value = items.length
  } catch {
    sharedCount.value = 0
  }
  cloudConnectionsStore.fetchConnections()
})

async function signOut() {
  await authStore.logout()
  router.push('/login')
}

function startNewFolder() {
  newFolderName.value = ''
  newFolderError.value = ''
  showNewFolderInput.value = true
}

function cancelNewFolder() {
  showNewFolderInput.value = false
  newFolderError.value = ''
}

async function submitNewFolder() {
  const trimmed = newFolderName.value.trim()
  if (!trimmed) {
    newFolderError.value = 'Folder name cannot be empty.'
    return
  }
  try {
    await foldersStore.createFolder(trimmed, null)
    showNewFolderInput.value = false
    newFolderError.value = ''
  } catch (e) {
    newFolderError.value = e.message || 'Failed to create folder.'
  }
}
</script>

<style scoped>
.nav-link {
  @apply flex items-center px-3 py-2 rounded-lg text-gray-600 hover:bg-gray-100 hover:text-gray-900 transition-colors text-sm font-medium;
}
.nav-link-active {
  @apply bg-indigo-50 text-indigo-700;
}
</style>
