<script setup>
import { computed, onMounted, reactive, ref, watch, nextTick } from 'vue'
import AuthDialog from './components/AuthDialog.vue'
import GoalsDashboard from './components/GoalsDashboard.vue'
import MiniCalendar from './components/MiniCalendar.vue'
import PlannerPage from './components/PlannerPage.vue'
import SettingsDashboard from './components/SettingsDashboard.vue'
import StatsDashboard from './components/StatsDashboard.vue'
import {
  clearAuthState,
  fetchCurrentUser,
  login,
  persistAuthState,
  readAuthState,
  signup,
  updatePassword,
  updateProfile,
} from './lib/authClient'
import { createGoal, fetchGoals, updateGoal } from './lib/goalsApi'
import { deletePlannerEntry, fetchPlannerEntries, savePlannerEntry } from './lib/plannerApi'
import {
  createInitialPlannerRecords,
  persistPlannerState,
  readPlannerStorageState,
  restorePlannerUiState,
} from './lib/plannerStorage'

const screenMode = ref('planner')
const viewMode = ref('focus')
const printLayout = ref('single')
const authDialogOpen = ref(false)
const authMode = ref('login')
const authBusy = ref(false)
const authMessage = ref('')
const authToken = ref('')
const currentUser = ref(null)
const goals = ref([])
const goalQuery = ref('')
const goalStatusFilter = ref('all')
const goalBusy = ref(false)
const goalMessage = ref('')
const editingGoalId = ref(null)
const syncStatus = ref('local')
const syncMessage = ref('')
const syncToastVisible = ref(false)
const selectedDate = ref(new Date())
const calendarViewDate = ref(new Date(selectedDate.value))
const statsRangeStart = ref(toKey(new Date(new Date().setDate(new Date().getDate() - 6))))
const statsRangeEnd = ref(toKey(new Date()))
const authForm = reactive({
  nickname: '',
  email: '',
  password: '',
})
const goalForm = reactive({
  title: '',
  targetDate: '',
  activeFrom: '',
  activeUntil: '',
  status: 'active',
})
const profileForm = reactive({
  nickname: '',
  email: '',
})
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
})
const profileBusy = ref(false)
const passwordBusy = ref(false)
const profileMessage = ref('')
const passwordMessage = ref('')

const hours = [
  '6', '7', '8', '9', '10', '11', '12',
  '1', '2', '3', '4', '5',
  '6', '7', '8', '9', '10', '11', '12',
  '1', '2', '3', '4', '5',
]

const timetableCellCount = hours.length * 6
let printPageStyleElement = null
let isHydratingRemoteRecords = false
const syncTimers = new Map()
let syncToastTimer = null

function createEmptyTimetable() {
  return Array.from({ length: timetableCellCount }, () => false)
}

function createTaskLabel(index) {
  return `${index + 1}`.padStart(2, '0')
}

function createTimetableFromRanges(ranges) {
  const timetable = createEmptyTimetable()

  ranges.forEach(([start, end]) => {
    for (let index = start; index <= end; index += 1) {
      timetable[index] = true
    }
  })

  return timetable
}

const plannerSeed = {
  '2026-04-21': {
    dday: 'D-12 LAUNCH',
    comment: '집중 작업 3개만 남기고, 10분 단위로 흐름을 끊지 않기.',
    tasks: [
      { label: '', title: '홈 화면 정보 구조 정리', checked: true },
      { label: '', title: '플래너 페이지 헤더 상태 연결', checked: true },
      { label: '', title: '타임테이블 액티브 블록 설계' },
      { label: '', title: '우측 캘린더 빠른 이동 구현' },
      { label: '', title: '전날 요약 영역 문구 다듬기' },
      { label: '', title: '다음날 할 일 자동 제안 시나리오' },
      { label: '', title: '통계 카드 레이아웃 정리' },
      { label: '', title: '모바일 스택 레이아웃 점검' },
      { label: '', title: '체크박스 인터랙션 연결' },
      { label: '', title: '페이지 넘김 애니메이션 방향 검토' },
      { label: '', title: 'Tailwind 토큰 정리' },
      { label: '', title: 'Vue 컴포넌트 분리 기준 정하기' },
      { label: '', title: '빈 상태 문구 작성' },
      { label: '', title: '주간 리듬 회고 메모 추가' },
      { label: '', title: '디자인 QA 체크리스트 정리' },
    ],
    memo: [
      { label: '', text: '오른쪽 패널은 정보 확인과 이동이 한 번에 되도록 유지.' },
      { label: '', text: '2페이지 보기는 비교용으로 남기고 기본값은 집중 보기로 사용.' },
      { label: '', text: '작업 흐름이 끊기지 않도록 클릭 포인트를 줄이기.' },
    ],
    prevSummary: [
      '어제 완료한 핵심 3개 보기',
      '이전 체크 누적률 78%',
      '막힌 작업 메모 바로 이어보기',
    ],
    nextFocus: [
      '내일 첫 집중 블록 예약',
      '다음날 핵심 3개 자동 복사',
      '미완료 작업만 재정렬',
    ],
    timetable: createTimetableFromRanges([
      [6, 13],
      [24, 32],
      [42, 47],
    ]),
  },
  '2026-04-22': {
    dday: 'D-11 LAUNCH',
    comment: '초반 90분은 구현, 후반은 문장과 사용성 정리에 사용.',
    tasks: [
      { label: '', title: '통계 섹션 수치 실제 계산 연결', checked: true },
      { label: '', title: '날짜 선택 시 상태 동기화' },
      { label: '', title: '다음날 할 일 템플릿 개선' },
      { label: '', title: '2페이지 보기 비교 카피 작성' },
      { label: '', title: '주간 흐름 카드 추가' },
      { label: '', title: '메모 영역 편집 UX 개선' },
      { label: '', title: '프린트 스타일 초안 점검' },
      { label: '', title: '색 대비 보정' },
      { label: '', title: '우측 패널 축약 버전 검토' },
      { label: '', title: '마감용 체크리스트 분리' },
      { label: '', title: '키보드 탐색 흐름 다듬기' },
      { label: '', title: '데이터 구조 문서화' },
      { label: '', title: '테스트 날짜 더미 세트 늘리기' },
      { label: '', title: '브랜드 푸터 위치 확정' },
      { label: '', title: '빈 상태 일러스트 여부 결정' },
    ],
    memo: [
      { label: '', text: '한 화면에 모든 정보를 모으되 시선 이동은 짧게.' },
      { label: '', text: '캘린더는 검색보다 빠른 이동 장치로 동작해야 함.' },
      { label: '', text: '실행 화면은 다이어리 같고, 인터랙션은 앱처럼.' },
    ],
    prevSummary: [
      '이전날 메모 3줄 이어보기',
      '전날 타임블록 밀도 확인',
      '완료율 기준 다음 일정 추천',
    ],
    nextFocus: [
      '다음날 오전 블록 추천',
      '오늘 미완료 작업 넘기기',
      '이번 주 누적 시간 요약',
    ],
    timetable: createTimetableFromRanges([
      [3, 8],
      [18, 23],
      [54, 62],
    ]),
  },
}

function toKey(date) {
  const year = date.getFullYear()
  const month = `${date.getMonth() + 1}`.padStart(2, '0')
  const day = `${date.getDate()}`.padStart(2, '0')
  return `${year}-${month}-${day}`
}

function toDateValue(value, fallback = new Date()) {
  const nextDate = new Date(value)
  return Number.isNaN(nextDate.getTime()) ? new Date(fallback) : nextDate
}

function startOfDay(date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate())
}

function buildFallbackRecord(date) {
  return {
    comment: '',
    goalEnabled: false,
    selectedGoalId: null,
    tasks: Array.from({ length: 15 }, (_, index) => ({
      label: '',
      title: '',
      checked: false,
    })),
    memo: Array.from({ length: 3 }, () => ({
      label: '',
      text: '',
    })),
    prevSummary: ['이전 기록 없음', '새로운 흐름 시작', ''],
    nextFocus: ['다음 집중 블록 준비', '내일의 핵심 3개 정하기', ''],
    timetable: createEmptyTimetable(),
  }
}

function normalizeRecord(record) {
  return {
    ...record,
    goalEnabled: Boolean(record.goalEnabled),
    selectedGoalId: record.selectedGoalId ?? null,
    tasks: record.tasks.map((task, index) => ({
      label: task.label ?? task.id ?? '',
      title: task.title ?? '',
      checked: Boolean(task.checked),
    })),
    memo: record.memo.map((item) => {
      if (typeof item === 'string') {
        return {
          label: '',
          text: item,
        }
      }

      return {
        label: item.label ?? '',
        text: item.text ?? '',
      }
    }),
    timetable: Array.isArray(record.timetable) && record.timetable.length === timetableCellCount
      ? [...record.timetable]
      : createEmptyTimetable(),
  }
}

const plannerRecords = reactive(createInitialPlannerRecords(plannerSeed, normalizeRecord))

restorePlannerUiState({
  selectedDate,
  calendarViewDate,
  statsRangeStart,
  statsRangeEnd,
  toDateValue,
})

function getPlannerRecord(date) {
  const key = toKey(date)

  if (!plannerRecords[key]) {
    plannerRecords[key] = buildFallbackRecord(date)
  }

  return plannerRecords[key]
}

const planner = computed(() => getPlannerRecord(selectedDate.value))

const secondaryDate = computed(() => {
  const next = new Date(selectedDate.value)
  next.setDate(next.getDate() + 1)
  return next
})

const secondaryPlanner = computed(() => getPlannerRecord(secondaryDate.value))

function getDateDisplay(date) {
  const main = `${date.getFullYear()}. ${`${date.getMonth() + 1}`.padStart(2, '0')}. ${`${date.getDate()}`.padStart(2, '0')}.`
  const weekdayMap = ['(일)', '(월)', '(화)', '(수)', '(목)', '(금)', '(토)']
  const weekday = weekdayMap[date.getDay()]
  const weekdayTone =
    date.getDay() === 0 ? 'text-red-500' : date.getDay() === 6 ? 'text-blue-500' : 'text-ink'

  return {
    main,
    weekday,
    weekdayTone,
  }
}

const selectedDateDisplay = computed(() => getDateDisplay(selectedDate.value))
const secondaryDateDisplay = computed(() => getDateDisplay(secondaryDate.value))

const monthLabel = computed(() =>
  `${calendarViewDate.value.getMonth() + 1}`.padStart(2, '0'),
)

const yearLabel = computed(() => `${calendarViewDate.value.getFullYear()}`)

const calendarDays = computed(() => {
  const base = calendarViewDate.value
  const first = new Date(base.getFullYear(), base.getMonth(), 1)
  const start = new Date(first)
  start.setDate(first.getDate() - first.getDay())

  return Array.from({ length: 35 }, (_, index) => {
    const date = new Date(start)
    date.setDate(start.getDate() + index)
    return {
      key: toKey(date),
      label: date.getDate(),
      date,
      isCurrentMonth: date.getMonth() === base.getMonth(),
    }
  })
})

const markedDateKeys = computed(() =>
  Object.entries(plannerRecords)
    .filter(([, record]) => hasPlannerContent(record))
    .map(([key]) => key),
)

const isAuthenticated = computed(() => Boolean(authToken.value && currentUser.value))
const filteredGoals = computed(() => {
  const query = goalQuery.value.trim().toLowerCase()
  return goals.value.filter((goal) => {
    if (goalStatusFilter.value !== 'all' && goal.status !== goalStatusFilter.value) {
      return false
    }

    if (!query) {
      return true
    }

    return goal.title.toLowerCase().includes(query)
  })
})
const activePlannerGoals = computed(() =>
  goals.value
    .filter((goal) => {
      if (goal.status !== 'active' || !goal.activeFrom || !goal.activeUntil) {
        return false
      }

      const selectedKey = toKey(selectedDate.value)
      return selectedKey >= goal.activeFrom && selectedKey <= goal.activeUntil
    })
    .sort((left, right) => {
      const leftDistance = Math.abs(startOfDay(toDateValue(left.targetDate)).getTime() - startOfDay(selectedDate.value).getTime())
      const rightDistance = Math.abs(startOfDay(toDateValue(right.targetDate)).getTime() - startOfDay(selectedDate.value).getTime())
      return leftDistance - rightDistance
    }),
)
const plannerGoal = computed(() => activePlannerGoals.value[0] ?? null)
const plannerDday = computed(() => {
  if (!planner.value.goalEnabled || !plannerGoal.value) {
    return ''
  }

  const targetDate = startOfDay(toDateValue(plannerGoal.value.targetDate))
  const currentDate = startOfDay(selectedDate.value)
  const diffDays = Math.round((targetDate.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000))
  const badge =
    diffDays === 0 ? 'D-DAY' : diffDays > 0 ? `D-${diffDays}` : `D+${Math.abs(diffDays)}`

  return `${badge} ${plannerGoal.value.title}`
})
const showPlannerDday = computed(() =>
  planner.value.goalEnabled && Boolean(plannerGoal.value),
)
const hasActiveGoalForSelectedDate = computed(() => Boolean(plannerGoal.value))

const filledTasks = computed(() =>
  planner.value.tasks.filter((task) => task.title.trim()),
)
const completedTasks = computed(() =>
  filledTasks.value.filter((task) => task.checked).length,
)
const completionRate = computed(() => {
  if (filledTasks.value.length === 0) {
    return 0
  }

  return Math.round((completedTasks.value / filledTasks.value.length) * 100)
})

function formatTotalTime(record) {
  const activeCellCount = record.timetable.filter(Boolean).length
  const totalMinutes = activeCellCount * 10
  const hoursPart = `${Math.floor(totalMinutes / 60)}`.padStart(2, '0')
  const minutesPart = `${totalMinutes % 60}`.padStart(2, '0')

  return `${hoursPart}H ${minutesPart}M`
}

function getFocusedMinutes(record) {
  return record.timetable.filter(Boolean).length * 10
}

function getCompletionRate(record) {
  const activeTasks = record.tasks.filter((task) => task.title.trim())

  if (activeTasks.length === 0) {
    return 0
  }

  const doneTasks = activeTasks.filter((task) => task.checked).length
  return Math.round((doneTasks / activeTasks.length) * 100)
}

function shiftDate(amount) {
  const next = new Date(selectedDate.value)
  next.setDate(next.getDate() + amount)
  selectedDate.value = next
  calendarViewDate.value = new Date(next)
}

function shiftCalendarMonth(amount) {
  const next = new Date(calendarViewDate.value)
  next.setMonth(next.getMonth() + amount)
  calendarViewDate.value = next
}

function shiftCalendarYear(amount) {
  const next = new Date(calendarViewDate.value)
  next.setFullYear(next.getFullYear() + amount)
  calendarViewDate.value = next
}

function selectDate(date) {
  selectedDate.value = new Date(date)
  calendarViewDate.value = new Date(date)
}

function updateComment(record, value) {
  record.comment = value
  schedulePlannerSyncForRecord(record)
}

function updateGoalEnabled(record, value) {
  if (value && !hasActiveGoalForSelectedDate.value) {
    return
  }

  record.goalEnabled = value
  schedulePlannerSyncForRecord(record)
}

function updateTaskLabel(record, { index, value }) {
  record.tasks[index].label = value
  schedulePlannerSyncForRecord(record)
}

function updateTaskTitle(record, { index, value }) {
  record.tasks[index].title = value
  schedulePlannerSyncForRecord(record)
}

function toggleTask(record, index) {
  record.tasks[index].checked = !record.tasks[index].checked
  schedulePlannerSyncForRecord(record)
}

function updateMemo(record, { index, value }) {
  record.memo[index].text = value
  schedulePlannerSyncForRecord(record)
}

function updateMemoLabel(record, { index, value }) {
  record.memo[index].label = value
  schedulePlannerSyncForRecord(record)
}

function updateTimetable(record, nextTimetable) {
  record.timetable = nextTimetable
  schedulePlannerSyncForRecord(record)
}

function hasPlannerContent(record) {
  return Boolean(
    record.comment.trim() ||
    record.tasks.some((task) => task.title.trim() || task.checked) ||
    record.memo.some((item) => item.label.trim() || item.text.trim()) ||
    record.timetable.some(Boolean),
  )
}

const plannerEntries = computed(() =>
  Object.entries(plannerRecords)
    .filter(([, record]) => hasPlannerContent(record))
    .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)),
)

const normalizedStatsRange = computed(() => {
  const todayKey = toKey(new Date())
  const startKey = statsRangeStart.value || todayKey
  const endKey = statsRangeEnd.value || todayKey

  if (startKey <= endKey) {
    return { startKey, endKey }
  }

  return { startKey: endKey, endKey: startKey }
})

const rangeEntries = computed(() =>
  plannerEntries.value.filter(([key]) =>
    key >= normalizedStatsRange.value.startKey && key <= normalizedStatsRange.value.endKey,
  ),
)

const totalFocusedMinutes = computed(() =>
  rangeEntries.value.reduce((total, [, record]) => total + getFocusedMinutes(record), 0),
)

const totalRecordedTasks = computed(() =>
  rangeEntries.value.reduce(
    (total, [, record]) => total + record.tasks.filter((task) => task.title.trim()).length,
    0,
  ),
)

const completedRecordedTasks = computed(() =>
  rangeEntries.value.reduce(
    (total, [, record]) => total + record.tasks.filter((task) => task.title.trim() && task.checked).length,
    0,
  ),
)

const aggregateCompletionRate = computed(() => {
  if (totalRecordedTasks.value === 0) {
    return 0
  }

  return Math.round((completedRecordedTasks.value / totalRecordedTasks.value) * 100)
})

const overviewCards = computed(() => [
  {
    label: 'TOTAL FOCUSED',
    value: formatMinutes(totalFocusedMinutes.value),
    caption: '지금까지 기록된 전체 집중 시간',
  },
  {
    label: 'AVERAGE COMPLETION',
    value: `${aggregateCompletionRate.value}%`,
    caption: '입력된 할 일 기준 전체 평균 완료율',
  },
  {
    label: 'RECORDED DAYS',
    value: `${rangeEntries.value.length}일`,
    caption: '기록이 남아 있는 날짜 수',
  },
  {
    label: 'COMPLETED TASKS',
    value: `${completedRecordedTasks.value}/${totalRecordedTasks.value || 0}`,
    caption: '완료된 할 일과 전체 입력된 할 일 수',
  },
])

function formatMinutes(totalMinutes) {
  const hoursPart = Math.floor(totalMinutes / 60)
  const minutesPart = totalMinutes % 60
  return `${hoursPart}H ${`${minutesPart}`.padStart(2, '0')}M`
}

function createDateLabel(dateKey) {
  const date = toDateValue(dateKey)
  const display = getDateDisplay(date)
  return `${display.main} ${display.weekday}`
}

const weeklyRecords = computed(() => {
  const entries = rangeEntries.value.map(([key, record]) => {
    const date = toDateValue(key)
    const weekdayShort = ['일', '월', '화', '수', '목', '금', '토'][date.getDay()]
    const focusedMinutes = getFocusedMinutes(record)

    return {
      key,
      weekday: weekdayShort,
      focusedMinutes,
      focusedTime: formatMinutes(focusedMinutes),
    }
  })

  if (entries.length === 0) {
    return []
  }

  const maxMinutes = Math.max(...entries.map((entry) => entry.focusedMinutes), 60)

  return entries.map((entry) => ({
    ...entry,
    barHeight: Math.max(12, Math.round((entry.focusedMinutes / maxMinutes) * 100)),
  }))
})

const recentRecords = computed(() =>
  [...rangeEntries.value]
    .sort(([leftKey], [rightKey]) => rightKey.localeCompare(leftKey))
    .slice(0, 5)
    .map(([key, record]) => ({
      key,
      dateLabel: createDateLabel(key),
      comment: record.comment.trim(),
      focusedTime: formatTotalTime(record),
      completionRate: getCompletionRate(record),
    })),
)

const bestDay = computed(() => {
  if (rangeEntries.value.length === 0) {
    return null
  }

  const [bestKey, bestRecord] = [...rangeEntries.value].reduce((bestEntry, currentEntry) => {
    const [, bestRecordValue] = bestEntry
    const [, currentRecordValue] = currentEntry

    return getFocusedMinutes(currentRecordValue) > getFocusedMinutes(bestRecordValue) ? currentEntry : bestEntry
  })

  return {
    dateLabel: createDateLabel(bestKey),
    summary: `${formatTotalTime(bestRecord)} 집중, 완료율 ${getCompletionRate(bestRecord)}%, 코멘트 "${
      bestRecord.comment.trim() || '없음'
    }"`,
  }
})

watch(
  [plannerRecords, selectedDate, calendarViewDate, statsRangeStart, statsRangeEnd],
  () => {
    persistPlannerState({
      plannerRecords,
      selectedDate: selectedDate.value,
      calendarViewDate: calendarViewDate.value,
      statsRangeStart: normalizedStatsRange.value.startKey,
      statsRangeEnd: normalizedStatsRange.value.endKey,
      includeRecords: !isAuthenticated.value,
    })
  },
  { deep: true },
)

watch(
  [selectedDate, plannerGoal],
  () => {
    if (!plannerGoal.value && planner.value.goalEnabled) {
      planner.value.goalEnabled = false
      schedulePlannerSyncForRecord(planner.value)
    }
  },
)

function fillTaskLabelsWithNumbers(record) {
  record.tasks.forEach((task, index) => {
    task.label = createTaskLabel(index)
  })
  schedulePlannerSyncForRecord(record)
}

function clearTaskLabels(record) {
  record.tasks.forEach((task) => {
    task.label = ''
  })
  schedulePlannerSyncForRecord(record)
}

function areTaskLabelsNumbered(record) {
  return record.tasks.every((task, index) => task.label === createTaskLabel(index))
}

function setSyncFeedback(status, message, options = {}) {
  const {
    visible = true,
    duration = 1600,
    sticky = false,
  } = options

  syncStatus.value = status
  syncMessage.value = message

  if (syncToastTimer) {
    window.clearTimeout(syncToastTimer)
    syncToastTimer = null
  }

  syncToastVisible.value = visible

  if (visible && !sticky) {
    syncToastTimer = window.setTimeout(() => {
      syncToastVisible.value = false
    }, duration)
  }
}

function resetAuthForm() {
  authForm.nickname = ''
  authForm.email = ''
  authForm.password = ''
}

function resetGoalForm() {
  goalForm.title = ''
  goalForm.targetDate = ''
  goalForm.activeFrom = ''
  goalForm.activeUntil = ''
  goalForm.status = 'active'
  editingGoalId.value = null
}

function syncProfileForm() {
  profileForm.nickname = currentUser.value?.nickname ?? ''
  profileForm.email = currentUser.value?.email ?? ''
}

function resetPasswordForm() {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

function openAuthDialog(mode = 'login') {
  authMode.value = mode
  authMessage.value = ''
  authDialogOpen.value = true
}

function closeAuthDialog() {
  authDialogOpen.value = false
  authMessage.value = ''
  resetAuthForm()
}

function updateAuthField({ field, value }) {
  authForm[field] = value
}

async function applyAuthSuccess(data) {
  authToken.value = data.token
  currentUser.value = data.user
  setSyncFeedback('cloud', '클라우드 동기화 연결됨')
  persistAuthState({
    token: data.token,
    user: data.user,
  })
  await loadGoals()
  await hydratePlannerRecordsFromApi()
  syncProfileForm()
  closeAuthDialog()
}

async function submitAuthForm() {
  authBusy.value = true
  authMessage.value = ''

  try {
    const result =
      authMode.value === 'login'
        ? await login({
            email: authForm.email,
            password: authForm.password,
          })
        : await signup({
            nickname: authForm.nickname,
            email: authForm.email,
            password: authForm.password,
          })

    await applyAuthSuccess(result)
  } catch (error) {
    authMessage.value = error.message || '인증 처리 중 문제가 발생했습니다.'
  } finally {
    authBusy.value = false
  }
}

async function restoreAuthSession() {
  const savedAuth = readAuthState()

  if (!savedAuth.token) {
    return
  }

  authToken.value = savedAuth.token
  currentUser.value = savedAuth.user ?? null

  try {
    const result = await fetchCurrentUser(savedAuth.token)
    currentUser.value = result.user
    setSyncFeedback('cloud', '클라우드 동기화 연결됨')
    persistAuthState({
      token: savedAuth.token,
      user: result.user,
    })
    await loadGoals()
    await hydratePlannerRecordsFromApi()
    syncProfileForm()
  } catch (error) {
    authToken.value = ''
    currentUser.value = null
    setSyncFeedback('local', '로그인 후 클라우드 저장을 사용할 수 있습니다.', {
      visible: false,
    })
    clearAuthState()
  }
}

function logout() {
  clearPendingSyncTimers()
  authToken.value = ''
  currentUser.value = null
  goals.value = []
  goalQuery.value = ''
  goalMessage.value = ''
  goalStatusFilter.value = 'all'
  setSyncFeedback('local', '로그인 후 클라우드 저장을 사용할 수 있습니다.', {
    visible: false,
  })
  clearAuthState()
  restoreLocalPlannerRecords()
  resetGoalForm()
  resetPasswordForm()
}

async function loadGoals() {
  if (!authToken.value) {
    return
  }

  goalBusy.value = true

  try {
    const result = await fetchGoals(authToken.value, {
      status: 'all',
    })

    goals.value = result.goals
    goalMessage.value = ''
  } catch (error) {
    goalMessage.value = error.message || '목표를 불러오지 못했습니다.'
  } finally {
    goalBusy.value = false
  }
}

async function submitGoal() {
  if (!goalForm.title.trim() || !goalForm.targetDate) {
    goalMessage.value = '목표 이름과 목표일을 입력해 주세요.'
    return
  }

  if ((goalForm.activeFrom && !goalForm.activeUntil) || (!goalForm.activeFrom && goalForm.activeUntil)) {
    goalMessage.value = '표시 시작일과 종료일은 함께 입력해 주세요.'
    return
  }

  if (goalForm.activeFrom && goalForm.activeUntil && goalForm.activeFrom > goalForm.activeUntil) {
    goalMessage.value = '표시 종료일은 시작일보다 빠를 수 없습니다.'
    return
  }

  goalBusy.value = true
  goalMessage.value = ''

  try {
    const result = await createGoal(authToken.value, {
      title: goalForm.title.trim(),
      targetDate: goalForm.targetDate,
      activeFrom: goalForm.activeFrom || null,
      activeUntil: goalForm.activeUntil || null,
      status: goalForm.status,
    })

    await loadGoals()
    resetGoalForm()
    goalQuery.value = ''
    goalMessage.value = result.message || '목표가 추가되었습니다.'
  } catch (error) {
    goalMessage.value = error.message || '목표를 추가하지 못했습니다.'
  } finally {
    goalBusy.value = false
  }
}

function updateGoalFormField({ field, value }) {
  goalForm[field] = value
}

function startGoalEdit(goal) {
  editingGoalId.value = goal.id
  goalForm.title = goal.title ?? ''
  goalForm.targetDate = goal.targetDate ?? ''
  goalForm.activeFrom = goal.activeFrom ?? ''
  goalForm.activeUntil = goal.activeUntil ?? ''
  goalForm.status = goal.status ?? 'active'
  goalMessage.value = ''
}

async function saveGoalEdit() {
  if (!editingGoalId.value) {
    return
  }

  if (!goalForm.title.trim() || !goalForm.targetDate) {
    goalMessage.value = '목표 이름과 목표일을 입력해 주세요.'
    return
  }

  if ((goalForm.activeFrom && !goalForm.activeUntil) || (!goalForm.activeFrom && goalForm.activeUntil)) {
    goalMessage.value = '표시 시작일과 종료일은 함께 입력해 주세요.'
    return
  }

  if (goalForm.activeFrom && goalForm.activeUntil && goalForm.activeFrom > goalForm.activeUntil) {
    goalMessage.value = '표시 종료일은 시작일보다 빠를 수 없습니다.'
    return
  }

  goalBusy.value = true
  goalMessage.value = ''

  try {
    const result = await updateGoal(authToken.value, editingGoalId.value, {
      title: goalForm.title.trim(),
      targetDate: goalForm.targetDate,
      activeFrom: goalForm.activeFrom || null,
      activeUntil: goalForm.activeUntil || null,
      status: goalForm.status,
    })

    await loadGoals()
    resetGoalForm()
    goalMessage.value = result.message || '목표가 수정되었습니다.'
  } catch (error) {
    goalMessage.value = error.message || '목표를 수정하지 못했습니다.'
  } finally {
    goalBusy.value = false
  }
}

function updateProfileField({ field, value }) {
  profileForm[field] = value
}

function updatePasswordField({ field, value }) {
  passwordForm[field] = value
}

async function submitProfileForm() {
  profileBusy.value = true
  profileMessage.value = ''

  try {
    const result = await updateProfile(authToken.value, {
      nickname: profileForm.nickname,
      email: profileForm.email,
    })

    currentUser.value = result.user
    persistAuthState({
      token: authToken.value,
      user: result.user,
    })
    syncProfileForm()
    profileMessage.value = '프로필이 저장되었습니다.'
  } catch (error) {
    profileMessage.value = error.message || '프로필을 저장하지 못했습니다.'
  } finally {
    profileBusy.value = false
  }
}

async function submitPasswordForm() {
  if (!passwordForm.currentPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
    passwordMessage.value = '모든 비밀번호 항목을 입력해 주세요.'
    return
  }

  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    passwordMessage.value = '새 비밀번호 확인이 일치하지 않습니다.'
    return
  }

  passwordBusy.value = true
  passwordMessage.value = ''

  try {
    await updatePassword(authToken.value, {
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword,
    })
    resetPasswordForm()
    passwordMessage.value = '비밀번호가 변경되었습니다.'
  } catch (error) {
    passwordMessage.value = error.message || '비밀번호를 변경하지 못했습니다.'
  } finally {
    passwordBusy.value = false
  }
}

function replacePlannerRecords(nextRecords) {
  Object.keys(plannerRecords).forEach((key) => {
    delete plannerRecords[key]
  })

  Object.entries(nextRecords).forEach(([key, record]) => {
    plannerRecords[key] = record
  })
}

function restoreLocalPlannerRecords() {
  replacePlannerRecords(createInitialPlannerRecords(plannerSeed, normalizeRecord))

  const savedState = readPlannerStorageState()

  if (savedState.selectedDate) {
    selectedDate.value = toDateValue(savedState.selectedDate, selectedDate.value)
  }

  if (savedState.calendarViewDate) {
    calendarViewDate.value = toDateValue(savedState.calendarViewDate, selectedDate.value)
  }
}

function findRecordKey(record) {
  return Object.entries(plannerRecords).find(([, value]) => value === record)?.[0] ?? null
}

function clearPendingSyncTimers() {
  syncTimers.forEach((timerId) => {
    window.clearTimeout(timerId)
  })
  syncTimers.clear()
}

function schedulePlannerSyncForRecord(record) {
  const recordKey = findRecordKey(record)

  if (!recordKey) {
    return
  }

  schedulePlannerSync(recordKey)
}

function schedulePlannerSync(recordKey) {
  if (!isAuthenticated.value || isHydratingRemoteRecords) {
    return
  }

  if (syncTimers.has(recordKey)) {
    window.clearTimeout(syncTimers.get(recordKey))
  }

  setSyncFeedback('syncing', '클라우드 저장 중...', {
    sticky: true,
  })

  const timerId = window.setTimeout(async () => {
    syncTimers.delete(recordKey)

    try {
      const record = plannerRecords[recordKey]

      if (!record) {
        if (syncTimers.size === 0) {
          setSyncFeedback('cloud', '클라우드 동기화 연결됨')
        }
        return
      }

      if (!hasPlannerContent(record)) {
        await deletePlannerEntry(authToken.value, recordKey)

        if (syncTimers.size === 0) {
          setSyncFeedback('cloud', '클라우드에서 삭제됨')
        }
        return
      }

      await savePlannerEntry(authToken.value, recordKey, {
        ...record,
        tasks: record.tasks.map((task) => ({ ...task })),
        memo: record.memo.map((item) => ({ ...item })),
        timetable: [...record.timetable],
      })

      if (syncTimers.size === 0) {
        setSyncFeedback('cloud', '클라우드에 저장됨')
      }
    } catch (error) {
      setSyncFeedback('error', error.message || '클라우드 저장에 실패했습니다.', {
        duration: 3200,
      })
    }
  }, 500)

  syncTimers.set(recordKey, timerId)
}

async function hydratePlannerRecordsFromApi() {
  if (!authToken.value) {
    return
  }

  isHydratingRemoteRecords = true
  setSyncFeedback('syncing', '클라우드 데이터를 불러오는 중...', {
    sticky: true,
  })

  try {
    const result = await fetchPlannerEntries(authToken.value)
    const remoteRecords = {}

    result.entries.forEach((entry) => {
      remoteRecords[entry.entryDate] = normalizeRecord(entry.payload)
    })

    replacePlannerRecords(remoteRecords)

    setSyncFeedback('cloud', '클라우드 동기화 연결됨')
  } catch (error) {
    setSyncFeedback('error', error.message || '클라우드 데이터를 불러오지 못했습니다.', {
      duration: 3200,
    })
  } finally {
    isHydratingRemoteRecords = false
  }
}

function applyPrintPageStyle(layout) {
  if (typeof document === 'undefined') {
    return
  }

  const pageRule =
    layout === 'double'
      ? '@page { size: A4 landscape; margin: 0; }'
      : '@page { size: A4 portrait; margin: 0; }'

  if (!printPageStyleElement) {
    printPageStyleElement = document.createElement('style')
    printPageStyleElement.setAttribute('data-print-page-style', 'true')
    document.head.appendChild(printPageStyleElement)
  }

  printPageStyleElement.textContent = pageRule
  document.body.dataset.printLayout = layout
}

async function printSelectedPlanner(layout = 'single') {
  printLayout.value = layout
  applyPrintPageStyle(layout)
  await nextTick()
  window.print()
}

onMounted(() => {
  setSyncFeedback('local', '로그인 후 클라우드 저장을 사용할 수 있습니다.', {
    visible: false,
  })
  restoreAuthSession()
})
</script>

<template>
  <main class="min-h-screen px-4 py-6 text-ink sm:px-6 lg:px-10">
    <div class="print-root mx-auto flex max-w-[1760px] flex-col gap-6 xl:grid xl:grid-cols-[280px_minmax(0,1fr)] xl:items-start">
      <aside class="print-hidden rounded-[28px] border border-white/60 bg-white/70 p-5 backdrop-blur sm:p-6 xl:sticky xl:top-6">
        <div class="space-y-6">
          <div class="space-y-2">
            <p class="text-[11px] font-bold uppercase tracking-[0.28em] text-stone-500">10 Minute Planner</p>
            <h1 class="text-2xl font-semibold tracking-[-0.04em] text-stone-900">
              다이어리처럼 보이되,<br>앱답게 빠르게 이동하는 플래너
            </h1>
            <p class="text-sm font-medium leading-6 text-stone-600">
              A5 본문을 최대한 넓게 쓰기 위해 상단 헤더 대신 왼쪽 사이드 내비게이션 구조로 정리했습니다.
            </p>
          </div>

          <section class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
            <template v-if="isAuthenticated">
              <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">SIGNED IN</p>
              <p class="mt-2 text-lg font-semibold tracking-[-0.03em] text-stone-900">{{ currentUser.nickname }}</p>
              <p class="mt-1 text-sm font-semibold text-stone-500">{{ currentUser.email }}</p>
              <button
                type="button"
                class="mt-4 w-full rounded-full border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.16em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="logout"
              >
                LOGOUT
              </button>
            </template>
            <template v-else>
              <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">ACCOUNT</p>
              <p class="mt-2 text-sm font-semibold leading-6 text-stone-700">
                로그인 후 문서, 통계, 목표 관리가 모두 계정 기준으로 연결됩니다.
              </p>
              <div class="mt-4 grid gap-2">
                <button
                  type="button"
                  class="w-full rounded-full border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.16em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                  @click="openAuthDialog('login')"
                >
                  LOGIN
                </button>
                <button
                  type="button"
                  class="w-full rounded-full border border-stone-900 bg-stone-900 px-4 py-3 text-xs font-bold tracking-[0.16em] text-white transition hover:bg-stone-700"
                  @click="openAuthDialog('signup')"
                >
                  SIGN UP
                </button>
              </div>
            </template>
          </section>

          <section v-if="isAuthenticated" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
            <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">NAVIGATION</p>
            <div class="mt-4 grid grid-cols-2 gap-2">
              <button
                type="button"
                class="rounded-2xl px-3 py-3 text-xs font-bold tracking-[0.14em] transition"
                :class="screenMode === 'planner' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                @click="screenMode = 'planner'"
              >
                PLANNER
              </button>
              <button
                type="button"
                class="rounded-2xl px-3 py-3 text-xs font-bold tracking-[0.14em] transition"
                :class="screenMode === 'stats' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                @click="screenMode = 'stats'"
              >
                STATS
              </button>
              <button
                type="button"
                class="rounded-2xl px-3 py-3 text-xs font-bold tracking-[0.14em] transition"
                :class="screenMode === 'goals' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                @click="screenMode = 'goals'"
              >
                GOALS
              </button>
              <button
                type="button"
                class="rounded-2xl px-3 py-3 text-xs font-bold tracking-[0.14em] transition"
                :class="screenMode === 'settings' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                @click="screenMode = 'settings'"
              >
                SETTINGS
              </button>
            </div>
          </section>

          <section v-if="isAuthenticated && screenMode === 'planner'" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
            <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">VIEW</p>
            <div class="mt-4 grid gap-2">
              <button
                type="button"
                class="rounded-2xl px-4 py-3 text-xs font-bold tracking-[0.14em] transition"
                :class="viewMode === 'focus' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                @click="viewMode = 'focus'"
              >
                1 PAGE + INFO
              </button>
              <button
                type="button"
                class="rounded-2xl px-4 py-3 text-xs font-bold tracking-[0.14em] transition"
                :class="viewMode === 'spread' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                @click="viewMode = 'spread'"
              >
                2 PAGE SPREAD
              </button>
            </div>
          </section>

          <section v-if="isAuthenticated && screenMode === 'planner'" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
            <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">DAY MOVE</p>
            <div class="mt-4 grid gap-2">
              <button
                type="button"
                class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="shiftDate(-1)"
              >
                PREV DAY
              </button>
              <button
                type="button"
                class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="shiftDate(1)"
              >
                NEXT DAY
              </button>
            </div>
          </section>

          <section v-if="isAuthenticated && screenMode === 'planner'" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
            <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">PRINT</p>
            <div class="mt-4 grid gap-2">
              <button
                type="button"
                class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="printSelectedPlanner('single')"
              >
                PRINT 1-UP
              </button>
              <button
                type="button"
                class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="printSelectedPlanner('double')"
              >
                PRINT 2-UP
              </button>
            </div>
          </section>
        </div>
      </aside>

      <div class="min-w-0 space-y-6">
      <section
        v-if="!isAuthenticated"
        class="print-hidden rounded-[32px] border border-white/60 bg-white/65 p-6 shadow-[0_24px_80px_rgba(28,25,23,0.08)] sm:p-8"
      >
        <div class="mx-auto flex max-w-3xl flex-col gap-6 text-center">
          <div class="space-y-3">
            <p class="text-[11px] font-bold uppercase tracking-[0.28em] text-stone-500">Members Only</p>
            <h2 class="text-3xl font-semibold tracking-[-0.05em] text-stone-900 sm:text-4xl">
              로그인 후 플래너를 작성하고<br>
              클라우드에 안전하게 저장하세요
            </h2>
            <p class="mx-auto max-w-2xl text-sm leading-7 text-stone-600 sm:text-base">
              이제 플래너는 사용자 계정 기준으로 문서와 통계가 연결됩니다. 로그인하지 않은 상태에서는 데이터가 섞일 수 있어
              작성 화면을 열지 않도록 변경했습니다.
            </p>
          </div>

          <div class="grid gap-4 rounded-[28px] border border-stone-200 bg-[#fbf7f0] p-5 text-left sm:grid-cols-3">
            <article class="rounded-2xl border border-stone-200 bg-white px-4 py-5">
              <p class="text-[10px] font-bold tracking-[0.18em] text-stone-500">ACCOUNT</p>
              <p class="mt-3 text-sm font-semibold leading-6 text-stone-800">
                회원가입 후 사용자별 플래너와 통계를 분리해서 관리합니다.
              </p>
            </article>
            <article class="rounded-2xl border border-stone-200 bg-white px-4 py-5">
              <p class="text-[10px] font-bold tracking-[0.18em] text-stone-500">CLOUD SAVE</p>
              <p class="mt-3 text-sm font-semibold leading-6 text-stone-800">
                작성 내용은 날짜별로 서버에 저장되고, 다른 기기에서도 이어볼 수 있습니다.
              </p>
            </article>
            <article class="rounded-2xl border border-stone-200 bg-white px-4 py-5">
              <p class="text-[10px] font-bold tracking-[0.18em] text-stone-500">PRINT & STATS</p>
              <p class="mt-3 text-sm font-semibold leading-6 text-stone-800">
                로그인 기반 데이터로 통계와 출력 흐름을 안정적으로 맞춰갑니다.
              </p>
            </article>
          </div>

          <div class="flex flex-col items-center justify-center gap-3 sm:flex-row">
            <button
              type="button"
              class="rounded-full border border-stone-300 bg-white px-6 py-3 text-xs font-bold tracking-[0.18em] text-stone-700 transition hover:border-stone-500 hover:text-stone-900"
              @click="openAuthDialog('login')"
            >
              LOGIN
            </button>
            <button
              type="button"
              class="rounded-full bg-stone-900 px-6 py-3 text-xs font-bold tracking-[0.18em] text-white transition hover:bg-stone-700"
              @click="openAuthDialog('signup')"
            >
              SIGN UP
            </button>
          </div>
        </div>
      </section>

      <section
        v-else-if="screenMode === 'planner' && viewMode === 'focus'"
        class="print-hidden grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]"
      >
        <div class="print-target">
          <PlannerPage
            :date-main="selectedDateDisplay.main"
            :date-weekday="selectedDateDisplay.weekday"
            :date-weekday-tone="selectedDateDisplay.weekdayTone"
            :dday="plannerDday"
            :show-dday="showPlannerDday"
            :comment="planner.comment"
            :total-time="formatTotalTime(planner)"
            :tasks="planner.tasks"
            :memo="planner.memo"
            :hours="hours"
            :timetable="planner.timetable"
            @update:comment="updateComment(planner, $event)"
            @update:task-label="updateTaskLabel(planner, $event)"
            @update:task-title="updateTaskTitle(planner, $event)"
            @toggle:task="toggleTask(planner, $event)"
            @update:memo-label="updateMemoLabel(planner, $event)"
            @update:memo="updateMemo(planner, $event)"
            @update:timetable="updateTimetable(planner, $event)"
          />
        </div>

        <aside class="print-hidden flex flex-col gap-4">
          <section class="border border-stone-200 bg-white/80 p-5">
            <p class="mb-4 text-[11px] font-bold tracking-[0.22em] text-ink">PREV SNAPSHOT</p>
            <div class="space-y-3">
              <p
                v-for="item in planner.prevSummary"
                :key="item"
                class="border-b border-stone-200 pb-3 text-[11px] font-semibold tracking-[0.08em] text-stone-700 last:border-b-0 last:pb-0"
              >
                {{ item || ' ' }}
              </p>
            </div>
          </section>

          <section class="border border-stone-200 bg-white/80 p-5">
            <div class="flex items-start justify-between gap-3">
              <div>
                <p class="text-[11px] font-bold tracking-[0.22em] text-ink">TASK LABELS</p>
                <p class="mt-2 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-600">
                  ON이면 왼쪽 라벨을 01, 02 형태로 채우고 OFF이면 비워 둡니다.
                </p>
              </div>
              <button
                type="button"
                class="relative h-8 w-16 shrink-0 rounded-full transition"
                :class="areTaskLabelsNumbered(planner) ? 'bg-stone-900' : 'bg-stone-300'"
                @click="areTaskLabelsNumbered(planner) ? clearTaskLabels(planner) : fillTaskLabelsWithNumbers(planner)"
              >
                <span
                  class="absolute top-1 h-6 w-6 rounded-full bg-white shadow-sm transition"
                  :class="areTaskLabelsNumbered(planner) ? 'left-9' : 'left-1'"
                />
              </button>
            </div>
          </section>

          <section class="border border-stone-200 bg-white/80 p-5">
            <p class="mb-4 text-[11px] font-bold tracking-[0.22em] text-ink">READ NEXT</p>
            <div class="space-y-3">
              <p
                v-for="item in planner.nextFocus"
                :key="item"
                class="border-b border-stone-200 pb-3 text-[11px] font-semibold tracking-[0.08em] text-stone-700 last:border-b-0 last:pb-0"
              >
                {{ item || ' ' }}
              </p>
            </div>
          </section>

          <section class="border border-stone-200 bg-white/80 p-5">
            <div class="flex items-start justify-between gap-3">
              <div>
                <p class="text-[11px] font-bold tracking-[0.22em] text-ink">D-DAY 사용</p>
                <p class="mt-2 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-600">
                  목표 검색과 기간 설정은 GOALS 화면에서 관리하고, 여기서는 현재 날짜에 D-DAY를 보여줄지 여부만 제어합니다.
                </p>
              </div>
              <button
                type="button"
                class="relative h-8 w-16 shrink-0 rounded-full transition disabled:cursor-not-allowed disabled:opacity-50"
                :class="planner.goalEnabled ? 'bg-stone-900' : 'bg-stone-300'"
                :disabled="!hasActiveGoalForSelectedDate"
                @click="updateGoalEnabled(planner, !planner.goalEnabled)"
              >
                <span
                  class="absolute top-1 h-6 w-6 rounded-full bg-white shadow-sm transition"
                  :class="planner.goalEnabled ? 'left-9' : 'left-1'"
                />
              </button>
            </div>

            <div class="mt-4 space-y-3">
              <div v-if="plannerGoal" class="rounded-2xl border border-stone-200 bg-white px-4 py-3">
                <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">현재 목표</p>
                <p class="mt-2 text-sm font-semibold tracking-[0.02em] text-stone-900">{{ plannerGoal.title }}</p>
                <p class="mt-1 text-[11px] font-semibold tracking-[0.06em] text-stone-500">
                  목표일 {{ plannerGoal.targetDate }} / 적용 {{ plannerGoal.activeFrom }} ~ {{ plannerGoal.activeUntil }}
                </p>
              </div>

              <div v-if="plannerGoal" class="rounded-2xl border border-stone-200 bg-[#fbf7f0] px-4 py-4">
                <p class="text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-600">
                  이 날짜에는 이미 적용된 목표가 있으므로 토글만으로 표시 여부를 빠르게 조절할 수 있습니다.
                </p>
              </div>

              <div v-else class="rounded-2xl border border-dashed border-stone-300 bg-white/70 px-4 py-4">
                <p class="text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-500">
                  현재 날짜에 적용된 목표가 없습니다. GOALS 화면에서 표시 기간을 지정하면 여기 토글이 자동으로 활성화됩니다.
                </p>
              </div>
            </div>
          </section>

          <MiniCalendar
            :month-label="monthLabel"
            :year-label="yearLabel"
            :days="calendarDays"
            :selected-key="toKey(selectedDate)"
            :marked-keys="markedDateKeys"
            @shift-month="shiftCalendarMonth"
            @shift-year="shiftCalendarYear"
            @go-today="selectDate(new Date())"
            @select="selectDate"
          />

          <section class="grid grid-cols-2 gap-4">
            <article class="border border-stone-200 bg-white/80 p-5">
              <p class="text-[11px] font-bold tracking-[0.22em] text-ink">STATS</p>
              <div class="mt-5 space-y-4">
                <div>
                  <p class="text-[28px] font-semibold tracking-[-0.05em] text-stone-900">{{ completionRate }}%</p>
                  <p class="text-[11px] font-semibold tracking-[0.08em] text-stone-500">TASK COMPLETION</p>
                </div>
                <div>
                  <p class="text-[22px] font-semibold tracking-[-0.04em] text-stone-900">{{ formatTotalTime(planner) }}</p>
                  <p class="text-[11px] font-semibold tracking-[0.08em] text-stone-500">FOCUSED TIME</p>
                </div>
              </div>
            </article>

            <article class="border border-stone-200 bg-white/80 p-5">
              <p class="text-[11px] font-bold tracking-[0.22em] text-ink">NEXT DAY</p>
              <div class="mt-5 space-y-3">
                <p class="text-lg font-semibold tracking-[-0.04em] text-stone-900">
                  <span>{{ secondaryDateDisplay.main }}</span>
                  <span class="ml-1" :class="secondaryDateDisplay.weekdayTone">{{ secondaryDateDisplay.weekday }}</span>
                </p>
                <p class="text-[11px] font-semibold tracking-[0.08em] text-stone-600">
                  내일의 첫 작업은 "{{ secondaryPlanner.tasks[0]?.title || '새 작업 추가' }}" 로 시작합니다.
                </p>
              </div>
            </article>
          </section>
        </aside>
      </section>

      <section
        v-else-if="screenMode === 'planner'"
        class="print-hidden overflow-x-auto rounded-[32px] border border-white/60 bg-white/40 p-4 sm:p-6"
      >
        <div class="flex min-w-[1260px] gap-6">
          <div class="print-target">
            <PlannerPage
              :date-main="selectedDateDisplay.main"
              :date-weekday="selectedDateDisplay.weekday"
              :date-weekday-tone="selectedDateDisplay.weekdayTone"
              :dday="plannerDday"
              :show-dday="showPlannerDday"
              :comment="planner.comment"
              :total-time="formatTotalTime(planner)"
              :tasks="planner.tasks"
              :memo="planner.memo"
              :hours="hours"
              :timetable="planner.timetable"
              @update:comment="updateComment(planner, $event)"
              @update:task-label="updateTaskLabel(planner, $event)"
              @update:task-title="updateTaskTitle(planner, $event)"
              @toggle:task="toggleTask(planner, $event)"
              @update:memo-label="updateMemoLabel(planner, $event)"
              @update:memo="updateMemo(planner, $event)"
              @update:timetable="updateTimetable(planner, $event)"
            />
          </div>
          <div class="print-hidden">
            <PlannerPage
              :date-main="secondaryDateDisplay.main"
              :date-weekday="secondaryDateDisplay.weekday"
              :date-weekday-tone="secondaryDateDisplay.weekdayTone"
              :dday="''"
              :show-dday="false"
              :comment="secondaryPlanner.comment"
              :total-time="formatTotalTime(secondaryPlanner)"
              :tasks="secondaryPlanner.tasks"
              :memo="secondaryPlanner.memo"
              :hours="hours"
              :timetable="secondaryPlanner.timetable"
              @update:comment="updateComment(secondaryPlanner, $event)"
              @update:task-label="updateTaskLabel(secondaryPlanner, $event)"
              @update:task-title="updateTaskTitle(secondaryPlanner, $event)"
              @toggle:task="toggleTask(secondaryPlanner, $event)"
              @update:memo-label="updateMemoLabel(secondaryPlanner, $event)"
              @update:memo="updateMemo(secondaryPlanner, $event)"
              @update:timetable="updateTimetable(secondaryPlanner, $event)"
            />
          </div>
        </div>
      </section>

      <GoalsDashboard
        v-else-if="screenMode === 'goals'"
        class="print-hidden"
        :goals="filteredGoals"
        :query="goalQuery"
        :status="goalStatusFilter"
        :form="goalForm"
        :editing-goal-id="editingGoalId"
        :busy="goalBusy"
        :message="goalMessage"
        :selected-date-key="toKey(selectedDate)"
        @update:query="goalQuery = $event"
        @update:status="goalStatusFilter = $event"
        @update:form-field="updateGoalFormField"
        @submit:create="submitGoal"
        @start-edit="startGoalEdit"
        @cancel-edit="resetGoalForm(); goalMessage = ''"
        @submit:update="saveGoalEdit"
      />

      <SettingsDashboard
        v-else-if="screenMode === 'settings'"
        class="print-hidden"
        :user="currentUser"
        :profile-form="profileForm"
        :password-form="passwordForm"
        :profile-busy="profileBusy"
        :password-busy="passwordBusy"
        :profile-message="profileMessage"
        :password-message="passwordMessage"
        @update:profile-field="updateProfileField"
        @update:password-field="updatePasswordField"
        @submit:profile="submitProfileForm"
        @submit:password="submitPasswordForm"
      />

      <StatsDashboard
        v-else
        class="print-hidden"
        :overview-cards="overviewCards"
        :weekly-records="weeklyRecords"
        :recent-records="recentRecords"
        :best-day="bestDay"
        :selected-date-label="`${selectedDateDisplay.main} ${selectedDateDisplay.weekday}`"
        :range-start="normalizedStatsRange.startKey"
        :range-end="normalizedStatsRange.endKey"
        @update:range-start="statsRangeStart = $event"
        @update:range-end="statsRangeEnd = $event"
      />

      <section v-if="isAuthenticated" class="print-only">
        <div v-if="printLayout === 'single'" class="print-paper print-paper--single">
          <div class="print-sheet-frame">
            <PlannerPage
              :date-main="selectedDateDisplay.main"
              :date-weekday="selectedDateDisplay.weekday"
              :date-weekday-tone="selectedDateDisplay.weekdayTone"
              :dday="plannerDday"
              :show-dday="showPlannerDday"
              :comment="planner.comment"
              :total-time="formatTotalTime(planner)"
              :tasks="planner.tasks"
              :memo="planner.memo"
              :hours="hours"
              :timetable="planner.timetable"
              @update:comment="updateComment(planner, $event)"
              @update:task-label="updateTaskLabel(planner, $event)"
              @update:task-title="updateTaskTitle(planner, $event)"
              @toggle:task="toggleTask(planner, $event)"
              @update:memo-label="updateMemoLabel(planner, $event)"
              @update:memo="updateMemo(planner, $event)"
              @update:timetable="updateTimetable(planner, $event)"
            />
          </div>
        </div>

        <div v-else class="print-paper print-paper--double">
          <div class="print-sheet-frame">
            <PlannerPage
              :date-main="selectedDateDisplay.main"
              :date-weekday="selectedDateDisplay.weekday"
              :date-weekday-tone="selectedDateDisplay.weekdayTone"
              :dday="plannerDday"
              :show-dday="showPlannerDday"
              :comment="planner.comment"
              :total-time="formatTotalTime(planner)"
              :tasks="planner.tasks"
              :memo="planner.memo"
              :hours="hours"
              :timetable="planner.timetable"
              @update:comment="updateComment(planner, $event)"
              @update:task-label="updateTaskLabel(planner, $event)"
              @update:task-title="updateTaskTitle(planner, $event)"
              @toggle:task="toggleTask(planner, $event)"
              @update:memo-label="updateMemoLabel(planner, $event)"
              @update:memo="updateMemo(planner, $event)"
              @update:timetable="updateTimetable(planner, $event)"
            />
          </div>
          <div class="print-sheet-frame">
            <PlannerPage
              :date-main="secondaryDateDisplay.main"
              :date-weekday="secondaryDateDisplay.weekday"
              :date-weekday-tone="secondaryDateDisplay.weekdayTone"
              :dday="''"
              :show-dday="false"
              :comment="secondaryPlanner.comment"
              :total-time="formatTotalTime(secondaryPlanner)"
              :tasks="secondaryPlanner.tasks"
              :memo="secondaryPlanner.memo"
              :hours="hours"
              :timetable="secondaryPlanner.timetable"
              @update:comment="updateComment(secondaryPlanner, $event)"
              @update:task-label="updateTaskLabel(secondaryPlanner, $event)"
              @update:task-title="updateTaskTitle(secondaryPlanner, $event)"
              @toggle:task="toggleTask(secondaryPlanner, $event)"
              @update:memo-label="updateMemoLabel(secondaryPlanner, $event)"
              @update:memo="updateMemo(secondaryPlanner, $event)"
              @update:timetable="updateTimetable(secondaryPlanner, $event)"
            />
          </div>
        </div>
      </section>
      </div>
    </div>

    <AuthDialog
      :open="authDialogOpen"
      :mode="authMode"
      :form="authForm"
      :busy="authBusy"
      :message="authMessage"
      @close="closeAuthDialog"
      @submit="submitAuthForm"
      @switch-mode="authMode = $event; authMessage = ''"
      @update:field="updateAuthField"
    />

    <transition
      enter-active-class="transition duration-200 ease-out"
      enter-from-class="translate-y-2 opacity-0"
      enter-to-class="translate-y-0 opacity-100"
      leave-active-class="transition duration-200 ease-in"
      leave-from-class="translate-y-0 opacity-100"
      leave-to-class="translate-y-2 opacity-0"
    >
      <div
        v-if="isAuthenticated && syncToastVisible"
        class="pointer-events-none fixed bottom-5 right-5 z-40 max-w-[240px] rounded-full border border-stone-200/70 bg-white/80 px-3 py-2 shadow-[0_10px_24px_rgba(28,25,23,0.08)] backdrop-blur"
      >
        <p
          class="text-[11px] font-semibold tracking-[0.04em]"
          :class="syncStatus === 'error' ? 'text-red-500' : syncStatus === 'syncing' ? 'text-blue-500' : 'text-stone-500'"
        >
          {{ syncMessage }}
        </p>
      </div>
    </transition>
  </main>
</template>
