<template>
  <q-form @submit="save" class="q-mt-lg" ref="myForm">
    <!-- SEÇÃO 1: LOCALIZAÇÃO -->
    <div class="form-section q-mb-sm">
      <div class="section-header">
        <div class="section-number">1</div>
        <div class="section-title">Onde devemos coletar sua carga?</div>
      </div>
      <div class="q-pa-md">
        <div class="row q-col-gutter-md items-start">
          <div class="col-xs-12 col-md-4">
            <q-option-group
              type="radio"
              v-model="selectedCompanyFromUserId"
              :options="userCompanyOptions"
              :disable="isDataLocked"
            />
          </div>
          <div class="col-xs-12 col-md-8">
            <div
              v-if="!isOtherLocation"
              class="selection-inline"
            >
              <div class="selection-inline-title">
                Nome: {{ selectedUserCompanyName || "Empresa selecionada" }}
              </div>
              <div class="selection-inline-text" v-if="selectedUserCompanyAlias">
                Alias: {{ selectedUserCompanyAlias }}
              </div>
              <div class="selection-inline-text" v-if="selectedUserCompanyCnpj">
                CNPJ: {{ selectedUserCompanyCnpj }}
              </div>
            </div>
            <div
              v-else
              class="selection-inline is-other"
            >
              <div class="selection-inline-title">Outro local</div>
              <div class="selection-inline-text">
                Atenção: Os dados preenchidos nas próximas etapas serão utilizados pela Transportadora durante o seu transporte.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- SEÇÃO 2: DADOS DO RESPONSÁVEL (OUTRO LOCAL) -->
    <div v-if="item.whereRetrieve == 'OP'" class="form-section q-mb-sm">
      <div class="section-header">
        <div class="section-number">2</div>
        <div class="section-title">Dados do responsável pela coleta</div>
      </div>
      <div class="q-pa-md">
        <div class="row q-col-gutter-md items-start q-mb-md">
          <div class="col-xs-12 col-md-4">
            <q-option-group
              type="radio"
              v-model="item.personType"
              :options="personTypeOptions"
              
            />
          </div>
          <div class="col-xs-12 col-md-8">
            <div class="selection-inline is-other">
              <div class="selection-inline-title">Atenção aos dados de contato</div>
              <div class="selection-inline-text">
                As informações fornecidas a seguir serão utilizadas para o seu transporte. Caso precise alterar algum dado, clique na edição e corrija a informação.
              </div>
            </div>
          </div>
        </div>
        <div class="row q-col-gutter-sm">
          <div :class="item.personType == 'PJ' ? 'col-xs-12 col-sm-4' : 'col-xs-12 col-sm-6'">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              unmasked-value
              v-model="item.document"
              type="text"
              :label="item.personType == 'PJ' ? $t('CNPJ') : $t('CPF')"
              :mask="item.personType == 'PJ' ? '##.###.###/####-##' : '###.###.###-##'"
              :placeholder="item.personType == 'PJ' ? 'Digite o CNPJ' : 'Digite o CPF'"
              :rules="[isInvalid('document')]"
              @input="searchDocument"
              @paste="onDocumentPaste"
              @blur="onDocumentBlur"
            />
          </div>
          <div v-if="item.personType == 'PJ'" class="col-xs-12 col-sm-4">
            <q-input
              outlined
              stack-label
              dense
              v-model="item.name"
              type="text"
              :label="$t('Razão social')"
              :disable="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
            />
          </div>
          <div v-else class="col-xs-12 col-sm-6">
            <q-input
              outlined
              stack-label
              dense
              v-model="item.name"
              type="text"
              :label="$t('Nome da pessoa física')"
              placeholder="Digite o nome da pessoa física"
              :readonly="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
            >
              <template v-if="canEditPhysicalPerson" v-slot:append>
                <q-btn
                  dense
                  flat
                  round
                  color="primary"
                  icon="edit"
                  aria-label="Editar dados da pessoa física"
                  @click.stop="openPhysicalPersonDialog"
                >
                  <q-tooltip>Editar dados da pessoa física</q-tooltip>
                </q-btn>
              </template>
            </q-input>
          </div>
          <div v-if="item.personType == 'PJ'" class="col-xs-12 col-sm-4">
            <q-input
              outlined
              stack-label
              dense
              v-model="item.alias"
              type="text"
              :label="$t('Nome fantasia')"
              :disable="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
            />
          </div>
          <div class="col-xs-12">
            <div class="contact-required-box">
              <div class="contact-box-header">
                <div>
                  <div class="contact-box-title">Contato obrigatório da pessoa física</div>
                  <div class="contact-box-text">
                    Informe quem a transportadora deve procurar para combinar a coleta.
                  </div>
                </div>
                <div class="contact-box-actions">
                  <q-checkbox
                    dense
                    v-model="noRecipientContactData"
                    label="Não tenho os dados de contato"
                  />
                  <template v-if="showCollaboratorActions && !noRecipientContactData">
                    <q-btn
                      dense
                      flat
                      round
                      color="primary"
                      icon="person_add"
                      aria-label="Novo colaborador"
                      @click="openCollaboratorDialog('create')"
                      :disable="isResponsibleDataBlockedByDocument || noRecipientContactData"
                    >
                      <q-tooltip>Novo colaborador</q-tooltip>
                    </q-btn>
                    <q-btn
                      dense
                      flat
                      round
                      color="primary"
                      icon="edit"
                      aria-label="Editar colaborador"
                      @click="openCollaboratorDialog('edit')"
                      :disable="isResponsibleDataBlockedByDocument || noRecipientContactData || !hasContactToEdit"
                    >
                      <q-tooltip>Editar colaborador</q-tooltip>
                    </q-btn>
                  </template>
                </div>
              </div>
              <div v-if="!noRecipientContactData" class="row q-col-gutter-sm">
                <div v-if="item.personType == 'PJ'" class="col-xs-12 col-sm-12 col-md-4">
                  <q-input
                    outlined
                    stack-label
                    dense
                    lazy-rules
                    v-model="item.contact.name"
                    type="text"
                    :label="$t('Nome da pessoa física')"
                    placeholder="Digite o nome da pessoa física"
                    :rules="[isInvalid('contactName')]"
                    :readonly="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
                  />
                </div>
                <div :class="item.personType == 'PJ' ? 'col-xs-12 col-sm-12 col-md-4' : 'col-xs-12 col-sm-6'">
                  <q-input
                    outlined
                    stack-label
                    dense
                    lazy-rules
                    v-model="item.contact.email"
                    type="text"
                    :label="$t('Email')"
                    placeholder="Digite um e-mail"
                    :loading="loadingContact"
                    :rules="[isInvalid('email')]"
                    :readonly="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
                  />
                </div>
                <div :class="item.personType == 'PJ' ? 'col-xs-12 col-sm-12 col-md-4' : 'col-xs-12 col-sm-6'">
                  <q-input
                    outlined
                    stack-label
                    dense
                    lazy-rules
                    unmasked-value
                    v-model="item.contact.phone"
                    type="text"
                    :label="$t('Telefone')"
                    :mask="phoneMask"
                    placeholder="Telefone"
                    :rules="[isInvalid('optionalPhone')]"
                    @keydown="handlePhoneKeydown"
                    @input="handlePhoneInput"
                    @paste="handlePhonePaste"
                    :readonly="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
                  />
                </div>
                <div v-if="contacts.length > 1" class="col-xs-12 col-sm-6">
                  <q-select
                    outlined
                    stack-label
                    dense
                    v-model="contactSelected"
                    :options="contactsOptions"
                    option-value="value"
                    option-label="label"
                    emit-value
                    map-options
                    label="Selecione o contato"
                    :disable="isResponsibleDataBlockedByDocument || noRecipientContactData"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- SEÇÃO 3: CONTATO -->
    <div v-else-if="item.whereRetrieve != 'MC'" class="form-section q-mb-sm">
      <div class="section-header">
        <div class="section-number">{{ item.whereRetrieve == 'MC' ? '2' : '3' }}</div>
        <div class="section-title">Contato de coleta</div>
      </div>
      <div class="q-pa-md">
        <div class="row q-col-gutter-sm">
          <div :class="item.personType == 'PJ' ? 'col-xs-12 col-sm-4' : 'col-xs-12 col-sm-6'">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              unmasked-value
              v-model="item.document"
              type="text"
              :label="item.personType == 'PJ' ? $t('CNPJ') : $t('CPF')"
              :mask="item.personType == 'PJ' ? '##.###.###/####-##' : '###.###.###-##'"
              :placeholder="item.personType == 'PJ' ? 'Digite o CNPJ' : 'Digite o CPF'"
              :rules="[isInvalid('document')]"
              @input="searchDocument"
              @paste="onDocumentPaste"
              @blur="onDocumentBlur"
            />
          </div>
          <div v-if="item.personType == 'PJ'" class="col-xs-12 col-sm-4">
            <q-input
              outlined
              stack-label
              dense
              v-model="item.name"
              type="text"
              :label="$t('Razão social')"
              :disable="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
            />
          </div>
          <div v-if="item.personType == 'PJ'" class="col-xs-12 col-sm-4">
            <q-input
              outlined
              stack-label
              dense
              v-model="item.alias"
              type="text"
              :label="$t('Nome fantasia')"
              :disable="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
            />
          </div>
          <div v-else class="col-xs-12 col-sm-6">
            <q-input
              outlined
              stack-label
              dense
              v-model="item.name"
              type="text"
              :label="$t('Nome da pessoa física')"
              placeholder="Digite o nome da pessoa física"
              :readonly="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
            >
              <template v-if="canEditPhysicalPerson" v-slot:append>
                <q-btn
                  dense
                  flat
                  round
                  color="primary"
                  icon="edit"
                  aria-label="Editar dados da pessoa física"
                  @click.stop="openPhysicalPersonDialog"
                >
                  <q-tooltip>Editar dados da pessoa física</q-tooltip>
                </q-btn>
              </template>
            </q-input>
          </div>
          <div class="col-xs-12">
            <q-checkbox
              dense
              v-model="noRecipientContactData"
              label="Não tenho os dados de contato"
            />
          </div>
          <div v-if="!noRecipientContactData && item.personType == 'PJ'" class="col-xs-12 col-sm-6">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              v-model="item.contact.name"
              type="text"
              :label="$t('Nome da pessoa física')"
              placeholder="Digite o nome da pessoa física"
              :rules="[isInvalid('contactName')]"
              :readonly="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
            />
          </div>
          <div v-if="!noRecipientContactData" class="col-xs-12 col-sm-6">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              v-model="item.contact.email"
              type="text"
              :label="$t('Email')"
              placeholder="Digite um e-mail"
              :loading="loadingContact"
              :rules="[isInvalid('email')]"
              :readonly="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
            />
          </div>
          <div v-if="!noRecipientContactData" class="col-xs-12 col-sm-6">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              unmasked-value
              v-model="item.contact.phone"
              type="text"
              :label="$t('Telefone')"
              :mask="phoneMask"
              placeholder="Telefone"
              :rules="[isInvalid('optionalPhone')]"
              @keydown="handlePhoneKeydown"
              @input="handlePhoneInput"
              @paste="handlePhonePaste"
              :readonly="isPersonFieldsLocked || isResponsibleDataBlockedByDocument"
            />
          </div>
          <div v-if="!noRecipientContactData && contacts.length > 1" class="col-xs-12 col-sm-6">
            <q-select
              outlined
              stack-label
              dense
              v-model="contactSelected"
              :options="contactsOptions"
              option-value="value"
              option-label="label"
              emit-value
              map-options
              label="Selecione o contato"
              :disable="isResponsibleDataBlockedByDocument || noRecipientContactData"
            />
          </div>
          <div v-if="showCollaboratorActions && !noRecipientContactData" class="col-xs-12">
            <div class="row q-col-gutter-sm">
              <div class="col-auto">
                <q-btn
                  dense
                  outline
                  color="primary"
                  icon="person_add"
                  label="Novo colaborador"
                  @click="openCollaboratorDialog('create')"
                  :disable="isResponsibleDataBlockedByDocument || noRecipientContactData"
                />
              </div>
              <div class="col-auto">
                <q-btn
                  dense
                  flat
                  color="primary"
                  icon="edit"
                  label="Editar colaborador"
                  @click="openCollaboratorDialog('edit')"
                  :disable="isResponsibleDataBlockedByDocument || noRecipientContactData || !hasContactToEdit"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- SEÇÃO 3.1: SELEÇÃO DE EMPRESA -->
    <div v-if="item.whereRetrieve != 'MC' && item.whereRetrieve != 'OP' && companiesOptions.length > 1" class="form-section q-mb-sm">
      <div class="section-header">
        <div class="section-number">{{ item.whereRetrieve == 'MC' ? '2' : '3' }}</div>
        <div class="section-title">Selecione a empresa</div>
      </div>
      <div class="q-pa-md">
        <q-select
          v-model="selectedCompanyId"
          :options="companiesOptions"
          option-value="value"
          option-label="label"
          emit-value
          map-options
          outlined
          dense
        />
      </div>
    </div>

    <!-- SEÇÃO 4: DADOS DA EMPRESA -->
    <div v-if="item.whereRetrieve != 'MC' && item.whereRetrieve != 'OP' && item.personType == 'PF'" class="form-section q-mb-sm">
      <div class="section-header">
        <div class="section-number">{{ item.whereRetrieve == 'MC' ? '2' : '4' }}</div>
        <div class="section-title">Dados da empresa responsável</div>
      </div>
      <div class="q-pa-md">
        <div class="row q-col-gutter-sm">
          <div class="col-xs-6 col-sm-6">
            <q-input
              outlined
              stack-label
              dense
              v-model="item.name"
              type="text"
              label="Razão social"
              
            />
          </div>
          <div class="col-xs-6 col-sm-6">
            <q-input
              outlined
              stack-label
              dense
              v-model="item.alias"
              type="text"
              label="Nome fantasia"
              
            />
          </div>
        </div>
        <div class="row q-col-gutter-sm q-mt-sm">

        </div>
      </div>
    </div>

    <!-- SEÇÃO 5: ENDEREÇO -->
    <div class="form-section q-mb-sm">
      <div class="section-header">
        <div class="section-number">
          {{
            item.whereRetrieve == 'MC'
              ? '2'
              : item.whereRetrieve == 'OP'
              ? '3'
              : '5'
          }}
        </div>
        <div class="section-title">{{ item.whereRetrieve === 'MC' ? 'Selecione endereço de coleta' : 'Endereço de coleta' }}</div>
      </div>
      <div class="q-pa-md">
        <ListAutocomplete
          v-if="!isDataLocked"
          :source="getGeoPlaces"
          :isLoading="isSearching"
          label="Busca de endereço"
          @selected="onSelect"
          placeholder="Digite o endereço completo (rua, número, bairro, CEP)"
        />
        <div v-else class="text-caption text-grey-7">
          Endereço deve ser preenchido manualmente.
        </div>
      </div>
    </div>

    <!-- SEÇÃO 6: DETALHES DO ENDEREÇO -->
    <div class="form-section q-mb-sm">
      <div class="section-header">
        <div class="section-number">
          {{
            item.whereRetrieve == 'MC'
              ? '3'
              : item.whereRetrieve == 'OP'
              ? '4'
              : '6'
          }}
        </div>
        <div class="section-title">Detalhes do endereço</div>
      </div>
      <div class="row q-pa-md q-col-gutter-md">
        <!-- <div class="row q-col-gutter-sm"> -->
          <div class="col-xs-12 col-sm-6 col-md-3">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              unmasked-value
              v-model="item.address.postal_code"
              type="text"
              :label="$t('CEP')"
              mask="#####-###"
              :rules="[isInvalid('postal_code')]"
              hide-bottom-space
            />
          </div>
          <div class="col-xs-12 col-sm-6 col-md-5">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              v-model="item.address.street"
              type="text"
              :label="$t('Rua')"
              :rules="[isInvalid('street')]"
              hide-bottom-space
            />
          </div>
          <div class="col-xs-12 col-sm-6 col-md-4">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              v-model="item.address.number"
              type="text"
              :label="$t('Número')"
              :rules="[isInvalid('number')]"
              hide-bottom-space
            />
          </div>
          <div class="col-xs-12 col-sm-12 col-md-12">
            <q-input
              outlined
              stack-label
              dense
              v-model="item.address.complement"
              type="text"
              :label="$t('Complemento')"
              hide-bottom-space
            />
          </div>
          <div class="col-xs-12 col-sm-6 col-md-4">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              v-model="item.address.district"
              type="text"
              :label="$t('Bairro')"
              :rules="[isInvalid('district')]"
              hide-bottom-space
            />
          </div>
          <div class="col-xs-12 col-sm-6 col-md-4">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              v-model="item.address.city"
              type="text"
              :label="$t('Cidade')"
              :rules="[isInvalid('city')]"
              hide-bottom-space
            />
          </div>
          <div class="col-xs-12 col-sm-6 col-md-2">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              v-model="item.address.state"
              type="text"
              :label="$t('UF')"
              mask="AA"
              :rules="[isInvalid('state')]"
              hide-bottom-space
            />
          </div>
          <div class="col-xs-12 col-sm-6 col-md-2">
            <q-input
              outlined
              stack-label
              dense
              lazy-rules
              v-model="item.address.country"
              type="text"
              :label="$t('País')"
              :rules="[isInvalid('country')]"
              hide-bottom-space
            />
          </div>
        <!-- </div> -->
      </div>
    </div>

    <!-- FOOTER: BOTÃO DE PRÓXIMA ETAPA -->
    <q-dialog v-model="dialogs.collaborator.visible">
      <q-card style="width: 520px; max-width: 96vw">
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">
            {{ dialogs.collaborator.mode === 'edit' ? 'Editar colaborador' : 'Novo colaborador' }}
          </div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>
        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-input
                outlined
                dense
                stack-label
                label="Nome"
                lazy-rules
                v-model="dialogs.collaborator.form.name"
                :rules="[isInvalid('contactName')]"
              />
            </div>
            <div class="col-12 col-sm-6">
              <q-input
                outlined
                dense
                stack-label
                label="E-mail"
                lazy-rules
                v-model="dialogs.collaborator.form.email"
                :rules="[isInvalid('email')]"
              />
            </div>
            <div class="col-12 col-sm-6">
              <q-input
                outlined
                dense
                stack-label
                unmasked-value
                :mask="collaboratorPhoneMask"
                label="Telefone"
                lazy-rules
                v-model="dialogs.collaborator.form.phone"
                :rules="[isInvalid('phone')]"
              />
            </div>
          </div>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn flat label="Cancelar" v-close-popup />
          <q-btn
            color="primary"
            label="Salvar"
            :loading="dialogs.collaborator.saving"
            @click="saveCollaborator"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <q-dialog v-model="dialogs.physicalPerson.visible">
      <q-card style="width: 520px; max-width: 96vw">
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">Editar dados da pessoa física</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>
        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-input
                outlined
                dense
                stack-label
                label="Nome"
                lazy-rules
                v-model="dialogs.physicalPerson.form.name"
                :rules="[isInvalid('contactName')]"
              />
            </div>
            <div class="col-12 col-sm-6">
              <q-input
                outlined
                dense
                stack-label
                label="E-mail"
                lazy-rules
                v-model="dialogs.physicalPerson.form.email"
                :rules="[isInvalid('email')]"
                :disable="noRecipientContactData"
              />
            </div>
            <div class="col-12 col-sm-6">
              <q-input
                outlined
                dense
                stack-label
                label="Telefone"
                lazy-rules
                v-model="dialogs.physicalPerson.form.phone"
                :rules="[isInvalid('optionalPhone')]"
                :disable="noRecipientContactData"
              />
            </div>
          </div>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn flat label="Cancelar" v-close-popup />
          <q-btn
            color="primary"
            label="Salvar"
            :loading="dialogs.physicalPerson.saving"
            @click="savePhysicalPerson"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <div class="q-pt-lg">
      <div class="row justify-end">
        <q-btn
          type="submit"
          color="primary"
          label="Seguinte"
          icon="arrow_forward"
          :loading="isLoading"
          class="q-px-lg"
        />
      </div>
    </div>

  </q-form>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import { fetch as apiFetch } from "src/boot/myapi";
import ListAutocomplete from "@freteclick/quasar-common-ui/src/components/common/ListAutocomplete.vue";

export default {
  components: {
    ListAutocomplete,
  },

  props: {
    order: {
      type: Object,
      required: true,
    },
    steps: {
      type: Object,
      required: true,
    },
    extra: {
      type: Object,
      required: true,
    },
    quoteContact: {
      type: Object,
      required: false,
    },
  },

  data() {
    let data = {
      isNewPeople: true,
      searchEmailTime: null,
      isSearching: false,
      loadingContact: false,
      loadingCep: false,
      noRecipientContactData: false,
      isDataLocked: false,
      isPersonDataLocked: false,
      physicalPersonCanPersist: false,
      companiesOptions: [],
      selectedCompanyId: null,
      lastContactData: null,
      selectedCompanyFromUserId: null,
      hasPersistedStepData: false,
      useCellphoneMask: false,
      contacts: [],
      contactSelected: null,
      localContactSeq: 0,
      dialogs: {
        collaborator: {
          visible: false,
          mode: "create",
          saving: false,
          form: {
            id: null,
            localKey: null,
            name: "",
            email: "",
            phone: "",
          },
        },
        physicalPerson: {
          visible: false,
          saving: false,
          form: {
            name: "",
            email: "",
            phone: "",
          },
        },
      },
      personTypeOptions: [
        { label: 'Pessoa Jurídica', value: 'PJ' },
        { label: 'Pessoa Física', value: 'PF' },
      ],
      item: {
        id: null,
        name: null,
        alias: null,
        document: null,
        personType: "PJ",
        whereRetrieve: "MC",
        contact: {
          id: null,
          name: null,
          email: null,
          phone: null,
        },
        address: {
          id: null,
          country: "",
          state: "",
          city: "",
          district: "",
          postal_code: "",
          street: "",
          number: "",
          complement: "",
        },
      },
    };

    const retrieve = this.steps && this.steps.retrieve ? this.steps.retrieve : null;
    const hasRetrieveData =
      !!retrieve &&
      (retrieve.id !== null ||
        Object.keys(retrieve).some(
          (key) => key !== "id" && retrieve[key] !== null && retrieve[key] !== undefined
        ));

    if (hasRetrieveData) {
      data.hasPersistedStepData = true;
      data.item.whereRetrieve =
        (this.extra && this.extra.whereRetrieve) ||
        retrieve.whereRetrieve ||
        data.item.whereRetrieve;
      data.item.contact.id = retrieve.contact ? retrieve.contact.id : null;
      data.item.contact.name = retrieve.contact ? retrieve.contact.name : null;
      data.item.contact.email = retrieve.contact ? retrieve.contact.email : null;
      data.item.contact.phone = retrieve.contact ? retrieve.contact.phone : null;
      data.contacts = this.extra && this.extra.contacts ? this.extra.contacts : [];
      data.noRecipientContactData = !!(
        this.extra && this.extra.noRecipientContactData
      );
      data.searchEmailValue = this.quoteContact ? this.quoteContact.email : null;
      data.item.id = retrieve.id;
      data.item.name = retrieve.name;
      data.item.alias = retrieve.alias;
      data.item.document = retrieve.document;
      data.item.personType =
        (this.extra && this.extra.personType) ||
        retrieve.personType ||
        data.item.personType;
      if (retrieve.address) {
        data.item.address.id = retrieve.address.id;
        data.item.address.country = retrieve.address.country;
        data.item.address.state = retrieve.address.state;
        data.item.address.city = retrieve.address.city;
        data.item.address.district = retrieve.address.district;
        data.item.address.postal_code = retrieve.address.postal_code;
        data.item.address.street = retrieve.address.street;
        data.item.address.number = retrieve.address.number;
        data.item.address.complement = retrieve.address.complement;
      }
      if (data.item.whereRetrieve === "OP") {
        data.selectedCompanyFromUserId = "OP";
      }
    }

    return data;
  },

  created() {
    this.ensureContactShape();
    this.loadUserCompanies();
    if (!this.hasPersistedStepData) {
      this.setAddress(this.order.address.origin);
      const loggedContact = this.getLoggedContact();
      if (this.item.whereRetrieve === "MC" && loggedContact) {
        this.item.contact = {
          ...this.item.contact,
          ...loggedContact,
        };
      } else if (
        this.order.contact &&
        this.order.id &&
        (!this.quoteContact ||
          (!this.quoteContact.name &&
            !this.quoteContact.email &&
            !this.quoteContact.phone))
      ) {
          this.item.contact = this.order.contact;
      }
      this.ensureContactShape();
      this.setContactData();
      this.checkRetrieve();
    }
  },

  computed: {
    ...mapGetters({
      isLoading: "people/isLoading",
      myCompany: "people/currentCompany",
      defaultCompany: "people/defaultCompany",
      companies: "people/companies",
    }),

    phoneMask() {
      const phone = this.item && this.item.contact ? this.item.contact.phone : "";
      const digits = this.normalizePhoneDigits(phone);
      return this.useCellphoneMask || digits.length > 10
        ? "(##) #####-####"
        : "(##) ####-####";
    },

    isPersonFieldsLocked() {
      return this.item.whereRetrieve !== "MC" && this.isPersonDataLocked;
    },

    isResponsibleDataBlockedByDocument() {
      const digits = (this.item && this.item.document ? this.item.document : "")
        .toString()
        .replace(/\D/g, "");
      return digits.length === 0;
    },

    logged() {
      return this.$store.getters["auth/user"];
    },

    isOtherLocation() {
      return this.selectedCompanyFromUserId === "OP";
    },

    selectedUserCompanyName() {
      if (this.isOtherLocation) return "";
      const company = this.selectedUserCompany;
      return company ? company.name || company.alias || "" : "";
    },

    selectedUserCompanyAlias() {
      if (this.isOtherLocation) return "";
      const company = this.selectedUserCompany;
      return company ? company.alias || "" : "";
    },

    selectedUserCompanyDocument() {
      if (this.isOtherLocation) return "";
      const company = this.selectedUserCompany;
      if (!company || !company.document) return "";
      const doc = company.document;
      if (typeof doc === "object") {
        return doc.id || doc.document || "";
      }
      return doc || "";
    },

    selectedUserCompanyCnpj() {
      const digits = (this.selectedUserCompanyDocument || "").toString().replace(/\D/g, "");
      if (!digits) return "";
      if (digits.length !== 14) return this.selectedUserCompanyDocument;
      return digits.replace(
        /^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/,
        "$1.$2.$3/$4-$5"
      );
    },

    selectedUserCompany() {
      if (this.selectedCompanyFromUserId && this.selectedCompanyFromUserId !== "OP") {
        const fromList = (this.companies || []).find(c => c.id === this.selectedCompanyFromUserId);
        if (fromList) return fromList;
      }
      return this.myCompany || this.defaultCompany || null;
    },

    userCompanyOptions() {
      const opts = [];
      const company = this.selectedUserCompany || this.myCompany || this.defaultCompany;

      if (company && company.id) {
        opts.push({
          label: company.name || company.alias || "Minha empresa",
          value: company.id,
        });
      }

      opts.push({
        label: "Outro local",
        value: "OP",
      });

      return opts;
    },

    quoteAddressIsFull() {
      if (this.order.address.origin === null) return null;

      return (
        this.order.address.origin.country.length > 0 &&
        this.order.address.origin.state.length > 0 &&
        this.order.address.origin.city.length > 0 &&
        this.order.address.origin.district.length > 0 &&
        this.order.address.origin.postalCode.length > 0 &&
        this.order.address.origin.street.length > 0 &&
        this.order.address.origin.number.length > 0
      );
    },

    contactsOptions() {
      return (this.contacts || []).map((contact) => ({
        label: contact.alias
          ? `${contact.name} (${contact.alias})`
          : contact.name || contact.email || contact.phone || "Contato",
        value: this.getContactOptionValue(contact),
      }));
    },

    showCollaboratorActions() {
      return (
        this.item &&
        this.item.personType === "PJ" &&
        this.item.document &&
        this.item.document.toString().replace(/\D/g, "").length === 14 &&
        this.item.whereRetrieve !== "MC"
      );
    },

    hasContactToEdit() {
      const selected = this.getSelectedContact();
      return !!(selected && selected.id);
    },

    canEditPhysicalPerson() {
      return (
        this.item &&
        this.item.personType === "PF" &&
        !!this.item.id &&
        this.isPersonDataLocked &&
        !this.isResponsibleDataBlockedByDocument
      );
    },

    collaboratorPhoneMask() {
      const v =
        this.dialogs &&
        this.dialogs.collaborator &&
        this.dialogs.collaborator.form &&
        this.dialogs.collaborator.form.phone
          ? this.dialogs.collaborator.form.phone
          : "";
      return v.length <= 10 ? "(##) ####-####" : "(##) #####-####";
    },
  },

  watch: {
    logged(newUser, oldUser) {
      const newToken = newUser && newUser.token ? newUser.token : null;
      const oldToken = oldUser && oldUser.token ? oldUser.token : null;
      if (newToken && newToken !== oldToken) {
        this.selectedCompanyFromUserId = null;
        this.loadUserCompanies();
      }
    },
    quoteContact: function (newValue) {
      if (newValue) {
        this.setContactData();
      }
    },
    noRecipientContactData(value) {
      if (value) {
        this.clearContactData();
      }
    },
    companies() {
      this.setDefaultCompanySelection();
    },
    selectedCompanyFromUserId(value) {
      this.onUserCompanySelectionChange(value);
    },
    contactSelected: function (contactId) {
      const selected = this.findContactByOptionValue(contactId);
      if (selected) {
        this.applySelectedContact(selected);
      }
    },
    selectedCompanyId: function (companyId) {
      if (companyId) {
        this.applySelectedCompany(companyId);
      }
    },
    "item.personType"(newType, oldType) {
      this.onPersonTypeChange(newType, oldType);
    },
    "item.whereRetrieve"(where) {
      this.whereRetrieve(where);
    },

    'newAddress.postal_code'(code) {
      const digits = (code || '').toString().replace(/\D/g, '');
      if (digits.length === 8) {
        this.loadingCep = true;
        this.getAddressByCEP(digits)
          .then(address => {
            if (address && address['@id']) {
              this.newAddress.country = address.country || '';
              this.newAddress.state = address.state || '';
              this.newAddress.city = address.city || '';
              this.newAddress.district = address.district || '';
              this.newAddress.street = address.street || '';
              this.newAddress.number = address.number ? address.number.toString() : '';
              const formatted = digits.substr(0,5) + '-' + digits.substr(5);
              this.newAddress.postal_code = formatted;
            }
          })
          .catch(() => {
            this.$q.notify({ message: this.$t('messages.noCepFound') || 'Nenhum endereço foi encontrado', type: 'negative' });
          })
          .finally(() => {
            this.loadingCep = false;
          });
      }
    },
  },

  methods: {
    ...mapActions({
      contact: "people/contact",
      createContact: "people/createContact",
      geoplace: "gmaps/geoplace",
      getAddress: "profile/getAddress",
      getPhones: "profile/getPhones",
      getEmails: "profile/getEmails",
      getAddressByCEP: 'gmaps/getAddressByCEP',
      saveProfile: 'profile/updateProfile',
      getCompanies: "people/myCompanies",
    }),

    loadUserCompanies() {
      return this.getCompanies()
        .then(() => {
          this.setDefaultCompanySelection();
        })
        .catch(() => {
          this.setDefaultCompanySelection();
        });
    },

    setDefaultCompanySelection() {
      if (this.selectedCompanyFromUserId) return;
      const company = this.selectedUserCompany;
      if (company && company.id) {
        this.selectedCompanyFromUserId = company.id;
      } else {
        this.selectedCompanyFromUserId = "OP";
      }
    },

    onUserCompanySelectionChange(value) {
      if (this.isDataLocked) return;
      if (value === "OP") {
        this.item.whereRetrieve = "OP";
        this.item.id = null;
        this.item.name = null;
        this.item.alias = null;
        this.item.document = null;
        this.checkRetrieve();
      } else if (value) {
        const company = (this.companies || []).find((c) => c.id === value);
        if (company) {
          this.item.whereRetrieve = "MC";
          this.applySelectedUserCompany(company);
          this.checkRetrieve();
        }
      } else {
        this.item.whereRetrieve = "OP";
        this.checkRetrieve();
      }
    },

    applySelectedUserCompany(company) {
      if (!company) return;
      this.item.id = company.id || null;
      this.item.name = company.alias || company.name || "";
      this.item.alias = company.alias || company.name || "";
      this.item.document = company.document || this.item.document;
      this.item.personType = "PJ";
    },

    whereRetrieve(where) {
      this.checkRetrieve();
    },

    checkRetrieve() {
      if (this.item.whereRetrieve == "MC") {
        this.setContactData();
        this.item.personType = "PJ";
      } else {
        if (!this.item.id) {
          this.reset();
          this.item.personType = "PJ";
        } else {
          this.item.personType = "PJ";
        }
      }
    },

    onPersonTypeChange(newType, oldType) {
      if (!oldType || newType === oldType) return;
      if (this.item.whereRetrieve === "MC") return;

      if (this.searchEmailTime !== null) {
        clearTimeout(this.searchEmailTime);
        this.searchEmailTime = null;
      }

      this.isPersonDataLocked = false;
      this.physicalPersonCanPersist = false;
      this.isNewPeople = true;
      this.noRecipientContactData = false;
      this.lastContactData = null;
      this.isDataLocked = false;
      this.selectedCompanyId = null;
      this.companiesOptions = [];
      this.contacts = [];
      this.contactSelected = null;
      this.item.id = null;
      this.item.name = null;
      this.item.alias = null;
      this.item.document = null;
      this.item.contact.id = null;
      this.item.contact.name = null;
      this.item.contact.email = null;
      this.item.contact.phone = null;
      if (this.dialogs && this.dialogs.physicalPerson) {
        this.dialogs.physicalPerson.visible = false;
      }
    },

    searchEmail: function (email) {
      if (this.searchEmailTime !== null) {
        clearTimeout(this.searchEmailTime);
        this.searchEmailTime = null;
      }
      return email;
    },

    searchDocument: function (document) {
      this.isPersonDataLocked = false;
      this.physicalPersonCanPersist = false;
      this.isNewPeople = true;
      this.noRecipientContactData = false;
      this.item.id = null;
      if (this.searchEmailTime !== null) {
        clearTimeout(this.searchEmailTime);
        this.searchEmailTime = null;
      }

      if (document) {
        const digits = document.toString().replace(/\D/g, "");
        const expectedLength = this.item.personType == "PJ" ? 14 : 11;
        if (digits.length < expectedLength) {
          this.item.name = null;
          this.item.alias = null;
        }
        if (digits.length !== expectedLength) {
          return;
        }
        this.searchEmailTime = setTimeout(
          function () {
            this.search(document);
          }.bind(this),
          1000
        );
      }
    },

    retira_acentos(str) {
      let com_acento =
        "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝŔÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿŕ";

      let sem_acento =
        "AAAAAAACEEEEIIIIDNOOOOOOUUUUYRsBaaaaaaaceeeeiiiionoooooouuuuybyr";
      let novastr = "";
      let troca = false;
      for (let i = 0; i < str.length; i++) {
        troca = false;
        for (let a = 0; a < com_acento.length; a++) {
          if (str.substr(i, 1) == com_acento.substr(a, 1)) {
            novastr += sem_acento.substr(a, 1);
            troca = true;
            break;
          }
        }
        if (troca == false) {
          novastr += str.substr(i, 1);
        }
      }
      return novastr;
    },

    getLoggedContact() {
      const user = this.logged;
      if (!user) return null;
      return {
        id: user.people || null,
        name: user.realname || user.username || user.user || null,
        email: user.email || null,
        phone: user.phone || null,
      };
    },

    getContactOptionValue(contact) {
      if (!contact) return null;
      return contact.localKey || contact.id || null;
    },

    findContactByOptionValue(contactValue) {
      const normalizedValue =
        contactValue === null || contactValue === undefined
          ? null
          : contactValue.toString();
      return (this.contacts || []).find(
        (c) => {
          const optionValue = this.getContactOptionValue(c);
          if (optionValue === null || optionValue === undefined) return false;
          return optionValue.toString() === normalizedValue;
        }
      );
    },

    getSelectedContact() {
      if (this.contactSelected !== null && this.contactSelected !== undefined) {
        const selected = this.findContactByOptionValue(this.contactSelected);
        if (selected) return selected;
      }
      if (this.item && this.item.contact && this.item.contact.id) {
        const byId = (this.contacts || []).find((c) => c.id === this.item.contact.id);
        if (byId) return byId;
      }
      if (this.item && this.item.contact && (this.item.contact.name || this.item.contact.email || this.item.contact.phone)) {
        return this.item.contact;
      }
      return null;
    },

    normalizeContact(contact) {
      if (!contact) return null;
      return {
        ...contact,
        name: contact.name || "",
        email: this.getContactEmailValue(contact),
        phone: this.getContactPhoneValue(contact),
      };
    },

    applySelectedContact(contact) {
      if (!contact) return;
      this.ensureContactShape();
      const email = this.getContactEmailValue(contact);
      const phone = this.getContactPhoneValue(contact);
      const merged = {
        ...this.item.contact,
        ...contact,
        email: email || this.item.contact.email || null,
        phone: phone || this.item.contact.phone || null,
      };
      this.$set(this.item, "contact", merged);
      this.ensureContactShape();
    },

    ensureContactShape() {
      if (!this.item) return;
      if (!this.item.contact || typeof this.item.contact !== "object") {
        this.$set(this.item, "contact", {});
      }
      ["id", "name", "email", "phone"].forEach((key) => {
        if (!(key in this.item.contact)) {
          this.$set(this.item.contact, key, null);
        }
      });
    },

    getContactEmailValue(source) {
      if (!source) return "";
      if (typeof source === "string") return source;
      if (Array.isArray(source)) {
        for (const item of source) {
          const value = this.getContactEmailValue(item);
          if (value) return value;
        }
        return "";
      }
      if (typeof source === "object") {
        const nestedCollections = [source.members, source.data, source.items, source.values];
        for (const collection of nestedCollections) {
          const value = this.getContactEmailValue(collection);
          if (value) return value;
        }

        const dynamicEmailKey = Object.keys(source).find((key) =>
          key && key.toString().toLowerCase().includes("mail")
        );
        if (
          dynamicEmailKey &&
          (typeof source[dynamicEmailKey] === "string" ||
            typeof source[dynamicEmailKey] === "number")
        ) {
          const dynamicValue = source[dynamicEmailKey].toString().trim();
          if (dynamicValue.length > 0) return dynamicValue;
        }

        if (typeof source.mail === "string" && source.mail.trim().length > 0) {
          return source.mail;
        }
        if (
          typeof source.emailAddress === "string" &&
          source.emailAddress.trim().length > 0
        ) {
          return source.emailAddress;
        }
        if (typeof source.email === "string" && source.email.trim().length > 0) {
          return source.email;
        }
        if (typeof source.address === "string" && source.address.trim().length > 0) {
          return source.address;
        }
        if (source.email && typeof source.email === "object") {
          const nested = this.getContactEmailValue(source.email);
          if (nested) return nested;
        }
        if (Array.isArray(source.emails)) {
          const fromEmails = this.getContactEmailValue(source.emails);
          if (fromEmails) return fromEmails;
        }
      }
      return "";
    },

    getContactPhoneValue(source) {
      if (!source) return "";
      if (typeof source === "string" || typeof source === "number") {
        return source.toString();
      }
      if (Array.isArray(source)) {
        for (const item of source) {
          const value = this.getContactPhoneValue(item);
          if (value) return value;
        }
        return "";
      }
      if (typeof source === "object") {
        const nestedCollections = [source.members, source.data, source.items, source.values];
        for (const collection of nestedCollections) {
          const value = this.getContactPhoneValue(collection);
          if (value) return value;
        }

        if (
          typeof source.cellphone === "string" ||
          typeof source.cellphone === "number"
        ) {
          return source.cellphone.toString();
        }
        if (typeof source.phone === "string" || typeof source.phone === "number") {
          const phone = source.phone.toString();
          if (source.ddd) return `${source.ddd}${phone}`;
          return phone;
        }
        if (Array.isArray(source.phones)) {
          const fromPhones = this.getContactPhoneValue(source.phones);
          if (fromPhones) return fromPhones;
        }
        const ddd = source.ddd ? source.ddd.toString() : "";
        const number = source.number ? source.number.toString() : "";
        if (ddd || number) return `${ddd}${number}`;
      }
      return "";
    },

    hasValidContactPhone(contact) {
      const digits = this.normalizePhoneDigits(this.getContactPhoneValue(contact));
      return digits.length >= 10 && digits.length <= 11;
    },

    hasValidContactData(contact) {
      return this.hasContactEmail(contact) && this.hasValidContactPhone(contact);
    },

    hasContactEmail(contact) {
      return this.getContactEmailValue(contact).toString().trim().length > 0;
    },

    resolveBestContactEmail(selectedContact, contacts, data) {
      return (
        this.getContactEmailValue(selectedContact) ||
        this.getContactEmailValue(contacts) ||
        this.getContactEmailValue(data && data.contact ? data.contact : null) ||
        this.getContactEmailValue(data) ||
        this.getContactEmailValue(this.item && this.item.contact ? this.item.contact : null) ||
        ""
      );
    },

    resolveBestContactPhone(selectedContact, contacts, data) {
      return (
        this.getContactPhoneValue(selectedContact) ||
        this.getContactPhoneValue(contacts) ||
        this.getContactPhoneValue(data && data.contact ? data.contact : null) ||
        this.getContactPhoneValue(data) ||
        this.getContactPhoneValue(this.item && this.item.contact ? this.item.contact : null) ||
        ""
      );
    },

    pickPreferredContact(contacts = []) {
      const list = Array.isArray(contacts) ? contacts : [];
      if (list.length === 0) return null;
      const logged = this.getLoggedContact();
      if (logged && logged.id) {
        const byId = list.find((c) => c.id === logged.id);
        if (byId && this.hasValidContactData(byId)) return byId;
      }
      if (logged && logged.email) {
        const loggedEmail = logged.email.toLowerCase();
        const byEmail = list.find(
          (c) => c.email && c.email.toLowerCase() === loggedEmail
        );
        if (byEmail && this.hasValidContactData(byEmail)) return byEmail;
      }
      const withContactData = list.find(
        (c) => this.hasValidContactData(c)
      );
      if (withContactData) return withContactData;

      return null;
    },

    openCollaboratorDialog(mode = "create") {
      const selected = this.getSelectedContact();
      this.dialogs.collaborator.mode = mode;
      if (mode === "edit" && selected) {
        this.dialogs.collaborator.form = {
          id: selected.id || null,
          localKey: selected.localKey || null,
          name: selected.name || "",
          email: selected.email || "",
          phone: selected.phone || "",
        };
      } else {
        this.dialogs.collaborator.form = {
          id: null,
          localKey: null,
          name: "",
          email: "",
          phone: "",
        };
      }
      this.dialogs.collaborator.visible = true;
    },

    openPhysicalPersonDialog() {
      if (!this.canEditPhysicalPerson) return;

      this.dialogs.physicalPerson.form = {
        name: this.item.name || "",
        email: this.item.contact && this.item.contact.email
          ? this.item.contact.email
          : "",
        phone: this.item.contact && this.item.contact.phone
          ? this.item.contact.phone
          : "",
      };
      this.dialogs.physicalPerson.visible = true;
    },

    onDocumentPaste() {
      this.$nextTick(() => {
        this.searchDocument(this.item.document);
      });
    },

    onDocumentBlur() {
      const document = this.item && this.item.document ? this.item.document : "";
      const digits = document.toString().replace(/\D/g, "");
      const expectedLength = this.item.personType == "PJ" ? 14 : 11;

      if (digits.length !== expectedLength) return;

      if (this.searchEmailTime !== null) {
        clearTimeout(this.searchEmailTime);
        this.searchEmailTime = null;
      }

      this.search(document);
    },

    saveCollaborator() {
      const payload = this.dialogs.collaborator.form || {};
      const name = (payload.name || "").trim();
      if (!name) {
        this.notifyError("Informe o nome do colaborador.");
        return;
      }
      const email = (payload.email || "").trim();
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        this.notifyError("Informe um e-mail válido para o colaborador.");
        return;
      }
      const phone = this.normalizePhoneDigits(payload.phone);
      if (!(phone.length >= 10 && phone.length <= 11)) {
        this.notifyError("Informe um telefone válido para o colaborador.");
        return;
      }

      this.dialogs.collaborator.saving = true;

      const selected = this.getSelectedContact();
      const mode = this.dialogs.collaborator.mode;

      const onSuccess = (contactId = null) => {
        const document = this.item && this.item.document ? this.item.document : null;
        const refresh = document ? this.search(document, contactId) : Promise.resolve();
        return refresh.then(() => {
          this.dialogs.collaborator.visible = false;
          this.$q.notify({
            message: "Colaborador salvo com sucesso.",
            position: "bottom",
            type: "positive",
          });
        });
      };

      const onError = (error) => {
        this.notifyError(
          error && error.message
            ? error.message
            : "Não foi possível salvar o colaborador."
        );
      };

      const finish = () => {
        this.dialogs.collaborator.saving = false;
      };

      if (mode === "create") {
        this.persistCollaboratorCreate(payload)
          .then((contactId) => onSuccess(contactId))
          .catch(onError)
          .finally(finish);
        return;
      }

      if (!selected || !selected.id) {
        finish();
        this.notifyError("Selecione um colaborador existente para editar.");
        return;
      }

      this.persistCollaboratorEdit(selected, payload)
        .then((contactId) => onSuccess(contactId))
        .catch(onError)
        .finally(finish);
    },

    savePhysicalPerson() {
      if (!this.canEditPhysicalPerson) return;

      const form = this.dialogs.physicalPerson.form || {};
      const name = (form.name || "").trim();
      if (!name) {
        this.notifyError("Informe o nome da pessoa física.");
        return;
      }

      const email = (form.email || "").trim();
      if (
        !this.noRecipientContactData &&
        !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
      ) {
        this.notifyError("Informe um e-mail válido para a pessoa física.");
        return;
      }

      const phone = this.normalizePhoneDigits(form.phone);
      if (phone && !(phone.length >= 10 && phone.length <= 11)) {
        this.notifyError("Informe um telefone válido para a pessoa física.");
        return;
      }

      if (!this.physicalPersonCanPersist) {
        this.applyPhysicalPersonDialogData(name, email, phone);
        this.dialogs.physicalPerson.visible = false;
        this.$q.notify({
          message:
            "Você não tem permissão para alterar este cadastro. Os dados foram aplicados apenas nesta cotação.",
          position: "bottom",
          type: "warning",
        });
        return;
      }

      this.dialogs.physicalPerson.saving = true;

      let chain = this.updatePhysicalPersonSummary(this.item.id, name);

      if (!this.noRecipientContactData) {
        const currentEmail = this.normalizeEmailValue(
          this.item && this.item.contact ? this.item.contact.email : ""
        );
        const currentPhone = this.normalizePhoneDigits(
          this.item && this.item.contact ? this.item.contact.phone : ""
        );

        if (this.normalizeEmailValue(email) !== currentEmail) {
          chain = chain.then(() =>
            this.updateCollaboratorEmail(this.item.id, email)
          );
        }
        if (phone !== currentPhone) {
          chain = chain.then(() =>
            this.updateCollaboratorPhone(this.item.id, phone)
          );
        }
      }

      chain
        .then(() => {
          this.applyPhysicalPersonDialogData(name, email, phone);
          this.dialogs.physicalPerson.visible = false;
          this.$q.notify({
            message: "Dados da pessoa física salvos com sucesso.",
            position: "bottom",
            type: "positive",
          });
        })
        .catch((error) => {
          this.notifyError(
            error && error.message
              ? error.message
              : "Não foi possível salvar os dados da pessoa física."
          );
        })
        .finally(() => {
          this.dialogs.physicalPerson.saving = false;
        });
    },

    applyPhysicalPersonDialogData(name, email, phone) {
      this.item.name = name;
      this.item.alias = name;
      this.ensureContactShape();
      this.item.contact.name = name;
      if (!this.noRecipientContactData) {
        this.item.contact.email = email;
        this.item.contact.phone = phone || null;
      }
    },

    normalizePhoneDigits(phone) {
      return (phone || "").toString().replace(/\D/g, "");
    },

    handlePhoneKeydown(event) {
      if (!event || !/^\d$/.test(event.key)) return;

      const digits = this.normalizePhoneDigits(
        this.item && this.item.contact ? this.item.contact.phone : ""
      );
      if (digits.length >= 10) {
        this.useCellphoneMask = true;
      }
    },

    handlePhoneInput(value) {
      this.useCellphoneMask = this.normalizePhoneDigits(value).length > 10;
    },

    handlePhonePaste(event) {
      const pasted = event && event.clipboardData
        ? event.clipboardData.getData("text")
        : "";
      const current = this.item && this.item.contact ? this.item.contact.phone : "";
      if (this.normalizePhoneDigits(current + pasted).length > 10) {
        this.useCellphoneMask = true;
      }
    },

    buildCollaboratorPayload(form) {
      return {
        name: (form.name || "").trim(),
        email: (form.email || "").trim(),
        phone: this.normalizePhoneDigits(form.phone),
      };
    },

    normalizeEmailValue(email) {
      return (email || "").toString().trim().toLowerCase();
    },

    getCollaboratorCompanyId() {
      if (this.item && this.item.id) return this.item.id;
      if (this.selectedCompanyId) return this.selectedCompanyId;
      if (this.companiesOptions && this.companiesOptions.length === 1) {
        return this.companiesOptions[0].value || null;
      }
      return null;
    },

    persistCollaboratorCreate(form) {
      const payload = this.buildCollaboratorPayload(form);
      const companyId = this.getCollaboratorCompanyId();

      if (!companyId) {
        return Promise.reject(
          new Error("Selecione e localize a empresa antes de incluir colaborador.")
        );
      }

      return this.createContact({
        companyId,
        contact: {
          name: payload.name,
          email: payload.email || null,
          phone: payload.phone || null,
        },
      }).then((response) => {
        if (!(response && response.success === true)) {
          throw new Error(
            (response && response.error) ||
              "Não foi possível criar o colaborador."
          );
        }
        return response && response.data ? response.data.contactId : null;
      });
    },

    updateCollaboratorSummary(peopleId, name) {
      return apiFetch(`customers/${peopleId}/summary`, {
        method: "PUT",
        headers: new Headers({ "Content-Type": "application/ld+json" }),
        body: JSON.stringify({
          name,
          alias: name,
        }),
      })
        .then((response) => response.json())
        .then((payload) => {
          if (!(payload && payload.response && payload.response.success)) {
            throw new Error(
              (payload && payload.response && payload.response.error) ||
                "Não foi possível atualizar o nome do colaborador."
            );
          }
          return true;
        });
    },

    updatePhysicalPersonSummary(peopleId, name) {
      return apiFetch(`customers/${peopleId}/summary`, {
        method: "PUT",
        headers: new Headers({ "Content-Type": "application/ld+json" }),
        body: JSON.stringify({
          name,
          alias: name,
        }),
      })
        .then((response) => response.json())
        .then((payload) => {
          if (!(payload && payload.response && payload.response.success)) {
            throw new Error(
              (payload && payload.response && payload.response.error) ||
                "Não foi possível atualizar o nome da pessoa física."
            );
          }
          return true;
        });
    },

    updateCollaboratorEmail(peopleId, email) {
      const next = (email || "").trim();
      if (!next) return Promise.resolve(true);

      return this.saveProfile({
        id: peopleId,
        component: "email",
        payload: {
          operation: "post",
          payload: { email: next },
        },
      }).then((result) => {
        if (result && result.response && result.response.success === false) {
          throw new Error(
            result.response.error ||
              "Não foi possível atualizar o e-mail do colaborador."
          );
        }
        return true;
      });
    },

    updateCollaboratorPhone(peopleId, phone) {
      const digits = this.normalizePhoneDigits(phone);
      if (!digits || digits.length < 10) return Promise.resolve(true);

      return this.saveProfile({
        id: peopleId,
        component: "phone",
        payload: {
          operation: "post",
          payload: {
            ddd: digits.substr(0, 2),
            phone: digits.substr(2),
          },
        },
      }).then((result) => {
        if (result && result.response && result.response.success === false) {
          throw new Error(
            result.response.error ||
              "Não foi possível atualizar o telefone do colaborador."
          );
        }
        return true;
      });
    },

    persistCollaboratorEdit(selected, form) {
      const payload = this.buildCollaboratorPayload(form);
      const currentName = (selected && selected.name ? selected.name : "")
        .toString()
        .trim();
      const currentEmail = this.normalizeEmailValue(selected && selected.email);
      const currentPhone = this.normalizePhoneDigits(selected && selected.phone);

      const shouldUpdateName = payload.name && payload.name !== currentName;
      const shouldUpdateEmail =
        this.normalizeEmailValue(payload.email) !== currentEmail;
      const shouldUpdatePhone = payload.phone !== currentPhone;

      let chain = Promise.resolve(true);

      if (shouldUpdateName) {
        chain = chain.then(() =>
          this.updateCollaboratorSummary(selected.id, payload.name)
        );
      }
      if (shouldUpdateEmail) {
        chain = chain.then(() =>
          this.updateCollaboratorEmail(selected.id, payload.email)
        );
      }
      if (shouldUpdatePhone) {
        chain = chain.then(() =>
          this.updateCollaboratorPhone(selected.id, payload.phone)
        );
      }

      return chain
        .then(() => selected.id);
    },

    normalizeCompanies(data) {
      if (!data || !data.companies) return [];
      const companies = Array.isArray(data.companies)
        ? data.companies
        : Array.isArray(data.companies.members)
        ? data.companies.members
        : Array.isArray(data.companies.data)
        ? data.companies.data
        : data.companies;
      return Array.isArray(companies) ? companies : companies ? [companies] : [];
    },

    applyCompanyDefaults() {
      const company = this.selectedUserCompany || this.myCompany || this.defaultCompany;
      if (company) {
        if (company.alias || company.name) {
          this.item.name = company.alias || company.name;
        }
        if (company.document) {
          this.item.document = company.document;
        }
      }
      const contact = this.getLoggedContact();
      if (contact) {
        if (contact.id) this.item.contact.id = contact.id;
        if (contact.name) this.item.contact.name = contact.name;
        if (contact.email) this.item.contact.email = contact.email;
        if (contact.phone) this.item.contact.phone = contact.phone;
      }
    },

    getCompanyFromContactData(data) {
      if (!data || !data.companies) return null;
      const companies = this.normalizeCompanies(data);
      return companies.length > 0 ? companies[0] : null;
    },

    formatQueryDate(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, "0");
      const d = String(date.getDate()).padStart(2, "0");
      return `${y}-${m}-${d}`;
    },

    searchCustomerByDocument(documentDigits) {
      const provider = this.myCompany || this.defaultCompany || null;
      if (!provider || !provider.id || !documentDigits) {
        return Promise.resolve({ success: false, data: null });
      }

      const toDate = new Date();
      const fromDate = new Date();
      fromDate.setDate(toDate.getDate() - 30);

      const params = {
        type: "all",
        from: this.formatQueryDate(fromDate),
        to: this.formatQueryDate(toDate),
        page: 1,
        limit: 8,
        searchBy: documentDigits,
        myProvider: provider.id,
      };

      return apiFetch("customers", { params })
        .then((response) => response.json())
        .then((payload) => {
          const apiResponse = payload && payload.response ? payload.response : null;
          if (!apiResponse || !apiResponse.success || !apiResponse.data) {
            return { success: false, data: null };
          }

          const members = Array.isArray(apiResponse.data.members)
            ? apiResponse.data.members
            : [];
          const customer = members.length > 0 ? members[0] : null;
          if (!customer) {
            return { success: false, data: null };
          }

          return {
            success: true,
            data: {
              id: customer.id || null,
              name: customer.name || null,
              alias: customer.alias || null,
              peopleType: customer.people_type || null,
              document: customer.document || documentDigits,
              contact: {
                id: null,
                name: null,
                email: customer.email || null,
                phone: customer.phone || null,
              },
              companies: [
                {
                  id: customer.id || null,
                  name: customer.name || null,
                  alias: customer.alias || null,
                  document: customer.document || documentDigits,
                },
              ],
            },
          };
        });
    },

    setContactData() {
      if (this.item.whereRetrieve === "MC") {
        this.applyCompanyDefaults();
        return;
      }
      if (
        (this.quoteContact && this.quoteContact.length > 0) ||
        this.order.contact
      ) {
        var contact = this.order.contact || this.quoteContact;
        if (contact.name) {
          this.item.contact.name = contact.name;
        }

        if (contact.phone) {
          this.item.contact.phone = contact.phone;
        }

        if (contact.email) {
          this.item.contact.email = contact.email;
        }

        if (contact.name || contact.phone || contact.email) {
          this.item.whereRetrieve = "MC";
        }
      }
    },

    applySelectedCompany(companyId) {
      const option = this.companiesOptions.find((c) => c.value === companyId);
      if (!option) return;
      this.item.id = option.value;
      if (option.raw && (option.raw.name || option.raw.alias)) {
        this.item.name = option.raw.name || option.raw.alias;
        this.item.alias = option.raw.alias || option.raw.name;
      }
      this.item.personType = "PJ";

      if (this.lastContactData && this.lastContactData.id === companyId) {
        if (this.lastContactData.document) {
          this.item.document =
            this.lastContactData.document.id ||
            this.lastContactData.document.document ||
            this.lastContactData.document;
        }
      }
    },

    save() {
      let data = this.item;
      data.whereRetrieve = this.item.whereRetrieve;
      if (this.noRecipientContactData) {
        this.clearContactData();
      } else {
        this.ensurePhysicalPersonContactName(data);
      }

      if (!this.validatePhysicalPersonContact(data)) {
        return;
      }

      this.$emit("saved", {
        errors: false,
        data: data,
        extra: {
          whereRetrieve: this.item.whereRetrieve,
          personType: this.item.personType,
          contacts: this.contacts,
          noRecipientContactData: this.noRecipientContactData,
        },
      });
    },

    contactByDocument(params = {}) {
      return apiFetch("people/1/contact", { params })
        .then((response) => response.json())
        .then((payload) => (payload && payload.response ? payload.response : null));
    },

    search(document = null, preferredContactId = null) {
      let request = {
        params: {},
      };
      const typedDigits = (document || "").toString().replace(/\D/g, "");

      if (this.order.address.origin !== null) {
        request.params["address[city]"] = this.order.address.origin.city;
        request.params["address[state]"] = this.order.address.origin.state;
        request.params["address[country]"] = this.order.address.origin.country;
      }

      if (document !== null) {
        request.params.document = typedDigits || document;
      }

      this.loadingContact = true;
      const searchPromise =
        document !== null
          ? this.contactByDocument(request.params)
          : this.contact(request);

      return searchPromise
        .then((response) => {
          const data = response && response.data ? response.data : null;
          let hasErrors = !(response && response.success === true && data);

          this.isNewPeople = true;
          this.item.contact = {
            id: null,
            name: null,
            email: null,
            phone: null,
          };
          this.ensureContactShape();
          this.contacts = [];
          this.lastContactData = data || null;
          this.companiesOptions = [];
          this.selectedCompanyId = null;
          this.isDataLocked = false;
          this.isPersonDataLocked = false;
          this.physicalPersonCanPersist = false;
          if (hasErrors) {
            this.item.id = null;
            this.item.name = null;
            this.item.alias = null;
            this.contactSelected = null;
            this.noRecipientContactData = false;
          }
          if (data) {
            const peopleType = data.peopleType
              ? data.peopleType.toString().toUpperCase()
              : null;
            const documentType =
              data.document && data.document.type
                ? data.document.type.toString().toUpperCase()
                : null;
            if (typedDigits.length === 14) {
              this.item.personType = "PJ";
            } else if (typedDigits.length === 11) {
              this.item.personType = "PF";
            } else if (documentType === "CNPJ" || documentType === "PJ") {
              this.item.personType = "PJ";
            } else if (documentType === "CPF" || documentType === "PF") {
              this.item.personType = "PF";
            } else if (peopleType === "J" || peopleType === "PJ") {
              this.item.personType = "PJ";
            }
          }

          if (!hasErrors) {
            this.isNewPeople = false;
            this.noRecipientContactData = false;
            this.isPersonDataLocked = true;

            this.item.name = data.name;
            this.item.alias = data.alias;

            const companies = this.normalizeCompanies(data);
            if (companies.length > 0) {
              this.companiesOptions = companies.map((company) => ({
                value: company.id,
                label: company.alias
                  ? `${company.alias} - ${company.name}`
                  : company.name,
                raw: company,
              }));
              const defaultId = data.id || this.companiesOptions[0].value;
              const hasDefault = this.companiesOptions.some(
                (c) => c.value === defaultId
              );
              this.selectedCompanyId = hasDefault
                ? defaultId
                : this.companiesOptions[0].value;
              this.isDataLocked = this.companiesOptions.length > 1;
              if (this.selectedCompanyId) {
                this.applySelectedCompany(this.selectedCompanyId);
              }
            }

            if (
              data.document
            ) {
              this.item.document =
                data.document.id || data.document.document || data.document;
            }

            const company = this.getCompanyFromContactData(data);
            if (company && (!this.item.name || !this.item.alias)) {
              this.item.name = this.item.name || company.name || company.alias || null;
              this.item.alias = this.item.alias || company.alias || company.name || null;
            }
            if (company && this.companiesOptions.length <= 1) {
              const companyId = company.id || company["@id"] || null;
              if (companyId) {
                this.item.id = companyId;
              }
              if (company.name || company.alias) {
                this.item.name = company.name || company.alias;
              }
              if (company.alias) {
                this.item.alias = company.alias;
              }
              if (company.document) {
                this.item.document =
                  company.document.id ||
                  company.document.document ||
                  company.document;
              }
              this.item.personType = "PJ";
            } else if (data.document && data.document.type) {
              this.item.id = data.id;
            } else if (this.companiesOptions.length > 1 && this.selectedCompanyId) {
              this.item.id = this.selectedCompanyId;
            }

            const contacts = Array.isArray(data.contact)
              ? data.contact
              : data.contact
              ? [data.contact]
              : [];
            const rawContactsEmail = this.getContactEmailValue(contacts);
            const rawContactsPhone = this.getContactPhoneValue(contacts);
            this.contacts = contacts.map((contact) => this.normalizeContact(contact));
            const selectedContact =
              (preferredContactId
                ? this.contacts.find((c) => c && c.id === preferredContactId)
                : null) || this.pickPreferredContact(this.contacts);
            this.contactSelected = selectedContact
              ? this.getContactOptionValue(selectedContact)
              : null;
            if (selectedContact) {
              this.applySelectedContact(selectedContact);
            }
            const bestEmail =
              this.resolveBestContactEmail(selectedContact, contacts, data) || rawContactsEmail;
            const bestPhone =
              this.resolveBestContactPhone(selectedContact, contacts, data) || rawContactsPhone;
            this.$set(this.item.contact, "email", bestEmail || null);
            this.$set(this.item.contact, "phone", bestPhone || null);
            this.$nextTick(() => {
              if (!this.item.contact.email && bestEmail) {
                this.$set(this.item.contact, "email", bestEmail);
              }
              if (!this.item.contact.phone && bestPhone) {
                this.$set(this.item.contact, "phone", bestPhone);
              }
            });

            if (typedDigits.length === 14) {
              this.item.personType = "PJ";
            } else if (typedDigits.length === 11) {
              this.item.personType = "PF";
              this.searchCustomerByDocument(typedDigits)
                .then((result) => {
                  const customer =
                    result && result.success ? result.data : null;
                  this.physicalPersonCanPersist = !!(
                    customer &&
                    customer.id &&
                    this.item &&
                    this.item.id &&
                    customer.id.toString() === this.item.id.toString()
                  );
                })
                .catch(() => {
                  this.physicalPersonCanPersist = false;
                });
            } else if (data.document && data.document.type) {
              const docType = data.document.type.toString().toUpperCase();
              this.item.personType =
                docType === "CNPJ" || docType === "PJ" ? "PJ" : "PF";
            }

          }

          return hasErrors === false ? data : false;
        })
        .catch((error) => {
          this.isNewPeople = true;
          this.isPersonDataLocked = false;
          this.physicalPersonCanPersist = false;
          this.notifyError(error.message);
        })
        .finally(() => {
          this.loadingContact = false;
        });
    },

    notifyError(message) {
      this.$q.notify({
        message: message,
        position: "bottom",
        type: "negative",
      });
    },

    getGeoPlaces(input) {
      this.isSearching = true;

      return this.geoplace(input).then((result) => {
        this.isSearching = false;

        if (result.success) {
          let items = [];
          for (let i = 0; i < result.data.length; i++) {
            items.push({
              label: result.data[i].description,
              value: result.data[i],
            });
          }
          return items;
        } else {
          this.$q.notify({
            message: this.$t("messages.gmapsReqNoData"),
            type: "negative",
            position: "bottom",
          });
        }
      });
    },

    onSelect(item) {
      this.resetFormValidation();
      this.setAddress({
        country: item.country,
        state: item.state,
        city: item.city,
        district: item.district,
        postalCode: item.postal_code,
        street: item.street,
        number: item.number,
      });
    },

    reset() {
      this.resetFormValidation();

      this.contactSelected = null;
      this.contacts = [];
      this.isDataLocked = false;
      this.companiesOptions = [];
      this.selectedCompanyId = null;
      this.lastContactData = null;
      this.isPersonDataLocked = false;
      this.physicalPersonCanPersist = false;
      this.noRecipientContactData = false;
      this.item.id = null;
      this.item.name = null;
      this.item.alias = null;
      this.item.document = null;
      this.item.contact.id = null;
      this.item.contact.name = null;
      this.item.contact.email = null;
      this.item.contact.phone = null;
      if (this.dialogs && this.dialogs.physicalPerson) {
        this.dialogs.physicalPerson.visible = false;
      }
    },

    setAddress(data) {
      if (!data) return;

      this.item.address.id = data.id ? data.id : null;
      this.item.address.country = data.country;
      this.item.address.state = data.state;
      this.item.address.city = data.city;
      this.item.address.district = data.district;
      this.item.address.postal_code = data.postalCode;
      this.item.address.street = data.street;
      this.item.address.number = data.number ? data.number.toString() : "";
      this.item.address.complement = data.complement ? data.complement : "";
    },

    isInvalid(key) {
      return (val) => {
        if (key == "optionalPhone" && !(val && val.length > 0)) return true;

        if (!(val && val.length > 0)) return this.$t("messages.fieldRequired");

        if (key == "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val))
          return this.$t("messages.emailInvalid");

        if (key == "phone") {
          const digits = (val || '').replace(/\D/g, '');
          if (!(digits.length >= 10 && digits.length <= 11))
            return this.$t("messages.phoneInvalid");
        }

        if (key == "optionalPhone") {
          const digits = (val || '').replace(/\D/g, '');
          if (digits.length > 0 && !(digits.length >= 10 && digits.length <= 11))
            return this.$t("messages.phoneInvalid");
        }

        if (key == "document") {
          const digits = (val || '').replace(/\D/g, '');
          const expectedLength = this.item.personType == "PJ" ? 14 : 11;
          if (digits.length !== expectedLength) return "Documento inválido";
        }

        return true;
      };
    },

    ensurePhysicalPersonContactName(data) {
      if (this.noRecipientContactData) return;
      if (!data || data.personType !== "PF" || !data.name) return;
      this.ensureContactShape();
      data.contact.name = data.name;
    },

    validatePhysicalPersonContact(data) {
      if (this.noRecipientContactData) return true;
      if (!data || data.personType !== "PF") return true;

      const contact = data.contact || {};
      const name = (contact.name || data.name || "").toString().trim();
      const email = (contact.email || "").toString().trim();
      const phone = this.normalizePhoneDigits(contact.phone);

      if (!name) {
        this.notifyError("Informe o nome da pessoa física.");
        return false;
      }
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        this.notifyError("Informe um e-mail válido para a pessoa física.");
        return false;
      }
      if (phone && !(phone.length >= 10 && phone.length <= 11)) {
        this.notifyError("Informe um telefone válido para a pessoa física.");
        return false;
      }

      data.contact.name = name;
      data.contact.email = email;
      data.contact.phone = phone || null;
      return true;
    },

    clearContactData() {
      this.ensureContactShape();
      this.contactSelected = null;
      this.item.contact.id = null;
      this.item.contact.name =
        this.item.personType === "PF" && this.item.name ? this.item.name : null;
      this.item.contact.email = null;
      this.item.contact.phone = null;
      if (this.dialogs && this.dialogs.collaborator) {
        this.dialogs.collaborator.visible = false;
      }
      if (this.dialogs && this.dialogs.physicalPerson) {
        this.dialogs.physicalPerson.visible = false;
      }
      this.resetFormValidation();
    },

    resetFormValidation() {
      this.$nextTick(() => {
        if (this.$refs.myForm && this.$refs.myForm.resetValidation) {
          this.$refs.myForm.resetValidation();
        }
      });
    },

    cancelCreateAddress() {
      this.showCreateAddressDialog = false;
      this.newAddress.postal_code = '';
    },
  },
};

</script>

<style scoped lang="scss">
.form-section {
  background: #ffffff;
  border: 1px solid #dbe3ef;
  border-left: 4px solid $primary;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(16, 42, 67, 0.06);
  padding: 0.4rem 0.75rem 0.6rem;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 0.45rem;
  padding-bottom: 0.35rem;
  border-bottom: 1px solid #edf2f7;
}

.section-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background-color: $primary;
  color: white;
  border-radius: 50%;
  font-weight: bold;
  font-size: 0.9rem;
  flex-shrink: 0;
}

.section-title {
  font-size: 1rem;
  font-weight: 600;
  color: #1f2f46;
  margin: 0;
}

.form-section :deep(.q-field__control) {
  border-radius: 8px;
}

// .address-grid {
//   background-color: #f5f5f5;
//   padding: 0.75rem;
//   border-radius: 4px;
// }

// .form-footer {
//   border-top: 1px solid #e0e0e0;
//   padding-top: 2rem;
//   padding-bottom: 2rem;
// }

.address-btn-container {
  display: flex;
  align-items: stretch;
}

.address-btn-container .q-btn {
  min-width: 120px;
  padding: 0 1.5rem !important;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
}

.selection-inline {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  background: #f7f8fa;
  padding: 0.65rem 0.85rem;
}

.selection-inline.is-other {
  border-color: $warning;
  background: #fff7e0;
}

.selection-inline-title {
  font-size: 0.85rem;
  font-weight: 700;
  color: $dark;
  margin-bottom: 0.2rem;
}

.selection-inline-text {
  font-size: 0.8rem;
  color: #5f6670;
}

.contact-required-box {
  border: 1px solid #cbd6e5;
  border-radius: 10px;
  background: #f8fbff;
  padding: 0.85rem;
}

.contact-box-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}

.contact-box-actions {
  display: flex;
  align-items: center;
  gap: 0.35rem;
  flex-shrink: 0;
}

.contact-box-title {
  font-size: 0.9rem;
  font-weight: 700;
  color: #1f2f46;
}

.contact-box-text {
  font-size: 0.8rem;
  color: #5f6670;
  margin-top: 0.15rem;
}
</style>
