<script setup lang="ts">
import { computed, type Slot } from 'vue'
import { useAttrsWithDefaults } from '../../../composables/useAttrsWithDefaults'
import { useHasSlot } from '../../../composables/useHasSlots'
import type { FdsContentBlockProps } from './types'

const props = withDefaults(defineProps<FdsContentBlockProps>(), {
  borderLeft: undefined,
  tight: false,
  heading: undefined,
  dataTestid: undefined,
})

const { id } = useAttrsWithDefaults(props)
const hasSlot = useHasSlot()

const contentClasses = computed(() => [
  'rounded-md p-4 bg-white mb-4',
  props.tight && 'pb-2',
  props.tight && 'p-4!',
  props.borderLeft && 'border-l-4',
  hasSlot.value ? 'pb-6' : 'pb-4',
])

const headerClasses = computed(() => ['m-0 text-lg font-bold tracking-wide', !hasSlot.value && 'mb-0!'])

const borderLeftStyle = computed(() => {
  if (!props.borderLeft) return {}

  const colorMap: Record<string, string> = {
    green: 'var(--color-green-600)',
    yellow: 'var(--color-yellow-400)',
    red: 'var(--color-red-500)',
  }

  return { 'border-left-color': colorMap[props.borderLeft] || props.borderLeft }
})

const autoId = `fds-content-block-${Math.random().toString(36).slice(2, 9)}`
const contentBlockId = computed(() => id.value ?? autoId)

const rootAttrs = computed(() => {
  const attrs: Record<string, string> = {}
  if (props.dataTestid) {
    attrs['data-testid'] = props.dataTestid
  }
  return attrs
})

defineSlots<{
  default?: Slot
  headerInfo?: Slot
}>()
</script>

<template>
  <div :id="contentBlockId" :class="contentClasses" :style="borderLeftStyle" v-bind="rootAttrs">
    <header v-if="heading" class="flex items-start justify-between gap-4 mb-4">
      <div class="flex items-center gap-3">
        <h3 :class="headerClasses">{{ heading }}</h3>
      </div>
      <div class="flex items-start gap-3 leading-8">
        <slot name="headerInfo" />
      </div>
    </header>
    <div class="mb-0-last-child">
      <slot />
    </div>
  </div>
</template>
