<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDocumentsStore } from '@/stores/documents'
import type { DocumentReasoning, BacklinksResponse, OutgoingLinksResponse } from '@/types'
import Header from '@/components/layout/Header.vue'
import Button from '@/components/common/Button.vue'
import Modal from '@/components/common/Modal.vue'
import TipTapEditor from '@/components/editor/TipTapEditor.vue'
import ReasoningPanel from '@/components/editor/ReasoningPanel.vue'

const route = useRoute()
const router = useRouter()
const documentsStore = useDocumentsStore()

const editTitle = ref('')
const tiptapContent = ref<Record<string, unknown> | null>(null)
const showTagModal = ref(false)
const newTagName = ref('')
const newTagColor = ref('#6366f1')
const showReasoningPanel = ref(true)
const saveTimeout = ref<ReturnType<typeof setTimeout> | null>(null)
const isReady = ref(false)

// Phase 3: Backlinks & Links
const backlinks = ref<BacklinksResponse | null>(null)
const outgoingLinks = ref<OutgoingLinksResponse | null>(null)
const backlinksLoading = ref(false)
const showExportModal = ref(false)
const exportFormat = ref<'markdown' | 'json'>('markdown')
const exporting = ref(false)

async function fetchLinks(docId: string) {
  backlinksLoading.value = true
  try {
    const [bl, ol] = await Promise.all([
      documentsStore.fetchBacklinks(docId).catch(() => null),
      documentsStore.fetchOutgoingLinks(docId).catch(() => null)
    ])
    backlinks.value = bl
    outgoingLinks.value = ol
  } finally {
    backlinksLoading.value = false
  }
}

onMounted(async () => {
  const docId = route.params.id as string
  await documentsStore.fetchDocument(docId)
  await documentsStore.fetchTags()

  if (documentsStore.currentDocument) {
    editTitle.value = documentsStore.currentDocument.title

    // Try to load TipTap content first, fall back to markdown conversion
    const savedTipTap = await documentsStore.fetchTipTapContent(docId)
    if (savedTipTap) {
      tiptapContent.value = savedTipTap
    } else if (documentsStore.currentDocument.content) {
      // Convert markdown to TipTap JSON (basic conversion)
      tiptapContent.value = markdownToTiptap(documentsStore.currentDocument.content)
    } else {
      tiptapContent.value = { type: 'doc', content: [{ type: 'paragraph' }] }
    }

    // Load backlinks
    await fetchLinks(docId)
  }
})

watch(() => route.params.id, async (newId) => {
  if (newId) {
    isReady.value = false
    await documentsStore.fetchDocument(newId as string)
    if (documentsStore.currentDocument) {
      editTitle.value = documentsStore.currentDocument.title
      const savedTipTap = await documentsStore.fetchTipTapContent(newId as string)
      if (savedTipTap) {
        tiptapContent.value = savedTipTap
      } else {
        tiptapContent.value = markdownToTiptap(documentsStore.currentDocument.content)
      }
      await fetchLinks(newId as string)
    }
  }
})

watch(() => documentsStore.currentDocument, (doc) => {
  if (doc) {
    editTitle.value = doc.title
  }
})

// Convert markdown string to basic TipTap JSON
function markdownToTiptap(markdown: string): Record<string, unknown> {
  if (!markdown) {
    return { type: 'doc', content: [{ type: 'paragraph' }] }
  }

  const lines = markdown.split('\n')
  const content: unknown[] = []

  for (const line of lines) {
    if (line.startsWith('### ')) {
      content.push({
        type: 'heading',
        attrs: { level: 3 },
        content: [{ type: 'text', text: line.substring(4) }]
      })
    } else if (line.startsWith('## ')) {
      content.push({
        type: 'heading',
        attrs: { level: 2 },
        content: [{ type: 'text', text: line.substring(3) }]
      })
    } else if (line.startsWith('# ')) {
      content.push({
        type: 'heading',
        attrs: { level: 1 },
        content: [{ type: 'text', text: line.substring(2) }]
      })
    } else if (line.startsWith('- ') || line.startsWith('* ')) {
      content.push({
        type: 'bulletList',
        content: [{
          type: 'listItem',
          content: [{
            type: 'paragraph',
            content: [{ type: 'text', text: line.substring(2) }]
          }]
        }]
      })
    } else if (/^\d+\.\s/.test(line)) {
      content.push({
        type: 'orderedList',
        content: [{
          type: 'listItem',
          content: [{
            type: 'paragraph',
            content: [{ type: 'text', text: line.replace(/^\d+\.\s/, '') }]
          }]
        }]
      })
    } else if (line.startsWith('```')) {
      // Skip code block markers for now (would need more complex handling)
      content.push({
        type: 'paragraph',
        content: [{ type: 'text', text: line }]
      })
    } else if (line.trim()) {
      content.push({
        type: 'paragraph',
        content: [{ type: 'text', text: line }]
      })
    } else {
      content.push({ type: 'paragraph' })
    }
  }

  return { type: 'doc', content }
}

function handleContentChange(content: Record<string, unknown>) {
  tiptapContent.value = content
  if (saveTimeout.value) {
    clearTimeout(saveTimeout.value)
  }
  saveTimeout.value = setTimeout(() => {
    saveContent()
  }, 1500)
}

function handleEditorReady() {
  isReady.value = true
}

async function saveContent() {
  if (!documentsStore.currentDocument || !tiptapContent.value) return
  await documentsStore.updateDocumentTipTapContent(
    documentsStore.currentDocument.id,
    tiptapContent.value
  )
}

async function updateTitle() {
  if (!documentsStore.currentDocument || !editTitle.value.trim()) return
  await documentsStore.updateDocument(
    documentsStore.currentDocument.id,
    editTitle.value.trim()
  )
}

async function removeTag(tagId: string) {
  if (!documentsStore.currentDocument) return
  await documentsStore.removeTag(documentsStore.currentDocument.id, tagId)
}

async function createAndAssignTag() {
  if (!newTagName.value.trim() || !documentsStore.currentDocument) return

  const tag = await documentsStore.createTag(newTagName.value.trim(), newTagColor.value)
  const currentTagIds = documentsStore.currentDocument.tags.map(t => t.id)
  await documentsStore.assignTags(documentsStore.currentDocument.id, [...currentTagIds, tag.id])

  showTagModal.value = false
  newTagName.value = ''
  newTagColor.value = '#6366f1'
}

async function goBack() {
  if (documentsStore.currentDocument) {
    router.push(`/projects/${documentsStore.currentDocument.project_id}`)
  } else {
    router.push('/dashboard')
  }
}

// Phase 3: Export
async function handleExport() {
  if (!documentsStore.currentDocument) return
  exporting.value = true
  try {
    const blob = await documentsStore.exportDocument(documentsStore.currentDocument.id, exportFormat.value)
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    const title = documentsStore.currentDocument.title.replace(/[^a-z0-9]/gi, '_')
    a.href = url
    a.download = `${title}.${exportFormat.value}`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    showExportModal.value = false
  } catch (e) {
    console.error('Export failed:', e)
  } finally {
    exporting.value = false
  }
}

function openExportModal() {
  showExportModal.value = true
}

function navigateToDocument(docId: string) {
  router.push(`/documents/${docId}`)
}

async function handleReasoningUpdate(reasoning: DocumentReasoning) {
  if (!documentsStore.currentDocument) return
  await documentsStore.updateReasoning(documentsStore.currentDocument.id, reasoning)
}

async function handleAddStep(thought: string, conclusion: string | null) {
  if (!documentsStore.currentDocument) return
  const step = await documentsStore.addReasoningStep(documentsStore.currentDocument.id, thought, conclusion)
  if (step && documentsStore.currentDocument.reasoning) {
    documentsStore.currentDocument.reasoning.reasoning_steps.push(step)
  }
}

async function handleDeleteStep(step: number) {
  if (!documentsStore.currentDocument) return
  await documentsStore.deleteReasoningStep(documentsStore.currentDocument.id, step)
  if (documentsStore.currentDocument.reasoning) {
    documentsStore.currentDocument.reasoning.reasoning_steps = documentsStore.currentDocument.reasoning.reasoning_steps.filter(s => s.step !== step)
  }
}

const tagColors = [
  '#6366f1', '#8b5cf6', '#ec4899', '#ef4444', '#f97316',
  '#eab308', '#22c55e', '#10b981', '#14b8a6', '#06b6d4'
]
</script>

<template>
  <div class="layout">
    <Header />
    <div class="layout__body">
      <main class="layout__content" :class="{ 'layout__content--with-panel': showReasoningPanel }">
        <div v-if="documentsStore.loading" class="loading">
          <div class="loading__spinner"></div>
          <p>Loading document...</p>
        </div>

        <div v-else-if="documentsStore.error" class="error">
          <p>{{ documentsStore.error }}</p>
          <Button variant="secondary" @click="goBack">Go Back</Button>
        </div>

        <div v-else-if="documentsStore.currentDocument" class="doc-view">
          <div class="doc-view__toolbar">
            <div class="doc-view__toolbar-left">
              <button class="doc-view__back" @click="goBack">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="m15 18-6-6 6-6"/>
                </svg>
                Back
              </button>

              <button
                class="doc-view__panel-toggle"
                :class="{ active: showReasoningPanel }"
                @click="showReasoningPanel = !showReasoningPanel"
                title="Toggle Reasoning Panel"
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M12 2a8 8 0 0 1 8 8c0 3.5-2 6-4 8l-2 2-2-2c-2-2-4-4.5-4-8a8 8 0 0 1 8-8z"/>
                  <circle cx="12" cy="10" r="3"/>
                </svg>
              </button>
            </div>

            <div class="doc-view__toolbar-right">
              <div class="doc-view__saving" v-if="documentsStore.saving">
                <div class="doc-view__saving-dot"></div>
                Saving...
              </div>
              <div class="doc-view__saved" v-else-if="isReady">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <polyline points="20 6 9 17 4 12"/>
                </svg>
                Saved
              </div>
              <button class="doc-view__export" @click="openExportModal" title="Export document">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                  <polyline points="7 10 12 15 17 10"/>
                  <line x1="12" y1="15" x2="12" y2="3"/>
                </svg>
                Export
              </button>
            </div>
          </div>

          <div class="doc-view__header">
            <input
              v-model="editTitle"
              type="text"
              class="doc-view__title"
              placeholder="Untitled Document"
              @blur="updateTitle"
              @keyup.enter="($event.target as HTMLInputElement).blur()"
            />
          </div>

          <div class="doc-view__tags">
            <span
              v-for="tag in documentsStore.currentDocument.tags"
              :key="tag.id"
              class="doc-view__tag"
              :style="{ backgroundColor: tag.color + '20', color: tag.color, borderColor: tag.color }"
            >
              {{ tag.name }}
              <button class="doc-view__tag-remove" @click="removeTag(tag.id)">×</button>
            </span>
            <button class="doc-view__add-tag" @click="showTagModal = true">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="12" y1="5" x2="12" y2="19"/>
                <line x1="5" y1="12" x2="19" y2="12"/>
              </svg>
              Add Tag
            </button>
          </div>

          <!-- Phase 3: Backlinks & Outgoing Links -->
          <div class="doc-view__links" v-if="backlinks || outgoingLinks">
            <div v-if="backlinks && backlinks.backlinks.length > 0" class="doc-view__links-section">
              <h3 class="doc-view__links-title">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
                  <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
                </svg>
                Backlinks ({{ backlinks.backlinks_count }})
              </h3>
              <div class="doc-view__links-list">
                <button
                  v-for="bl in backlinks.backlinks"
                  :key="bl.document_id"
                  class="doc-view__link-item"
                  @click="navigateToDocument(bl.document_id)"
                >
                  <span class="doc-view__link-icon">📄</span>
                  <span class="doc-view__link-info">
                    <span class="doc-view__link-title">{{ bl.title }}</span>
                    <span class="doc-view__link-project">{{ bl.project_name }}</span>
                  </span>
                </button>
              </div>
            </div>

            <div v-if="outgoingLinks && outgoingLinks.outgoing_links.length > 0" class="doc-view__links-section">
              <h3 class="doc-view__links-title">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <line x1="5" y1="12" x2="19" y2="12"/>
                  <polyline points="12 5 19 12 12 19"/>
                </svg>
                Outgoing Links ({{ outgoingLinks.outgoing_links_count }})
              </h3>
              <div class="doc-view__links-list">
                <button
                  v-for="ol in outgoingLinks.outgoing_links"
                  :key="ol.document_id"
                  class="doc-view__link-item"
                  :class="{ 'doc-view__link-item--broken': !ol.exists }"
                  @click="ol.exists && navigateToDocument(ol.document_id)"
                >
                  <span class="doc-view__link-icon">{{ ol.exists ? '📄' : '⚠️' }}</span>
                  <span class="doc-view__link-info">
                    <span class="doc-view__link-title">{{ ol.title || 'Unknown Document' }}</span>
                    <span class="doc-view__link-project">{{ ol.exists ? ol.project_name : 'Document not found' }}</span>
                  </span>
                </button>
              </div>
            </div>
          </div>

          <div class="doc-view__editor">
            <TipTapEditor
              v-if="tiptapContent"
              :model-value="tiptapContent"
              placeholder="Start writing..."
              @update:model-value="handleContentChange"
              @ready="handleEditorReady"
            />
          </div>
        </div>
      </main>

      <!-- Reasoning Panel Sidebar -->
      <ReasoningPanel
        v-if="showReasoningPanel && documentsStore.currentDocument"
        :document-id="documentsStore.currentDocument.id"
        :reasoning="documentsStore.currentDocument.reasoning"
        :editable="true"
        @update="handleReasoningUpdate"
        @add-step="handleAddStep"
        @delete-step="handleDeleteStep"
      />
    </div>

    <!-- Tag Modal -->
    <Modal :show="showTagModal" title="Add Tag" @close="showTagModal = false">
      <div class="form__field">
        <label for="tag-name" class="form__label">Tag Name</label>
        <input
          id="tag-name"
          v-model="newTagName"
          type="text"
          class="form__input"
          placeholder="backend"
          autofocus
        />
      </div>
      <div class="form__field">
        <label class="form__label">Color</label>
        <div class="color-picker">
          <button
            v-for="color in tagColors"
            :key="color"
            :class="['color-picker__option', { 'color-picker__option--selected': color === newTagColor }]"
            :style="{ backgroundColor: color }"
            @click="newTagColor = color"
          ></button>
        </div>
      </div>
      <template #footer>
        <Button variant="secondary" @click="showTagModal = false">Cancel</Button>
        <Button variant="primary" @click="createAndAssignTag">Add Tag</Button>
      </template>
    </Modal>

    <!-- Export Modal -->
    <Modal :show="showExportModal" title="Export Document" @close="showExportModal = false">
      <div class="form__field">
        <label class="form__label">Format</label>
        <div class="export-formats">
          <button
            :class="['export-format', { 'export-format--selected': exportFormat === 'markdown' }]"
            @click="exportFormat = 'markdown'"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
              <polyline points="14 2 14 8 20 8"/>
              <line x1="16" y1="13" x2="8" y2="13"/>
              <line x1="16" y1="17" x2="8" y2="17"/>
              <polyline points="10 9 9 9 8 9"/>
            </svg>
            <span>Markdown</span>
            <small>.md file</small>
          </button>
          <button
            :class="['export-format', { 'export-format--selected': exportFormat === 'json' }]"
            @click="exportFormat = 'json'"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
              <polyline points="14 2 14 8 20 8"/>
              <path d="M8 13h2"/><path d="M8 17h2"/>
              <path d="M14 13h2"/><path d="M14 17h2"/>
            </svg>
            <span>JSON</span>
            <small>.json with metadata</small>
          </button>
        </div>
      </div>
      <template #footer>
        <Button variant="secondary" @click="showExportModal = false">Cancel</Button>
        <Button variant="primary" :loading="exporting" @click="handleExport">Download</Button>
      </template>
    </Modal>
  </div>
</template>

<style scoped>
.layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.layout__body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.layout__content {
  flex: 1;
  overflow-y: auto;
  background: var(--bg-primary);
}

.layout__content--with-panel {
  /* Content takes remaining space when panel is visible */
}

.loading,
.error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  height: 100%;
  color: var(--text-secondary);
}

.loading__spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.doc-view {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem;
}

.doc-view__toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1.5rem;
}

.doc-view__toolbar-left {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.doc-view__toolbar-right {
  display: flex;
  align-items: center;
}

.doc-view__back {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: none;
  border: none;
  border-radius: 6px;
  font-size: 0.875rem;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.doc-view__back:hover {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

.doc-view__panel-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  background: none;
  border: 1px solid var(--border);
  border-radius: 6px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.doc-view__panel-toggle:hover {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

.doc-view__panel-toggle.active {
  background: var(--accent);
  border-color: var(--accent);
  color: white;
}

.doc-view__saving {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.8125rem;
  color: var(--text-secondary);
}

.doc-view__saving-dot {
  width: 8px;
  height: 8px;
  background: var(--accent);
  border-radius: 50%;
  animation: pulse 1s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.4;
  }
}

.doc-view__saved {
  display: flex;
  align-items: center;
  gap: 0.375rem;
  font-size: 0.8125rem;
  color: #22c55e;
}

.doc-view__export {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.375rem 0.75rem;
  margin-left: 0.75rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 0.8125rem;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.doc-view__export:hover {
  border-color: var(--accent);
  color: var(--accent);
}

.doc-view__header {
  margin-bottom: 1rem;
}

.doc-view__title {
  width: 100%;
  padding: 0;
  background: none;
  border: none;
  font-size: 2rem;
  font-weight: 600;
  color: var(--text-primary);
  outline: none;
}

.doc-view__title::placeholder {
  color: var(--text-secondary);
}

.doc-view__tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border);
}

.doc-view__tag {
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.25rem 0.625rem;
  border: 1px solid;
  border-radius: 9999px;
  font-size: 0.8125rem;
  font-weight: 500;
}

.doc-view__tag-remove {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  padding: 0;
  background: none;
  border: none;
  border-radius: 50%;
  font-size: 1rem;
  line-height: 1;
  cursor: pointer;
  opacity: 0.7;
}

.doc-view__tag-remove:hover {
  opacity: 1;
}

.doc-view__add-tag {
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.25rem 0.625rem;
  background: var(--bg-secondary);
  border: 1px dashed var(--border);
  border-radius: 9999px;
  font-size: 0.8125rem;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.doc-view__add-tag:hover {
  border-color: var(--accent);
  color: var(--accent);
}

.doc-view__editor {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* Phase 3: Backlinks */
.doc-view__links {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  margin-bottom: 1.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border);
}

.doc-view__links-section {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.doc-view__links-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0;
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--text-primary);
}

.doc-view__links-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.doc-view__link-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s;
  text-align: left;
  max-width: 280px;
}

.doc-view__link-item:hover {
  border-color: var(--accent);
  background: var(--bg-tertiary);
}

.doc-view__link-item--broken {
  opacity: 0.6;
  cursor: not-allowed;
}

.doc-view__link-item--broken:hover {
  border-color: var(--border);
  background: var(--bg-secondary);
}

.doc-view__link-icon {
  font-size: 1rem;
  flex-shrink: 0;
}

.doc-view__link-info {
  display: flex;
  flex-direction: column;
  gap: 0.125rem;
  min-width: 0;
}

.doc-view__link-title {
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.doc-view__link-project {
  font-size: 0.75rem;
  color: var(--text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Export Modal Styles */
.export-formats {
  display: flex;
  gap: 0.75rem;
}

.export-format {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  padding: 1.25rem 1rem;
  background: var(--bg-secondary);
  border: 2px solid var(--border);
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.15s;
  color: var(--text-secondary);
}

.export-format:hover {
  border-color: var(--accent);
  color: var(--text-primary);
}

.export-format--selected {
  border-color: var(--accent);
  background: rgba(99, 102, 241, 0.08);
  color: var(--accent);
}

.export-format span {
  font-size: 0.9375rem;
  font-weight: 600;
  color: var(--text-primary);
}

.export-format small {
  font-size: 0.75rem;
  color: var(--text-secondary);
}

/* Form styles */
.form__field {
  margin-bottom: 1.25rem;
}

.form__field:last-child {
  margin-bottom: 0;
}

.form__label {
  display: block;
  margin-bottom: 0.5rem;
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--text-primary);
}

.form__input {
  width: 100%;
  padding: 0.75rem 1rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 0.9375rem;
  color: var(--text-primary);
  outline: none;
  transition: border-color 0.15s, box-shadow 0.15s;
  box-sizing: border-box;
}

.form__input::placeholder {
  color: var(--text-secondary);
}

.form__input:focus {
  border-color: var(--accent);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.color-picker {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.color-picker__option {
  width: 32px;
  height: 32px;
  border: 2px solid transparent;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.1s, border-color 0.1s;
}

.color-picker__option:hover {
  transform: scale(1.1);
}

.color-picker__option--selected {
  border-color: var(--text-primary);
}
</style>
