<script setup lang="ts">
/**
 * Экран регистрации (RegisterView).
 *
 * Источник дизайна: liderra_v8_handoff/concepts/v8_login.html секция #form-register.
 * Источник логики: ТЗ v8.5 §1.5/§4.1 — два обязательных click-wrap'а
 * (оферта + согласие на ПДн). 3-й «маркетинговый» click-wrap из handoff
 * НЕ реализован (handoff противоречит ТЗ — расхождение #2 из реестра v1.13).
 *
 * MVP: фронт-форма без backend submit. POST /register будет в отдельном коммите.
 */
import { extractValidationErrors } from '../../api/client';
import { useAuthStore } from '../../stores/auth';
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';

const email = ref('');
const password = ref('');
const showPassword = ref(false);
const acceptOffer = ref(false);
const acceptPdn = ref(false);
const errors = ref<Record<string, string[]>>({});

const auth = useAuthStore();
const router = useRouter();

// Простая оценка силы пароля 0..4 для индикатора. На backend будет zxcvbn.
const passwordStrength = computed(() => {
    const v = password.value;
    if (!v) return 0;
    let score = 0;
    if (v.length >= 8) score++;
    if (/[A-ZА-Я]/.test(v) && /[a-zа-я]/.test(v)) score++;
    if (/\d/.test(v)) score++;
    if (/[^A-Za-zА-Яа-я0-9]/.test(v)) score++;
    return score;
});

const strengthLabel = computed(() => {
    const map = ['—', 'Слабый', 'Средний', 'Хороший', 'Надёжный'];
    return map[passwordStrength.value];
});

const strengthColor = computed(() => {
    const map = ['', 'error', 'warning', 'info', 'success'];
    return map[passwordStrength.value];
});

const canSubmit = computed(
    () => email.value.length > 0 && password.value.length >= 8 && acceptOffer.value && acceptPdn.value,
);

async function handleSubmit() {
    errors.value = {};
    try {
        const response = await auth.register({
            email: email.value,
            password: password.value,
            accept_offer: acceptOffer.value,
            accept_pdn: acceptPdn.value,
        });
        await router.push(response.requires_2fa ? '/2fa' : '/dashboard');
    } catch (error: unknown) {
        const validationErrors = extractValidationErrors(error);
        if (validationErrors) {
            errors.value = validationErrors;
        } else {
            errors.value = { email: ['Произошла ошибка. Попробуйте позже.'] };
        }
    }
}
</script>

<template>
    <v-card variant="flat" :max-width="380" width="100%" color="transparent" class="register-card">
        <header class="register-header">
            <h1 class="text-h5 mb-1">Создать аккаунт</h1>
            <p class="text-body-2 text-medium-emphasis ma-0">
                Уже есть?
                <RouterLink to="/login" class="text-primary"> Войдите </RouterLink>
            </p>
        </header>

        <v-form class="register-form" @submit.prevent="handleSubmit">
            <v-text-field
                v-model="email"
                label="Рабочий email"
                type="email"
                autocomplete="email"
                placeholder="manager@yourcompany.ru"
                variant="outlined"
                density="comfortable"
                required
                :error-messages="errors.email"
            />

            <v-text-field
                v-model="password"
                label="Пароль"
                :type="showPassword ? 'text' : 'password'"
                autocomplete="new-password"
                placeholder="Минимум 8 символов"
                variant="outlined"
                density="comfortable"
                :append-inner-icon="showPassword ? 'mdi-eye-off' : 'mdi-eye'"
                required
                :error-messages="errors.password"
                @click:append-inner="showPassword = !showPassword"
            />

            <div v-if="password" class="strength-block mb-2">
                <v-progress-linear
                    :model-value="(passwordStrength / 4) * 100"
                    :color="strengthColor"
                    height="4"
                    rounded
                />
                <span class="text-caption text-medium-emphasis"> {{ strengthLabel }} </span>
            </div>

            <div class="checks">
                <v-checkbox v-model="acceptOffer" density="compact" hide-details color="primary">
                    <template #label>
                        <span class="text-body-2">
                            Принимаю
                            <a href="/legal/offer" class="text-primary" target="_blank" rel="noopener">оферту</a>
                        </span>
                    </template>
                </v-checkbox>
                <v-checkbox v-model="acceptPdn" density="compact" hide-details color="primary">
                    <template #label>
                        <span class="text-body-2">
                            Согласен с
                            <a href="/legal/privacy" class="text-primary" target="_blank" rel="noopener">
                                политикой обработки персональных данных
                            </a>
                        </span>
                    </template>
                </v-checkbox>
            </div>

            <v-btn
                type="submit"
                color="primary"
                block
                size="large"
                variant="flat"
                :disabled="!canSubmit"
                :loading="auth.loading"
            >
                Создать аккаунт
            </v-btn>
        </v-form>
    </v-card>
</template>

<style scoped>
.register-card {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.register-header h1 {
    font-variation-settings: 'opsz' 26;
    letter-spacing: -0.018em;
}

.register-form {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.strength-block {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.checks {
    display: flex;
    flex-direction: column;
    gap: 4px;
    margin-bottom: 8px;
}
</style>
