<template>
  <a-spin :spinning="loading">
    <div class="section-container">
      <div class="page">
        <!-- Topbar -->
        <div class="topbar">
          <div class="topbarLeft">
            <div class="hello">Bienvenido, {{ authStore.userName }}</div>
            <div class="sub">DNI: {{ authStore.userDni || "No registrado" }}</div>
          </div>

          <!-- Estado observado (DERECHA) -->
          <div class="topbarRight" v-if="esObservado !== null">
            <div
              class="statusPill"
              :class="esObservado ? 'statusBad' : 'statusOk'"
              :title="mensaje"
            >
              <span class="statusDot" />
              <span class="statusText">
                {{ esObservado ? "Observado" : "Apto" }}
              </span>
            </div>

            <div class="statusMsg" :class="esObservado ? 'msgBad' : 'msgOk'">
              {{ mensaje }}
            </div>
          </div>
        </div>

        <a-divider class="softDivider" />

        <!-- Test -->
        <a-card :bordered="false" class="testBox">
          <div class="testHead">
            <div class="testHeadLeft">
              <div class="testTitle">Tu test diagnóstico</div>
              <div class="testSub">
                Es un <b>test referencial</b> para practicar y medir tu nivel. <b>No afecta</b> tu postulación oficial.
              </div>

              <div class="mt12">
                <a-space direction="vertical" size="small">
                  <div class="bulletRow">
                    <span class="dot" />
                    <span>10 preguntas • 10 min aprox. • resultado inmediato</span>
                  </div>
                  <div class="bulletRow">
                    <span class="dot" />
                    <span>
                      Si el test pide secuencia, también puedes usar la del pago de tu
                      <b>Carpeta de Postulante</b> (no pagas extra por este test).
                    </span>
                  </div>
                </a-space>
              </div>
            </div>

            <div class="testHeadRight">
              <a-button
                type="primary"
                size="large"
                class="btnTest"
                :disabled="!canGoTest"
                @click="goToTest"
                block
              >
                Ir al test
              </a-button>

              <div class="microHelp" v-if="!canGoTest">Aún no tienes un test asignado.</div>
            </div>
          </div>
        </a-card>

        <a-divider class="softDivider" />

        <!-- Procesos -->
        <div class="sectionHead">
          <div>
            <div class="sectionTitle">Procesos activos</div>
            <div class="sectionSub">Revisa los procesos habilitados y postula cuando corresponda.</div>
          </div>

          <div class="sectionRight">
            <a-badge count="Nuevo" class="new-badge" />
          </div>
        </div>

        <div class="tableWrap mt12">
          <a-table
            :columns="processColumns"
            :data-source="state.processes"
            row-key="id"
            :loading="loading"
            :pagination="{ pageSize: 6 }"
            :scroll="{ x: 720 }"
            class="modernTable"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'fecha_inicio_preinscripcion'">
                {{ formatDate(record.fecha_inicio_preinscripcion) }}
              </template>

              <template v-else-if="column.key === 'fecha_fin_preinscripcion'">
                {{ formatDate(record.fecha_fin_preinscripcion) }}
              </template>

              <template v-else-if="column.key === 'actions'">
                <div class="actions">
                  <a-button
                    size="small"
                    type="primary"
                    block
                    class="actionBtnPrimary"
                    :disabled="!record.link_preinscripcion || esObservado === true"
                    @click="onApply(record)"
                  >
                    Postular
                  </a-button>
                </div>
              </template>
            </template>
          </a-table>
        </div>

        <a-empty
          v-if="!loading && state.processes.length === 0"
          class="mt12"
          description="No hay procesos activos por el momento."
        />
      </div>
    </div>
  </a-spin>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { Modal } from "ant-design-vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "../../store/postulanteStore";
import axios from "../../axiosPostulante";

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

const loading = ref(false);
const canApply = computed(() => esObservado.value === false);
// estado observado
const esObservado = ref(null);
const mensaje = ref("");

const state = reactive({
  test: { hasAssigned: true },
  processes: [],
});

const canGoTest = computed(() => !!state.test.hasAssigned);

const processColumns = computed(() => [
  { title: "Título", dataIndex: "titulo", key: "titulo", ellipsis: true },
  { title: "Inicio preinscripción", dataIndex: "fecha_inicio_preinscripcion", key: "fecha_inicio_preinscripcion" },
  { title: "Fin preinscripción", dataIndex: "fecha_fin_preinscripcion", key: "fecha_fin_preinscripcion" },
  { title: "Acciones", key: "actions" },
]);

function formatDate(val) {
  if (!val) return "-";
  if (typeof val === "string" && val.includes("T")) return val.split("T")[0];
  const d = new Date(val);
  if (isNaN(d.getTime())) return String(val);
  return d.toLocaleDateString();
}

const api = {
  async getProcesosActivos() {
    const { data } = await axios.get("/procesos-disponibles-preinscripcion");
    return data;
  },
};

async function fetchDashboard() {
  loading.value = true;
  try {
    const resp = await api.getProcesosActivos();
    state.processes = Array.isArray(resp?.data) ? resp.data : [];
  } catch (e) {
    console.error(e);
    state.processes = [];
  } finally {
    loading.value = false;
  }
}

function goToTest() {
  if (!canGoTest.value) return;

  Modal.confirm({
    title: "Test diagnóstico",
    content: "Este test es referencial y no afecta tu postulación. ¿Deseas continuar?",
    okText: "Continuar",
    cancelText: "Cancelar",
    onOk() {
      router.push("/portal-postulante/test");
    },
  });
}

function onApply(process) {
  if (!process.link_preinscripcion) return;
  window.open(process.link_preinscripcion, "_blank", "noopener,noreferrer");
}

onMounted(async () => {
  // Observación (derecha)
  const r = await authStore.getObservacion();
  if (r?.success) {
    esObservado.value = r.es_observado;
    mensaje.value = r.mensaje;
  } else {
    esObservado.value = null;
    mensaje.value = "";
  }
});

onMounted(fetchDashboard);
</script>

<style scoped>
/* ====== BASE ====== */
.section-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.page {
  width: 100%;
  max-width: 1120px;
  margin: 0 auto;
}

.mt12 { margin-top: 12px; }
.microHelp { font-size: 12px; color: #6b7280; margin-top: 8px; }
.softDivider { margin: 16px 0; }

/* ====== TOPBAR ====== */
.topbar {
  display: flex;
  justify-content: space-between;
  gap: 14px;
  flex-wrap: wrap;
  align-items: flex-start;
}

.topbarRight {
  display: grid;
  gap: 8px;
  justify-items: end;
  text-align: right;
}

.hello {
  font-size: 28px;
  font-weight: 900;
  color: #0f172a;
  margin: 0;
  letter-spacing: 0.2px;
}

.sub {
  margin-top: 6px;
  font-size: 14px;
  color: #64748b;
}

/* estado */
.statusPill {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-radius: 999px;
  font-weight: 900;
  font-size: 12px;
  border: 1px solid rgba(15, 23, 42, 0.12);
  background: rgba(15, 23, 42, 0.03);
}

.statusDot {
  width: 10px;
  height: 10px;
  border-radius: 999px;
  background: currentColor;
}

.statusOk {
  color: #16a34a;
  border-color: rgba(22, 163, 74, 0.25);
  background: rgba(22, 163, 74, 0.08);
}

.statusBad {
  color: #dc2626;
  border-color: rgba(220, 38, 38, 0.25);
  background: rgba(220, 38, 38, 0.08);
}

.statusMsg {
  max-width: 340px;
  font-size: 12px;
  color: #64748b;
  line-height: 1.35;
}

.msgOk { color: #166534; }
.msgBad { color: #7f1d1d; }

/* ====== TEST CARD ====== */
.testBox {
  border: 1px solid rgba(15, 23, 42, 0.08);
  border-radius: 18px;
  box-shadow: 0 10px 24px rgba(15, 23, 42, 0.06);
  background: #fff;
}

.testBox :deep(.ant-card-body) {
  padding: 24px;
}

.testHead {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 18px;
  align-items: start;
}

.testTitle {
  font-size: 20px;
  font-weight: 900;
  color: #0f172a;
}

.testSub {
  margin-top: 8px;
  font-size: 14px;
  color: #475569;
  line-height: 1.6;
  max-width: 760px;
}

.testHeadRight {
  display: grid;
  gap: 8px;
  align-content: start;
}

.btnTest {
  height: 48px;
  border-radius: 12px;
  font-weight: 900;
  border: none;
}

/* bullets */
.bulletRow {
  display: flex;
  gap: 10px;
  align-items: flex-start;
  font-size: 14px;
  color: #475569;
  line-height: 1.6;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 999px;
  background: #1677ff;
  margin-top: 9px;
  flex: 0 0 auto;
}

/* ====== SECTION HEAD ====== */
.sectionHead {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
  align-items: flex-start;
}

.sectionTitle {
  font-size: 20px;
  font-weight: 900;
  color: #0f172a;
  margin: 0;
}

.sectionSub {
  margin-top: 6px;
  font-size: 14px;
  color: #64748b;
  line-height: 1.6;
}

.new-badge :deep(.ant-badge-count) {
  background: linear-gradient(45deg, #ff6b6b, #ffd700);
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.25);
  border-radius: 999px;
}

/* ====== TABLE WRAP ====== */
.tableWrap {
  width: 100%;
  overflow-x: auto;
  border-radius: 18px;
  border: 1px solid rgba(15, 23, 42, 0.08);
  box-shadow: 0 10px 24px rgba(15, 23, 42, 0.06);
  background: #fff;
  padding: 8px;
}

:deep(.modernTable .ant-table) {
  background: transparent;
}

:deep(.modernTable .ant-table-container) {
  overflow-x: auto;
  border-radius: 14px;
}

:deep(.modernTable .ant-table-thead > tr > th) {
  background: rgba(15, 23, 42, 0.03);
  color: #0f172a;
  font-weight: 900;
}

:deep(.modernTable .ant-table-tbody > tr > td) {
  color: #475569;
}

.actions {
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
}

.actionBtnPrimary {
  border-radius: 10px;
  height: 36px;
  font-weight: 900;
}

/* ====== RESPONSIVE ====== */
@media (max-width: 992px) {
  .section-container {
    padding: 0 16px;
  }

  .testHead {
    grid-template-columns: 1fr;
  }

  .testHeadRight {
    justify-items: stretch;
  }

  .topbarRight {
    width: 100%;
    justify-items: start;
    text-align: left;
  }

  .statusMsg {
    max-width: 100%;
  }
}

@media (max-width: 768px) {
  .section-container {
    max-width: none;
    padding: 0 !important;
    margin: 0 !important;
  }

  .page {
    max-width: none;
    margin: 0;
    padding: 0;
  }

  .softDivider {
    margin: 12px 0;
  }

  .hello {
    font-size: 22px;
  }

  /* card full width en móvil */
  .testBox,
  .tableWrap {
    border-radius: 0;
    border-left: 0;
    border-right: 0;
  }

  .testBox :deep(.ant-card-body) {
    padding: 14px;
  }

  .tableWrap {
    padding: 6px;
  }
}

@media (max-width: 480px) {
  .hello {
    font-size: 20px;
  }
  .testSub,
  .bulletRow,
  .sectionSub {
    font-size: 13px;
  }
}
</style>