<template>
  <div class="contacts _container">
    <div
      :class="{'_loading': loading}"
      class="contacts__content"
    >
      <h1 class="contacts__title _title">{{ t('contacts.contact_us') }}</h1>
      <div class="contacts__wrapper">
        <i18n-t
          keypath="contacts.language_note"
          tag="p"
          scope="global"
          class="contacts__text"
        >
          <NuxtLink
            target="_blank"
            to="https://translate.google.com/"
          >{{ t('contacts.google_translate') }}</NuxtLink>
        </i18n-t>
        <i18n-t
          keypath="contacts.to_remove"
          tag="p"
          scope="global"
          class="contacts__text"
        >
          <NuxtLink
            :to="generateLink('/dmca')"
            target="_blank"
          >{{ t('contacts.dmca_request') }}</NuxtLink>
        </i18n-t>
        <UiSelect
          v-model="form.subject"
          :items="subjectItems"
          :placeholder="$t('contacts.choose_subject')"
          class="contacts__select"
          name="Subject"
          @change="onSubjectChange"
        />

        <div class="contacts__input-wrapper">
          <template
            v-for="(item, index) in getSubjectItems"
            :key="`contact-form-${index}`"
          >
            <UiInput
              v-if="['text', 'tel', 'textarea'].includes(item.type)"
              v-model="form.data[item.value] as string"
              :type="item.type as InputTypes"
              :label="t(`contacts.${item.label}`)"
              :class="{'--wide': item.wide}"
              :required="item?.required"
              :error="error[item.value]"
              @update:error="(val: boolean) => error[item.value] = val"
            />
            <UiRadio
              v-if="item.type === 'radio' "
              v-model="reasonValue"
              :value="item.value"
              :label="t(`contacts.${item.text}`)"
              :error="errorRadio"
              name="reason"
              @update:error="(val: boolean) => errorRadio = val"
            />
          </template>
          <UiInput
            v-model="form.message"
            :placeholder="placeholder"
            :label="t('contacts.message')"
            :error="error.message"
            type="textarea"
            class="--wide"
            required
            @update:error="(val: boolean) => error.message = val"
          />
          <UiInput
            v-if="form.subject !== String(ContactsSubjects.DMCA)"
            v-model="form.name"
            :label="t('contacts.name')"
          />
          <UiInput
            v-model="form.from"
            :label="t('contacts.email')"
            :error="error.from"
            type="email"
            autocomplete="email"
            required
            @update:error="(val: boolean) => error.from = val"
          />
          <template
            v-for="(item, index) in getSubjectItems"
            :key="`contact-form-${index}`"
          >
            <UiCheckbox
              v-if="item.type === 'checkbox'"
              v-model="form.data[item.value] as boolean"
              :error="error[item.value]"
              class="--wide"
              @update:error="(val: boolean) => error[item.value] = val"
            >{{ t(`contacts.${item.text}`) }}
            </UiCheckbox>
          </template>
        </div>
      </div>
      <div class="contacts__submit">
        <UiBtn
          :disabled="loading"
          wide
          size="l"
          theme="primary"
          @click="submit"
        >{{ t('contacts.send') }}
        </UiBtn>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { IContactsForm, ISelectItem, InputTypes } from '../types';
import { contactFormsScheme } from '../lib';
import { ContactsSubjects, validateEmail, validatePhone } from '../runtime';
import { ContactsApiService } from '../services/api/contacts.service';

const { initRecaptcha, getRecaptchaToken } = useRecaptcha();

const route = useRoute();

const form = ref<IContactsForm>({
  subject: route.query[ 'subject' ] as ContactsSubjects || ContactsSubjects.Feedback,
  message: '',
  name: '',
  from: '',
  token: '',
  data: {},
});

const reasonValue = ref('');
const errorRadio = ref(false);

const error = ref<Record<string, boolean>>({
  from: false,
  message: false,
  name: false,
});

const { t } = useI18n();
const { generateLink } = useGenerateLink();

const subjectItems: ISelectItem[] = [
  {
    title: t('contacts.feedback'),
    value: ContactsSubjects.Feedback,
  },
  {
    title: t('contacts.problems'),
    value: ContactsSubjects.Bugs,
  },
  {
    title: t('contacts.dmca'),
    value: ContactsSubjects.DMCA,
  },
  {
    title: t('contacts.report'),
    value: ContactsSubjects.Report,
  },
  {
    title: t('contacts.advertising'),
    value: ContactsSubjects.Advertising,
  },
];

const getSubjectItems = computed(() => contactFormsScheme.find((subItem) => subItem.subject === form.value.subject)?.items);

const requiredFields = computed(() => getSubjectItems.value?.filter(item => item.required).map(item => item.value));

const loading = ref(false);

const { show, showError } = useSnackbar();

// Загружаем reCAPTCHA при открытии формы (onMounted) — даёт Google время собрать данные о поведении
onMounted(async () => {
  try {
    await initRecaptcha();
    console.log('reCAPTCHA готов для этой формы');
  } catch (err) {
    console.error('Ошибка инициализации reCAPTCHA:', err);
  }
});

function resetForm() {
  Object.keys(form.value).forEach((key) => {
    if (key !== 'subject' && key !== 'data') {
      // @ts-expect-error — TS не знает, что значения всех полей строковые
      form.value[ key ] = '';
    }
    if (key === 'data') {
      form.value.data = {};
    }
  });
}

async function submit() {
  error.value.message = !form.value.message.trim();
  error.value.name = form.value.subject !== String(ContactsSubjects.DMCA) && !form.value.name.trim();
  error.value.from = !validateEmail(form.value.from);

  let valid = true;

  if (form.value.subject === ContactsSubjects.Report) {
    errorRadio.value = !reasonValue.value;
    if (errorRadio.value) {
      valid = false;
    }
  } else {
    errorRadio.value = false;
  }

  if (requiredFields.value && requiredFields.value.length > 0) {
    requiredFields.value.forEach(item => {
      if (item === 'phone') {
        error.value[ item ] = !validatePhone(form.value.data[ item ] as string);
      } else if (['confirmTrue', 'confirmOwner'].includes(item)) {
        error.value[ item ] = !form.value.data[ item ];
      } else {
        const value = form.value.data[ item ];
        error.value[ item ] = value === undefined || value === null || String(value).trim() === '';
      }

      if (error.value[ item ]) valid = false;
    });
  }

  const baseValid = !error.value.message && !error.value.from;
  if (!(baseValid && valid)) {
    const firstError = Object.entries(error.value).find(([, val]) => val)?.[0];
    showError(firstError ? `error_${firstError}` : 'fill_all_fields');
    return;
  }

  try {
    loading.value = true;

    form.value.token = await getRecaptchaToken('password_reset');

    if (form.value.subject === ContactsSubjects.Report) {
      form.value.data[ 'reportReason' ] = reasonValue.value;
    }

    await ContactsApiService.email(form.value);
    show('email_send');
    resetForm();
  } catch (error) {
    console.log('error send email', error);
    showError('email_error');
  } finally {
    loading.value = false;
  }
}

const router = useRouter();

function onSubjectChange(event: ContactsSubjects) {
  Object.keys(error.value).forEach(key => {
    error.value[ key ] = false;
  });
  resetForm();
  router.push({
    query: {
      subject: event
    }
  });
}

watch(() => route.query, (value) => {
  if (value) {
    form.value.subject = value.subject as ContactsSubjects;
  }
});

const placeholder = computed(() => t('contacts.type_here'));

const pagePureName = useGetPureRouteName();
const { meta } = useMeta({ t, pageKey: pagePureName, brandName: useAppConfig().brandName });

watchEffect(() => {
  useHead(meta.value);
});
</script>

<style lang="scss">
.contacts {
  padding-block: 32px;
}

.contacts__content {
  @include font-sm;

  display: grid;
  margin: 0 auto;
  padding: 24px;
  border-radius: $radius-2xl;
  color: $contacts-text;
  border: 1px solid $contacts-border;
  background-color: $contacts-wrapper-bg;

  @include from-br(sm) {
    padding: 32px;
    max-width: 734px;
    width: 734px;
  }
}

.contacts__wrapper {
  display: grid;
}

.contacts__title {
  margin-bottom: 16px;
  color: $contacts-title;
}

.contacts__text {
  line-height: 22.75px;
}

.contacts__text:first-child {
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid $contacts-text-border;
}

.contacts__text a {
  color: $contacts-link;

  @include hover(color) {
    color: $contacts-link--hover;
  }
}


.contacts__select {
  margin-bottom: 24px;
}

.contacts__text:last-of-type {
  margin-bottom: 32px;
}

.contacts__input-wrapper {
  display: grid;
  gap: 24px;

  @include from-br(sm) {
    grid-template-columns: 1fr 1fr;
    justify-items: start;
  }
}

.contacts__input-wrapper .--wide {
  @include from-br(sm) {
    grid-column: 1/3;
  }
}

.contacts__submit {
  padding-top: 24px;
}
</style>
