<script setup lang="ts">
// 로그인 — 좌측 브랜드 패널 + 우측 로그인 폼
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import RelayMark from '@/components/RelayMark.vue'
import { useAuthStore } from '@/stores/auth.store'
import { useDialog } from '@/composables/useDialog'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const dialog = useDialog()

// 폼 상태
const email = ref('')
const password = ref('')
const showPassword = ref(false)
const keepLogin = ref(true)
const submitting = ref(false)

// 상단 안내 배너 — 이메일 인증(/login?verified=1|0) 또는 비밀번호 재설정 완료(/login?reset=1)
const verifyBanner = computed<{ ok: boolean; text: string } | null>(() => {
  if (route.query.reset === '1')
    return { ok: true, text: '비밀번호가 변경되었습니다. 새 비밀번호로 로그인해 주세요.' }
  const v = route.query.verified
  if (v === '1') return { ok: true, text: '이메일 인증이 완료되었습니다. 로그인해 주세요.' }
  if (v === '0')
    return {
      ok: false,
      text: '인증 링크가 만료되었거나 유효하지 않습니다. 인증 메일을 다시 받아 주세요.',
    }
  return null
})

// 로그인 처리 — 성공 시 항상 프로젝트 목록으로 진입(이전 화면/딥링크로 복귀하지 않음)
async function onLogin() {
  if (submitting.value) return
  submitting.value = true
  try {
    // silent: 미인증(403)은 토스트 없이 화면 전환으로 처리하므로 전역 에러 알림을 끈다
    await authStore.login(
      {
        email: email.value.trim(),
        password: password.value,
        keepLogin: keepLogin.value,
      },
      { silent: true },
    )
    await router.push('/projects')
  } catch (err) {
    const res = (
      err as { response?: { status?: number; data?: { error?: { message?: string } } } }
    )?.response
    // 미인증 계정(서버 403) → 인증 메일을 즉시 발송하고 '발송 완료' 화면으로 조용히 이동
    if (res?.status === 403) {
      const addr = email.value.trim()
      try {
        await authStore.resendVerification(addr)
      } catch {
        // 재발송 실패는 무시(화면 전환 우선)
      }
      await router.push({ path: '/signup', query: { sent: addr } })
      return
    }
    // 그 외(자격 불일치 등) — 서버 메시지를 직접 안내
    void dialog.alert(
      res?.data?.error?.message ?? '이메일 또는 비밀번호가 올바르지 않습니다.',
      { variant: 'danger' },
    )
  } finally {
    submitting.value = false
  }
}

// 소셜 로그인 — 백엔드 OAuth 엔드포인트로 전체 페이지 이동(쿠키 기반 세션이라 새 창 X)
const apiBase = import.meta.env.VITE_API_BASE_URL || '/api'
function goSocial(provider: 'google' | 'kakao') {
  window.location.href = `${apiBase}/auth/${provider}`
}

// 브랜드 패널 강조 포인트
const points = [
  '프로젝트 · 업무 · 담당자로 이어지는 명확한 구조',
  '체크리스트와 마감기한으로 진행 관리',
  '역할 기반 권한으로 안전하게 관리',
]
</script>

<template>
  <div class="auth">
    <!-- 브랜드 패널 -->
    <aside class="brand-panel">
      <div class="blob b1" />
      <div class="blob b2" />
      <div class="ring" />
      <div class="bp-logo">
        <span class="logo"><RelayMark white /></span> Relay
      </div>
      <div class="bp-body">
        <div class="bp-head">
          지시부터 완료까지,<br>팀의 업무 흐름을 하나로
        </div>
        <div class="bp-sub">
          프로젝트 단위로 업무를 정리하고, 담당자에게 명확하게 지시하세요. 진행 상황은 한눈에
          추적됩니다.
        </div>
        <div class="bp-points">
          <div
            v-for="point in points"
            :key="point"
            class="bp-point"
          >
            <span class="ic">
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="3"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </span>
            {{ point }}
          </div>
        </div>
      </div>
      <div class="bp-foot">
        © 2026 Relay · 사내 업무 지시 플랫폼
      </div>
    </aside>

    <!-- 폼 패널 -->
    <main class="form-panel">
      <div class="auth-card">
        <div class="ac-logo">
          <span class="logo"><RelayMark white /></span> Relay
        </div>
        <h1 class="ac-title">
          로그인
        </h1>
        <p class="ac-sub">
          업무 지시를 시작하려면 로그인하세요.
        </p>

        <!-- 이메일 인증 결과 배너 -->
        <div
          v-if="verifyBanner"
          class="verify-banner"
          :class="{ err: !verifyBanner.ok }"
          role="status"
        >
          <svg
            v-if="verifyBanner.ok"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="3"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <path d="M20 6 9 17l-5-5" />
          </svg>
          <svg
            v-else
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2.4"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <circle
              cx="12"
              cy="12"
              r="10"
            /><path d="M15 9l-6 6M9 9l6 6" />
          </svg>
          {{ verifyBanner.text }}
        </div>

        <!-- 소셜 로그인 -->
        <div class="socials">
          <button
            class="sbtn"
            type="button"
            @click="goSocial('google')"
          >
            <span class="sico">
              <svg
                width="20"
                height="20"
                viewBox="0 0 48 48"
              >
                <path
                  fill="#FFC107"
                  d="M43.6 20.5H42V20H24v8h11.3C33.7 32.4 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 6.5 29.5 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.3-.4-3.5z"
                />
                <path
                  fill="#FF3D00"
                  d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 6.5 29.5 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"
                />
                <path
                  fill="#4CAF50"
                  d="M24 44c5.4 0 10.3-2.1 14-5.4l-6.5-5.5C29.6 34.6 26.9 36 24 36c-5.2 0-9.6-3.5-11.2-8.3l-6.5 5C9.6 39.6 16.2 44 24 44z"
                />
                <path
                  fill="#1976D2"
                  d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.1-4.1 5.5l6.5 5.5C41.4 36 44 30.5 44 24c0-1.3-.1-2.3-.4-3.5z"
                />
              </svg>
            </span>
            Google로 계속하기
          </button>
          <button
            class="sbtn kakao"
            type="button"
            @click="goSocial('kakao')"
          >
            <span class="sico">
              <svg
                width="19"
                height="19"
                viewBox="0 0 24 24"
                fill="#191600"
              >
                <path d="M12 3C6.5 3 2 6.5 2 10.8c0 2.8 1.9 5.2 4.7 6.6-.2.7-.7 2.6-.8 3-.1.5.2.5.4.4.2-.1 2.6-1.8 3.7-2.5.6.1 1.3.1 2 .1 5.5 0 10-3.5 10-7.8C22 6.5 17.5 3 12 3z" />
              </svg>
            </span>
            카카오로 계속하기
          </button>
        </div>

        <div class="divider">
          또는 이메일로 로그인
        </div>

        <!-- 이메일 로그인 -->
        <form @submit.prevent="onLogin">
          <div class="field">
            <label
              class="flabel"
              for="login-email"
            >이메일</label>
            <input
              id="login-email"
              v-model="email"
              class="tinput"
              type="email"
              placeholder="name@acme.co"
              autocomplete="email"
            >
          </div>
          <div class="field">
            <label
              class="flabel"
              for="login-pw"
            >비밀번호</label>
            <div class="pw-wrap">
              <input
                id="login-pw"
                v-model="password"
                class="tinput"
                :type="showPassword ? 'text' : 'password'"
                placeholder="비밀번호 입력"
                autocomplete="current-password"
              >
              <button
                class="pw-toggle"
                type="button"
                :title="showPassword ? '비밀번호 숨기기' : '비밀번호 표시'"
                :aria-label="showPassword ? '비밀번호 숨기기' : '비밀번호 표시'"
                @click="showPassword = !showPassword"
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                  <circle
                    cx="12"
                    cy="12"
                    r="3"
                  />
                </svg>
              </button>
            </div>
          </div>

          <div class="options">
            <button
              class="keep"
              type="button"
              @click="keepLogin = !keepLogin"
            >
              <span
                class="box"
                :class="{ on: keepLogin }"
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="3.5"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                >
                  <path d="M20 6 9 17l-5-5" />
                </svg>
              </span>
              로그인 상태 유지
            </button>
            <RouterLink
              class="link"
              to="/forgot-password"
            >
              비밀번호 찾기
            </RouterLink>
          </div>

          <button
            class="submit"
            type="submit"
            :disabled="submitting"
          >
            {{ submitting ? '로그인 중…' : '로그인' }}
          </button>
        </form>

        <div class="signup">
          계정이 없으신가요? <RouterLink to="/signup">
            회원가입
          </RouterLink>
        </div>
        <div class="verify-note">
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <path d="M22 6 12 13 2 6" />
            <rect
              x="2"
              y="4"
              width="20"
              height="16"
              rx="2"
            />
          </svg>
          이메일 회원가입은 인증 메일 확인 후 완료됩니다
        </div>
      </div>
    </main>
  </div>
</template>

<style scoped>
/* 로그인 화면은 본문보다 큰 모서리 반경을 사용 */
.auth {
  --radius: 8px;
  display: flex;
  min-height: 100vh;
}

/* ---- 브랜드 패널 ---- */
.brand-panel {
  flex: 0 0 46%;
  max-width: 38.75rem;
  position: relative;
  overflow: hidden;
  background: linear-gradient(155deg, #4f46e5 0%, #4338ca 52%, #2e2a8f 100%);
  color: #fff;
  padding: 2.75rem 3rem;
  display: flex;
  flex-direction: column;
}
.brand-panel .blob {
  position: absolute;
  border-radius: 50%;
  filter: blur(2px);
  pointer-events: none;
}
.brand-panel .b1 {
  width: 22.5rem;
  height: 22.5rem;
  right: -7.5rem;
  top: -5.625rem;
  background: rgba(255, 255, 255, 0.1);
}
.brand-panel .b2 {
  width: 16.25rem;
  height: 16.25rem;
  left: -5.625rem;
  bottom: -4.375rem;
  background: rgba(255, 255, 255, 0.07);
}
.brand-panel .ring {
  position: absolute;
  right: 3.75rem;
  bottom: 5rem;
  width: 11.25rem;
  height: 11.25rem;
  border: 1.5px solid rgba(255, 255, 255, 0.14);
  border-radius: 50%;
}
.brand-panel .ring::after {
  content: '';
  position: absolute;
  inset: 2.125rem;
  border: 1.5px solid rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}
.bp-logo {
  display: flex;
  align-items: center;
  gap: 0.625rem;
  font-weight: 700;
  font-size: 1.125rem;
  letter-spacing: -0.0125rem;
  position: relative;
  z-index: 1;
}
.bp-logo .logo {
  width: 2rem;
  height: 2rem;
  border-radius: 0.5625rem;
  background: rgba(255, 255, 255, 0.16);
  border: 1px solid rgba(255, 255, 255, 0.22);
  display: grid;
  place-items: center;
  font-size: 1.0625rem;
  font-weight: 800;
}
.bp-body {
  margin-top: auto;
  position: relative;
  z-index: 1;
}
.bp-head {
  font-size: 2.125rem;
  font-weight: 700;
  line-height: 1.32;
  letter-spacing: -0.05rem;
  text-wrap: balance;
}
.bp-sub {
  margin-top: 1.125rem;
  font-size: 0.9375rem;
  line-height: 1.7;
  color: rgba(255, 255, 255, 0.82);
  max-width: 25rem;
}
.bp-points {
  margin-top: 1.875rem;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}
.bp-point {
  display: flex;
  align-items: center;
  gap: 0.6875rem;
  font-size: 0.875rem;
  color: rgba(255, 255, 255, 0.92);
}
.bp-point .ic {
  width: 1.375rem;
  height: 1.375rem;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.16);
  display: grid;
  place-items: center;
  flex-shrink: 0;
}
.bp-point .ic svg {
  width: 0.8125rem;
  height: 0.8125rem;
}
.bp-foot {
  margin-top: 2.5rem;
  font-size: 0.781rem;
  color: rgba(255, 255, 255, 0.6);
  position: relative;
  z-index: 1;
}

/* ---- 폼 패널 ---- */
.form-panel {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2.5rem 1.5rem;
}
.auth-card {
  width: 100%;
  max-width: 24rem;
}
.ac-logo {
  display: none;
}
.ac-title {
  font-size: 1.5rem;
  font-weight: 700;
  letter-spacing: -0.03125rem;
}
.ac-sub {
  color: var(--text-2);
  font-size: 0.875rem;
  margin-top: 0.4375rem;
}

.verify-banner {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 1.5rem;
  padding: 0.6875rem 0.875rem;
  border-radius: var(--radius);
  font-size: 0.8125rem;
  font-weight: 600;
  line-height: 1.45;
  color: #1b7a3d;
  background: var(--green-weak);
  border: 1px solid var(--green-border);
}
.verify-banner.err {
  color: var(--red);
  background: var(--red-weak);
  border-color: var(--red-border);
}
.verify-banner svg {
  width: 1rem;
  height: 1rem;
  flex-shrink: 0;
}
.socials {
  display: flex;
  flex-direction: column;
  gap: 0.625rem;
  margin-top: 1.75rem;
}
.sbtn {
  height: 2.875rem;
  border-radius: var(--radius);
  border: 1px solid var(--border-strong);
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.625rem;
  cursor: pointer;
  font-family: inherit;
  font-size: 0.906rem;
  font-weight: 600;
  color: var(--text);
  text-decoration: none;
  position: relative;
  transition:
    background 0.12s,
    border-color 0.12s;
}
.sbtn:hover {
  background: #f7f8fa;
}
.sbtn .sico {
  position: absolute;
  left: 1rem;
  display: grid;
  place-items: center;
}
.sbtn.kakao {
  background: var(--kakao);
  border-color: var(--kakao);
  color: var(--kakao-text);
}
.sbtn.kakao:hover {
  background: #f2d900;
}

.divider {
  display: flex;
  align-items: center;
  gap: 0.875rem;
  margin: 1.375rem 0;
  color: var(--text-3);
  font-size: 0.781rem;
}
.divider::before,
.divider::after {
  content: '';
  height: 1px;
  background: var(--border);
  flex: 1;
}

.field {
  margin-bottom: 0.875rem;
}
.flabel {
  font-size: 0.8125rem;
  font-weight: 600;
  color: var(--text-2);
  margin-bottom: 0.4375rem;
  display: block;
}
.tinput {
  width: 100%;
  height: 2.75rem;
  border: 1px solid var(--border-strong);
  border-radius: var(--radius);
  padding: 0 0.8125rem;
  font-family: inherit;
  font-size: 0.875rem;
  color: var(--text);
  background: #fff;
}
.tinput:focus {
  outline: none;
  border-color: var(--accent);
  box-shadow: 0 0 0 3px var(--accent-weak);
}
.tinput::placeholder {
  color: var(--text-3);
}
.pw-wrap {
  position: relative;
}
.pw-wrap .tinput {
  padding-right: 2.75rem;
}
.pw-toggle {
  position: absolute;
  right: 0.375rem;
  top: 50%;
  transform: translateY(-50%);
  width: 2.125rem;
  height: 2.125rem;
  border: none;
  background: transparent;
  color: var(--text-3);
  display: grid;
  place-items: center;
  cursor: pointer;
  border-radius: 0.375rem;
}
.pw-toggle:hover {
  background: #f1f2f4;
  color: var(--text-2);
}
.pw-toggle svg {
  width: 1.125rem;
  height: 1.125rem;
}

.options {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0.25rem 0 1.375rem;
}
.keep {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  font-size: 0.8125rem;
  color: var(--text-2);
  user-select: none;
  white-space: nowrap;
  background: none;
  border: none;
  font-family: inherit;
  padding: 0;
}
.keep .box {
  width: 1.0625rem;
  height: 1.0625rem;
  border-radius: 0.3125rem;
  border: 1.5px solid var(--border-strong);
  display: grid;
  place-items: center;
  background: #fff;
}
.keep .box.on {
  background: var(--accent);
  border-color: var(--accent);
}
.keep .box svg {
  width: 0.6875rem;
  height: 0.6875rem;
  color: #fff;
  opacity: 0;
}
.keep .box.on svg {
  opacity: 1;
}
.link {
  color: var(--accent);
  font-size: 0.8125rem;
  font-weight: 600;
  text-decoration: none;
  white-space: nowrap;
}
.link:hover {
  text-decoration: underline;
}

.submit {
  width: 100%;
  height: 2.875rem;
  border-radius: var(--radius);
  border: none;
  background: var(--accent);
  color: #fff;
  font-family: inherit;
  font-size: 0.9375rem;
  font-weight: 700;
  cursor: pointer;
  box-shadow: 0 1px 2px rgba(79, 70, 229, 0.4);
}
.submit:hover {
  background: var(--accent-hover);
}

.signup {
  margin-top: 1.5rem;
  text-align: center;
  font-size: 0.844rem;
  color: var(--text-2);
}
.signup a {
  color: var(--accent);
  font-weight: 600;
  text-decoration: none;
}
.signup a:hover {
  text-decoration: underline;
}
.verify-note {
  margin-top: 0.375rem;
  text-align: center;
  font-size: 0.75rem;
  color: var(--text-3);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.3125rem;
}
.verify-note svg {
  width: 0.8125rem;
  height: 0.8125rem;
}

/* 좁은 화면 — 브랜드 패널 숨기고 카드 로고 노출 */
@media (max-width: 55rem) {
  .brand-panel {
    display: none;
  }
  .ac-logo {
    display: flex;
    align-items: center;
    gap: 0.5625rem;
    font-weight: 700;
    font-size: 1.0625rem;
    margin-bottom: 1.625rem;
  }
  .ac-logo .logo {
    width: 1.75rem;
    height: 1.75rem;
    border-radius: 0.5rem;
    background: linear-gradient(135deg, #5b54f0, #4338ca);
    display: grid;
    place-items: center;
    color: #fff;
    font-size: 0.9375rem;
    font-weight: 800;
  }
}
</style>
