<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import type { SpecSection, StatusState } from '@/api/types'
import AcceptanceCriteria from './AcceptanceCriteria.vue'
import SectionAiActions from './SectionAiActions.vue'
import { useClickOutside } from '@/composables/useClickOutside'
import { statusClass } from '@/utils/status'

const props = defineProps<{
  modelValue: SpecSection
  index: number
  owner?: string
  repo?: string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: SpecSection]
  remove: []
  duplicate: []
}>()

const statusOptions = ['draft', 'todo', 'in_progress', 'done', 'blocked', 'deprecated']
const collapsed = ref(false)
const showOverflowMenu = ref(false)
const showStatusDropdown = ref(false)
const isFocused = ref(false)
const textareaRef = ref<HTMLTextAreaElement | null>(null)
const statusDropdownRef = ref<HTMLElement | null>(null)
const overflowMenuRef = ref<HTMLElement | null>(null)

useClickOutside(statusDropdownRef, () => { showStatusDropdown.value = false })
useClickOutside(overflowMenuRef, () => { showOverflowMenu.value = false })

function update(field: string, value: unknown) {
  emit('update:modelValue', { ...props.modelValue, [field]: value })
}

function updateStatus(state: string) {
  const current = typeof props.modelValue.status === 'string'
    ? { state: props.modelValue.status as StatusState }
    : props.modelValue.status
  emit('update:modelValue', { ...props.modelValue, status: { ...current, state: state as StatusState } })
  showStatusDropdown.value = false
}

function getStatusState(): string {
  return typeof props.modelValue.status === 'string'
    ? props.modelValue.status
    : props.modelValue.status.state
}

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

const acProgress = computed(() => {
  const total = props.modelValue.acceptance_criteria.length
  const done = props.modelValue.acceptance_criteria.filter(ac => ac.checked).length
  const pct = total > 0 ? Math.round((done / total) * 100) : 0
  return { done, total, pct }
})

function autoResize(el: HTMLTextAreaElement) {
  el.style.height = 'auto'
  el.style.height = Math.min(el.scrollHeight, window.innerHeight * 0.5) + 'px'
}

function handleTextareaInput(e: Event) {
  const el = e.target as HTMLTextAreaElement
  update('prose_content', el.value)
  autoResize(el)
}

const textareaMinHeight = computed(() => {
  const content = props.modelValue.prose_content || props.modelValue.content || ''
  return content.includes('\n') || content.length > 80 ? '6rem' : '3rem'
})

function handleFocusIn() { isFocused.value = true }
function handleFocusOut(e: FocusEvent) {
  const root = (e.currentTarget as HTMLElement)
  if (!root.contains(e.relatedTarget as Node)) {
    isFocused.value = false
  }
}

onMounted(() => {
  nextTick(() => {
    if (textareaRef.value) {
      autoResize(textareaRef.value)
    }
  })
})
</script>

<template>
  <div
    class="border-l-3 border-accent-500 border border-l-[3px] border-border-light/60 dark:border-slate-800 rounded-lg bg-surface-light dark:bg-surface-alt transition-all"
    :class="{ 'section-card-focused border-accent-200 dark:border-accent-800': isFocused }"
    @focusin="handleFocusIn"
    @focusout="handleFocusOut"
  >
    <!-- Section header — Row 1 (always visible) -->
    <div class="flex items-center gap-2 px-4 py-3">
      <!-- Drag handle — always visible -->
      <span class="cursor-grab text-slate-300 dark:text-slate-600 hover:text-slate-500 dark:hover:text-slate-400 drag-handle transition-colors">
        <svg class="w-4 h-4" viewBox="0 0 16 16" fill="currentColor">
          <circle cx="5" cy="2.5" r="1.2" />
          <circle cx="11" cy="2.5" r="1.2" />
          <circle cx="5" cy="6.5" r="1.2" />
          <circle cx="11" cy="6.5" r="1.2" />
          <circle cx="5" cy="10.5" r="1.2" />
          <circle cx="11" cy="10.5" r="1.2" />
          <circle cx="5" cy="14.5" r="1.2" />
          <circle cx="11" cy="14.5" r="1.2" />
        </svg>
      </span>

      <!-- Collapse chevron -->
      <button
        class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors"
        @click="collapsed = !collapsed"
      >
        <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 + title -->
      <span class="text-sm font-semibold font-display text-slate-400 dark:text-slate-500 select-none">
        {{ props.modelValue.section_number }}.
      </span>
      <input
        :value="modelValue.title"
        class="flex-1 text-lg font-semibold font-display border-0 border-b-2 border-transparent focus:border-accent-500 bg-transparent focus:outline-none text-slate-800 dark:text-slate-200 transition-colors"
        placeholder="Section title"
        @input="update('title', ($event.target as HTMLInputElement).value)"
      />

      <!-- Collapsed summary: status + AC count -->
      <template v-if="collapsed">
        <span class="status-badge text-[10px]" :class="statusClass(getStatusState())">
          {{ getStatusState().replace('_', ' ') }}
        </span>
        <span v-if="acSummary" class="text-[11px] text-slate-400 dark:text-slate-500">
          {{ acSummary }}
        </span>
      </template>

      <!-- Overflow menu -->
      <div ref="overflowMenuRef" class="relative">
        <button
          class="text-slate-300 hover:text-slate-500 dark:text-slate-600 dark:hover:text-slate-400 transition-colors p-1"
          @click="showOverflowMenu = !showOverflowMenu"
        >
          <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" d="M12 6.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 12.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 18.75a.75.75 0 110-1.5.75.75 0 010 1.5z" />
          </svg>
        </button>
        <div v-if="showOverflowMenu" class="absolute right-0 z-20 mt-1 bg-surface-light dark:bg-surface-elevated border border-border-light dark:border-slate-700 rounded-lg shadow-lg py-1 min-w-[150px]">
          <button
            class="w-full text-left px-3 py-1.5 text-xs hover:bg-surface-light-alt dark:hover:bg-surface-alt flex items-center gap-2"
            @click="emit('duplicate'); showOverflowMenu = false"
          >
            <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 01-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 011.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 00-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 01-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 00-3.375-3.375h-1.5a1.125 1.125 0 01-1.125-1.125v-1.5a3.375 3.375 0 00-3.375-3.375H9.75" />
            </svg>
            Duplicate section
          </button>
          <button
            class="w-full text-left px-3 py-1.5 text-xs hover:bg-surface-light-alt dark:hover:bg-surface-alt flex items-center gap-2"
            @click="collapsed = true; showOverflowMenu = false"
          >
            <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15" />
            </svg>
            Collapse
          </button>
          <div class="border-t border-border-light/60 dark:border-slate-700 my-1"></div>
          <button
            class="w-full text-left px-3 py-1.5 text-xs text-red-500 hover:bg-red-50 dark:hover:bg-red-900/10 flex items-center gap-2"
            @click="emit('remove'); showOverflowMenu = false"
          >
            <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
            </svg>
            Remove section
          </button>
        </div>
      </div>
    </div>

    <!-- Section header — Row 2 (visible when expanded) -->
    <div v-if="!collapsed" class="flex items-center gap-2 px-4 pb-2">
      <!-- Status badge dropdown -->
      <div ref="statusDropdownRef" class="relative">
        <button
          class="status-badge cursor-pointer hover:ring-2 hover:ring-accent-500/30 transition-shadow text-[11px]"
          :class="statusClass(getStatusState())"
          @click="showStatusDropdown = !showStatusDropdown"
        >
          {{ getStatusState().replace('_', ' ') }}
        </button>
        <div v-if="showStatusDropdown" class="absolute left-0 z-20 mt-1 bg-surface-light dark:bg-surface-elevated border border-border-light dark:border-slate-700 rounded-lg shadow-lg py-1 min-w-[130px]">
          <button
            v-for="s in statusOptions"
            :key="s"
            class="w-full text-left px-3 py-1.5 text-xs hover:bg-surface-light-alt dark:hover:bg-surface-alt"
            @click="updateStatus(s)"
          >
            <span class="status-badge text-[10px]" :class="statusClass(s)">{{ s.replace('_', ' ') }}</span>
          </button>
        </div>
      </div>

      <!-- AC progress bar -->
      <div v-if="acProgress.total > 0" class="flex-1 flex items-center gap-2">
        <div class="flex-1 h-1.5 rounded-full bg-surface-light-elevated dark:bg-slate-700 overflow-hidden">
          <div
            class="h-full rounded-full transition-all duration-300"
            :class="acProgress.pct === 100 ? 'bg-emerald-500' : 'bg-brand-500'"
            :style="{ width: acProgress.pct + '%' }"
          ></div>
        </div>
        <span class="text-[10px] text-slate-400 tabular-nums">{{ acProgress.done }}/{{ acProgress.total }}</span>
      </div>
      <div v-else class="flex-1"></div>

      <!-- AI actions -->
      <SectionAiActions
        v-if="props.owner && props.repo"
        :section="modelValue"
        :owner="props.owner"
        :repo="props.repo"
        @update-prose="update('prose_content', $event)"
        @update-acs="update('acceptance_criteria', $event)"
      />
    </div>

    <!-- Collapsible body -->
    <Transition name="collapse">
      <div v-if="!collapsed" class="px-4 pb-4">
        <!-- Prose content: auto-resizing textarea -->
        <textarea
          ref="textareaRef"
          :value="modelValue.prose_content || modelValue.content"
          class="w-full border-0 border-b border-transparent focus:border-gray-200 dark:focus:border-slate-700 bg-transparent px-0 py-2 text-sm resize-none focus:outline-none text-slate-700 dark:text-slate-300 leading-relaxed"
          :style="{ minHeight: textareaMinHeight }"
          placeholder="Section content..."
          @input="handleTextareaInput"
        ></textarea>

        <!-- Acceptance Criteria -->
        <AcceptanceCriteria
          :model-value="modelValue.acceptance_criteria"
          @update:model-value="update('acceptance_criteria', $event)"
        />
      </div>
    </Transition>
  </div>
</template>
