<template>
  <div
    :class="[
      'ivyforms-field',
      'ivyforms-field__gdpr',
      'ivyforms-field__gdpr_' + field.id,
      field.cssClasses,
    ]"
  >
    <IvyFormItem
      :label="field.hideLabel ? '' : field.label"
      :required="true"
      :error="error"
      :prop="field.type + '_' + field.fieldIndex"
      :show-info="!!field.description"
      :info-text="String(field.description || '')"
      :show-info-icon="false"
      label-position="top"
    >
      <IvyCheckbox
        :id="fieldID"
        :model-value="localValue"
        priority="secondary"
        type="checkmark"
        class="ivyforms-field__gdpr-checkbox ivyforms-flex ivyforms-align-items-center ivyforms-gap-8 ivyforms-font-16 ivyforms-font-weight-500"
        :aria-required="'true'"
        @change="onCheck"
      >
        <SafeHTML :html="agreementText || field.label" field-type="gdpr" />
      </IvyCheckbox>
    </IvyFormItem>
  </div>
</template>
<script setup lang="ts">
import { computed, inject } from 'vue'
import type { Field } from '@/types/field'
import IvyCheckbox from '@/views/_components/checkbox/IvyCheckbox.vue'
import IvyFormItem from '@/views/_components/form/IvyFormItem.vue'
import SafeHTML from '@/views/_components/SafeHTML.vue'
const props = defineProps<{
  modelValue: boolean | string | undefined
  field: Field
  disabled?: boolean
  error?: string
}>()
const emit = defineEmits(['update:modelValue'])
const fieldID = `field_${props.field.fieldIndex}`
const clearFieldError = inject<(fieldKey: string) => void>('clearFieldError', () => {})
const fieldKey = computed(() => props.field.type + '_' + props.field.fieldIndex)
const agreementText = computed(
  () => ((props.field as Record<string, unknown>).agreementText as string) || '',
)
const localValue = computed(() => {
  const v = props.modelValue
  if (typeof v === 'boolean') return v
  if (v === 'true' || v === '1') return true
  return false
})
function onCheck(val: boolean | string) {
  emit('update:modelValue', val)
  clearFieldError(fieldKey.value)
}
</script>

<style lang="scss" scoped>
.ivyforms-field__gdpr {
  :deep(a) {
    color: var(--map-accent-sky-blue-fill-1);
    text-decoration: underline;

    &:hover {
      color: #2563eb;
      text-decoration: underline;
    }
  }
}
</style>
