<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.email"
            v-model:error="validationErrors.email"
            type="email"
            autofocus
            color="violet-normal"
            :rules="[inputRules.required, inputRules.email]"
            :label="$t('common.terms.email')"
            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-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 Logo from "src/assets/logo_serprati.svg";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultPasswordInput from "src/components/defaults/DefaultPasswordInput.vue";

const PRIVACY_POLICY_URL = "https://politicas.softpar.inf.br/politicas/politicaSerpRatiAssociado.html";
const openUrl = (url) => window.open(url, "_blank");

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({
  email: null,
  password: process.env.PASSWORD ?? null,
});

const checkbox = ref(false);

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

onBeforeMount(() => {
  const email_storage = $q.cookies.get("email");
  if (email_storage) {
    checkbox.value = true;
    form.value.email = email_storage;
  }
});
</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>
