<script setup lang="ts">
import { ref, computed, watchEffect } from 'vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import type { SpecSection } from '@/api/types'
import { statusClass } from '@/utils/status'
import SpecAcceptanceCriteria from './SpecAcceptanceCriteria.vue'

const props = defineProps<{
  section: SpecSection
  repoOwner?: string
  repoName?: string
  depth?: number
  allExpanded?: boolean | null
}>()

const emit = defineEmits<{ 'reset-global': [] }>()

const sectionStatus = computed(() =>
  typeof props.section.status === 'string'
    ? props.section.status
    : props.section.status.state
)

const localCollapsed = ref(sectionStatus.value === 'done')

// Re-sync localCollapsed when status changes
watchEffect(() => {
  localCollapsed.value = sectionStatus.value === 'done'
})

const collapsed = computed(() => {
  if (props.allExpanded === true) return false
  if (props.allExpanded === false) return true
  return localCollapsed.value
})

function toggleSection() {
  // If global expand/collapse is active, reset it so individual clicks take effect
  if (props.allExpanded !== null) {
    // Set local state to the opposite of current visual state before resetting global
    localCollapsed.value = !collapsed.value
    emit('reset-global')
    return
  }
  localCollapsed.value = !localCollapsed.value
}

const acSummary = computed(() => {
  const total = props.section.acceptance_criteria.length
  const done = props.section.acceptance_criteria.filter(ac => ac.checked).length
  return total > 0 ? `${done}/${total} ACs` : ''
})

const renderedContent = computed(() => {
  const content = props.section.prose_content || props.section.content || ''
  if (!content.trim()) return ''
  const raw = marked.parse(content, { async: false }) as string
  return DOMPurify.sanitize(raw)
})

const ticketBadgeClass: Record<string, string> = {
  jira: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  linear: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
  github: 'bg-gray-100 text-gray-600 dark:bg-gray-800/50 dark:text-gray-400',
}

function ticketUrl(link: { system: string; ticket_id: string }): string | null {
  if (link.system === 'github' && props.repoOwner && props.repoName) {
    return `https://github.com/${props.repoOwner}/${props.repoName}/issues/${link.ticket_id.replace('#', '')}`
  }
  // Jira/Linear URLs require instance-specific base URLs we don't have;
  // render as non-link badge rather than constructing broken URLs
  return null
}

const currentDepth = computed(() => props.depth ?? 0)

function hasDelta(section: SpecSection): string | null {
  const content = section.prose_content || section.content || ''
  if (content.includes('<!-- delta:added -->')) return 'added'
  if (content.includes('<!-- delta:modified -->')) return 'modified'
  if (content.includes('<!-- delta:removed -->')) return 'removed'
  return null
}

const deltaType = computed(() => hasDelta(props.section))
const deltaClass: Record<string, string> = {
  added: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  modified: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  removed: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
}
</script>

<template>
  <div
    class="border-l-[3px] border-accent-500 border border-border-light/60 dark:border-slate-800 rounded-lg bg-surface-light dark:bg-surface-alt transition-all"
    :class="{ 'ml-4': currentDepth > 0 }"
  >
    <!-- Section header -->
    <div
      role="button"
      tabindex="0"
      class="flex items-center gap-2 px-4 py-3 cursor-pointer select-none"
      @click="toggleSection"
      @keydown.enter.prevent="toggleSection"
      @keydown.space.prevent="toggleSection"
    >
      <!-- Collapse chevron -->
      <button class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors">
        <svg
          class="w-4 h-4 transition-transform duration-200"
          :class="collapsed ? '-rotate-90' : ''"
          fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"
        >
          <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
        </svg>
      </button>

      <!-- Section number -->
      <span class="text-sm font-semibold font-display text-slate-400 dark:text-slate-500 select-none">
        {{ section.section_number }}.
      </span>

      <!-- Section title -->
      <span class="flex-1 text-lg font-semibold font-display text-slate-800 dark:text-slate-200">
        {{ section.title }}
      </span>

      <!-- Status badge -->
      <span class="status-badge text-[10px]" :class="statusClass(sectionStatus)">
        {{ sectionStatus.replace('_', ' ') }}
      </span>

      <!-- AC summary -->
      <span v-if="acSummary" class="text-[11px] text-slate-400 dark:text-slate-500 tabular-nums">
        {{ acSummary }}
      </span>

      <!-- Delta badge -->
      <span
        v-if="deltaType"
        class="text-[10px] px-1.5 py-0.5 rounded font-medium"
        :class="deltaClass[deltaType]"
      >{{ deltaType }}</span>

      <!-- Ticket link pill -->
      <a
        v-if="section.ticket_link && ticketUrl(section.ticket_link)"
        :href="ticketUrl(section.ticket_link)!"
        target="_blank"
        rel="noopener"
        class="text-[10px] px-1.5 py-0.5 rounded font-medium inline-flex items-center gap-1"
        :class="ticketBadgeClass[section.ticket_link.system] || ticketBadgeClass.github"
        @click.stop
      >
        {{ section.ticket_link.system === 'github' ? '#' : '' }}{{ section.ticket_link.ticket_id }}
      </a>
      <span
        v-else-if="section.ticket_link"
        class="text-[10px] px-1.5 py-0.5 rounded font-medium inline-flex items-center gap-1"
        :class="ticketBadgeClass[section.ticket_link.system] || ticketBadgeClass.github"
      >
        {{ section.ticket_link.ticket_id }}
      </span>
    </div>

    <!-- Collapsible body -->
    <Transition name="collapse">
      <div v-if="!collapsed" class="px-4 pb-4">
        <!-- Prose content -->
        <!-- eslint-disable-next-line vue/no-v-html -->
        <div
          v-if="renderedContent"
          class="spec-prose text-sm"
          v-html="renderedContent"
        ></div>

        <!-- Acceptance Criteria -->
        <SpecAcceptanceCriteria :criteria="section.acceptance_criteria" />

        <!-- Recursive children -->
        <div v-if="section.children && section.children.length > 0" class="mt-4 space-y-3">
          <SpecSectionCard
            v-for="child in section.children"
            :key="child.id"
            :section="child"
            :repo-owner="repoOwner"
            :repo-name="repoName"
            :depth="currentDepth + 1"
            :all-expanded="allExpanded"
            @reset-global="emit('reset-global')"
          />
        </div>
      </div>
    </Transition>
  </div>
</template>
