<template>
  <q-page class="login-page column items-center justify-center">
    <div class="login-overlay" />

    <div class="login-card column items-center">
      <div class="column items-center fields-card">
        <q-img :src="Logo" class="login-logo q-mb-xl" />

        <q-form
          ref="formRef"
          class="full-width"
          autocorrect="off"
          autocapitalize="off"
          autocomplete="off"
          spellcheck="false"
          @submit="onSubmit"
        >
          <DefaultInput
            v-model="form.identifier"
            v-model:error="validationErrors.identifier"
            autofocus
            color="violet-normal"
            :rules="[inputRules.required]"
            :label="$t('auth.email_or_badge')"
            lazy-rules
          >
            <template #append>
              <q-icon name="mdi-account-outline" color="grey-5" />
            </template>
          </DefaultInput>

          <DefaultPasswordInput
            v-model="form.password"
            v-model:error="validationErrors.password"
            :rules="[inputRules.required, inputRules.min(6)]"
            lazy-rules
            :label="$t('common.terms.password')"
          />

          <q-checkbox
            v-model="checkbox"
            size="xs"
            :label="$t('auth.remember_email') || 'Lembrar e-mail'"
            class="q-mb-md"
            style="margin-left: -6px"
          />

          <q-btn
            class="full-width q-mt-sm login-btn"
            color="violet-normal"
            :label="$t('auth.sign-in')"
            type="submit"
            unelevated
            :loading
          >
            <template #loading>
              <q-spinner />
            </template>
          </q-btn>
          <q-btn
            class="full-width q-mt-sm login-btn"
            color="violet-normal"
            :label="$t('auth.first_access.button')"
            outline
            @click="router.push({ name: 'FirstAccessPage' })"
          />
        </q-form>

        <a
          href="#"
          class="forgot-link q-mt-md"
          @click.prevent="router.push({ name: 'ForgotPasswordPage' })"
        >
          {{ $t("auth.forgot_password") }}
        </a>

        <q-btn
          flat
          no-caps
          dense
          class="q-mt-lg privacy-link"
          :label="$t('common.terms.privacy_policy')"
          @click="openUrl(PRIVACY_POLICY_URL)"
        />
      </div>
    </div>
  </q-page>
</template>

<script setup>
import { ref, onBeforeMount, useTemplateRef } from "vue";
import { useQuasar } from "quasar";
import { useAuth } from "src/composables/useAuth";
import { useRouter } from "vue-router";
import { useInputRules } from "src/composables/useInputRules";
import { useSubmitHandler } from "src/composables/useSubmitHandler";
import { PRIVACY_POLICY_URL, openUrl } from "src/helpers/links";

import Logo from "src/assets/logo_serprati.svg";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";

const router = useRouter();
const $q = useQuasar();
const { inputRules } = useInputRules();
const { login } = useAuth();

const formRef = useTemplateRef("formRef");

const {
  loading,
  validationErrors,
  execute: submitForm,
} = useSubmitHandler({
  onSuccess: () => router.push({ name: "CarteirinhaPage" }),
  formRef,
});

const form = ref({
  identifier: null,
  password: process.env.PASSWORD ?? null,
});

const checkbox = ref(false);

const onSubmit = async () => {
  await submitForm(() => login(form.value.identifier, form.value.password));
  const saved = $q.cookies.get("login_identifier");
  if (saved && !checkbox.value) {
    $q.cookies.remove("login_identifier");
  }
  if (checkbox.value) {
    $q.cookies.set("login_identifier", form.value.identifier, {
      path: "/",
      sameSite: "Lax",
    });
  }
};

onBeforeMount(() => {
  const saved = $q.cookies.get("login_identifier");
  if (saved) {
    checkbox.value = true;
    form.value.identifier = saved;
  }
});
</script>

<style lang="scss" scoped>
@use "sass:map";
@use "src/css/quasar.variables.scss" as *;

.login-page {
  min-height: 100dvh;
  background-image: url("src/assets/pessoas_fundo.jpg");
  background-size: cover;
  background-position: center;
  position: relative;
}

.login-overlay {
  position: absolute;
  inset: 0;
  background: rgba(74, 20, 140, 0.48);
  z-index: 0;
}

.login-card {
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: calc(100% - 32px);
  min-height: calc(100dvh - 32px);
  background: rgba(255, 255, 255, 0.747);
  border-radius: 16px;
  box-shadow: 0 4px 32px rgba(0, 0, 0, 0.15);
  padding-top: env(safe-area-inset-top);
  padding-bottom: env(safe-area-inset-bottom);
}

.fields-card {
  width: 100%;
  max-width: 400px;
  padding: 32px;
  border-radius: 12px;

  // Texto digitado visível em todos os estados
  :deep(.q-field__native),
  :deep(.q-field__input) {
    color: $color-text !important;
  }

  // Fundo opaco branco (evita herdar transparência do card)
  :deep(.q-field__control) {
    background: $surface !important;
  }

  // Label padrão (sem foco)
  :deep(.q-field__label) {
    color: $color-text-2;
  }

  // Label quando focado
  :deep(.q-field--focused .q-field__label) {
    color: $violet-normal;
  }

  // Label quando tem conteúdo mas sem foco (blur com valor)
  :deep(.q-field--float:not(.q-field--focused) .q-field__label) {
    color: $neutral-dark-active;
  }
}

.login-logo {
  width: 280px;
  max-width: 100%;
}

.login-btn {
  height: 44px;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.forgot-link {
  color: map.get($colors, "violet-normal");
  font-size: 13px;
  text-decoration: none;
  cursor: pointer;

  &:hover {
    color: map.get($colors, "violet-normal-hover");
    text-decoration: underline;
  }
}

.privacy-link {
  font-size: 12px;
  color: rgba(74, 20, 140, 0.65);
  text-decoration: underline;
}
</style>
