<template>
  <div class="p-8 max-w-3xl mx-auto">
    <BreadcrumbBar :segments="breadcrumbSegments" :show-root="false" class="mb-4" />

    <h2 class="text-2xl font-semibold text-gray-900 mb-1">Settings</h2>
    <p class="text-sm text-gray-500 mb-6">Account-level options for your DocuVault workspace.</p>

    <!-- OAuth success toast (fixed top-right, auto-dismisses 5s) -->
    <div
      v-if="oauthSuccessProvider"
      class="fixed top-4 right-4 z-50 flex items-center gap-3 bg-white border border-green-200 rounded-xl shadow-lg px-5 py-4 max-w-sm"
    >
      <AppIcon name="checkCircle" class="w-5 h-5 text-green-500 shrink-0" />
      <div class="flex-1 min-w-0">
        <p class="text-sm font-semibold text-gray-900">{{ providerDisplayName(oauthSuccessProvider) }} connected</p>
        <p class="text-xs text-gray-500 mt-0.5">Your files are now available in the sidebar.</p>
      </div>
      <button
        @click="oauthSuccessProvider = null"
        aria-label="Dismiss notification"
        class="text-gray-400 hover:text-gray-600 shrink-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-1 rounded"
      >
        <AppIcon name="x" class="w-4 h-4" />
      </button>
    </div>

    <!-- Tab strip -->
    <div class="flex border-b border-gray-200 mb-6">
      <button
        v-for="tab in tabs"
        :key="tab.id"
        @click="activeTab = tab.id"
        class="px-4 py-2 text-sm font-semibold border-b-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-1 rounded-t"
        :class="activeTab === tab.id
          ? 'text-indigo-600 border-indigo-600'
          : 'text-gray-500 hover:text-gray-700 border-transparent'"
      >
        {{ tab.label }}
      </button>
    </div>

    <!-- Tab: Preferences -->
    <SettingsPreferencesTab v-if="activeTab === 'preferences'" />

    <!-- Tab: AI Configuration -->
    <SettingsAiTab v-if="activeTab === 'ai'" />

    <!-- Tab: Account -->
    <SettingsAccountTab v-if="activeTab === 'account'" />

    <!-- Tab: Cloud Storage -->
    <div v-if="activeTab === 'cloud'">
      <!-- OAuth error banner (persistent until dismissed) -->
      <div
        v-if="oauthError"
        class="mb-6 flex items-start gap-3 bg-red-50 border border-red-200 rounded-xl px-5 py-4"
      >
        <AppIcon name="exclamationCircle" class="w-5 h-5 text-red-500 shrink-0 mt-0.5" />
        <div class="flex-1 min-w-0">
          <p class="text-sm font-semibold text-red-700">Connection failed</p>
          <p class="text-sm text-red-600 mt-0.5">{{ oauthError }}</p>
          <p class="text-xs text-red-500 mt-1">Try connecting again. If the problem persists, check that the app has the correct permissions in your provider's account settings.</p>
        </div>
        <button
          @click="oauthError = null"
          aria-label="Dismiss error"
          class="text-red-400 hover:text-red-600 shrink-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-1 rounded"
        >
          <AppIcon name="x" class="w-4 h-4" />
        </button>
      </div>

      <SettingsCloudTab />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import AppIcon from '../components/ui/AppIcon.vue'
import SettingsPreferencesTab from '../components/settings/SettingsPreferencesTab.vue'
import SettingsAiTab from '../components/settings/SettingsAiTab.vue'
import SettingsCloudTab from '../components/settings/SettingsCloudTab.vue'
import SettingsAccountTab from '../components/settings/SettingsAccountTab.vue'
import BreadcrumbBar from '../components/ui/BreadcrumbBar.vue'

const router = useRouter()

const tabs = [
  { id: 'preferences', label: 'Preferences' },
  { id: 'ai', label: 'AI Configuration' },
  { id: 'cloud', label: 'Cloud Storage' },
  { id: 'account', label: 'Account' },
]

const activeTab = ref('preferences')

const breadcrumbSegments = computed(() => {
  const tab = tabs.find(t => t.id === activeTab.value)
  return [{ label: 'Settings' }, { label: tab?.label ?? activeTab.value }]
})
const oauthSuccessProvider = ref(null)
const oauthError = ref(null)

const PROVIDER_NAMES = {
  google_drive: 'Google Drive',
  onedrive: 'OneDrive',
  nextcloud: 'Nextcloud',
  webdav: 'WebDAV server',
}

function providerDisplayName(key) {
  return PROVIDER_NAMES[key] || key
}

onMounted(() => {
  const params = new URLSearchParams(window.location.search)
  const connectedProvider = params.get('cloud_connected')
  const errorMsg = params.get('cloud_error')

  if (connectedProvider || errorMsg) {
    activeTab.value = 'cloud'
    router.replace({ path: '/settings' })

    if (connectedProvider) {
      oauthSuccessProvider.value = connectedProvider
      setTimeout(() => { oauthSuccessProvider.value = null }, 5000)
    }

    if (errorMsg) {
      oauthError.value = decodeURIComponent(errorMsg)
    }
  }
})
</script>
