<template>
  <UForm
    :name="name"
    :schema="schema"
    :class="ui.root({ class: [props.ui?.root, props.class] })"
    :validate-on="['input']"
    nested
  >
    <UFormField
      name="title"
      label="Заголовок"
      :hint="`${state.title.length}/60`"
      :ui="{ hint: 'text-xs' }"
    >
      <UInput
        :model-value="state.title"
        placeholder="Введите заголовок..."
        class="w-full"
        @update:model-value="state = { ...state, title: $event }"
      />

      <template #help>
        <p class="text-xs mb-2">
          Рекомендуемая длина: 45-60 символов
        </p>
        <UProgress
          :model-value="title.progress"
          :color="title.color"
          size="sm"
        />
      </template>
    </UFormField>

    <UFormField
      name="description"
      label="Описание"
      :hint="`${state.description.length}/160`"
      :ui="{ hint: 'text-xs' }"
    >
      <UTextarea
        :model-value="state.description"
        placeholder="Введите описание..."
        class="w-full"
        autoresize
        @update:model-value="state = { ...state, description: $event }"
      />

      <template #help>
        <p class="text-xs mb-2">
          Рекомендуемая длина: 130-160 символов
        </p>
        <UProgress
          :model-value="description.progress"
          :color="description.color"
          size="sm"
        />
      </template>
    </UFormField>
  </UForm>
</template>

<script>
import theme from "#build/cms/form-seo";
import { useAppConfig } from "#imports";
import { computed } from "vue";
import { z } from "zod";
import { useSeoStats } from "../composables/useSeoStats";
import { tv } from "../tv";
</script>

<script setup>
const props = defineProps({
  class: { type: null, required: false },
  name: { type: String, required: false, default: "seo" },
  ui: { type: null, required: false }
});
const model = defineModel({ type: [Object, null] });
const state = computed({
  get: () => {
    return model.value ?? {
      title: "",
      description: ""
    };
  },
  set: (value) => {
    const isEmpty = Object.values(value).every((value2) => !value2);
    model.value = isEmpty ? null : value;
  }
});
const appConfig = useAppConfig();
const schema = z.object({
  title: z.string(),
  description: z.string()
}).nullable();
const { title, description } = useSeoStats(() => state.value);
const ui = computed(() => tv({ extend: tv(theme), ...appConfig.cms?.formSeo || {} })());
</script>
