<template>
  <div class="dashboard">
    <div v-if="isAuthenticated && user">
      <h2>Today's Habits for {{ user.nickname }}</h2>
      
      <div v-if="loading" class="loading-message">
        <p>Loading habits...</p>
      </div>

      <div v-else-if="processedHabits.length > 0" class="habits-list">
        <div v-for="habit in processedHabits" :key="habit.id" class="habit-card">
          <div class="habit-details">
            <div class="habit-header">
              <span class="habit-name">{{ habit.name }}</span>
              <button
                v-if="!isCompleteToday(habit)"
                @click="completeHabit(habit.id)"
                :disabled="completing === habit.id"
                class="complete-btn"
              >
                {{ completing === habit.id ? '...' : 'Complete' }}
              </button>
              <span v-else class="completed-text">✅ Done!</span>
            </div>
            <div class="calendar-grid">
              <div 
                v-for="day in calendarDays" 
                :key="day.getTime()"
                :class="['calendar-cell', getDayStatus(habit, day)]"
              >
                <span class="date-label">{{ formatDate(day) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <p>No habits scheduled for today. Great job!</p>
        <NuxtLink to="/habits">Manage Habits</NuxtLink>
      </div>

    </div>
    <div v-else>
       <p>Loading session...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';

// --- Type Definitions ---
interface Habit {
  id: number;
  name: string;
  daysOfWeek: number[]; // 0 = Sunday, 6 = Saturday
  completions: { id: number; date: string }[];
  createdAt: string;
}
// Internal type for easier lookup
interface HabitWithCompletionSet extends Habit {
  completionDates: Set<number>; // Set of timestamps for O(1) lookup
  createdAtTimestamp: number;
}

// --- Composables ---
const { user, isAuthenticated } = useAuth();
const api = useApi();

// --- State ---
const allHabits = ref<Habit[]>([]);
const loading = ref(true);
const completing = ref<number | null>(null);

// --- Helpers: Date Normalization & Formatting ---
/**
 * Normalizes a date to the start of the day in UTC.
 * This is CRITICAL for consistent date comparisons across timezones.
 * @param date The date to normalize.
 * @returns A new Date object set to 00:00:00 UTC.
 */
const normalizeDateUTC = (date: Date): Date => {
  return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
};
const today = normalizeDateUTC(new Date());

const formatDate = (date: Date): string => {
  // Format: "3 янв."
  return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
};


// --- Computed Properties ---
const processedHabits = computed((): HabitWithCompletionSet[] => {
  const todayDayIndex = today.getUTCDay(); // 0 = Sunday, 1 = Monday...
  return allHabits.value
    .filter(h => h.daysOfWeek.includes(todayDayIndex)) // Only show habits active today
    .map(habit => ({
      ...habit,
      // Pre-calculate a Set of completion timestamps for fast O(1) lookups
      completionDates: new Set(habit.completions.map(c => normalizeDateUTC(new Date(c.date)).getTime())),
      createdAtTimestamp: normalizeDateUTC(new Date(habit.createdAt)).getTime(),
    }));
});

const calendarDays = computed(() => {
  const dates = [];
  const currentDayOfWeek = today.getUTCDay(); // 0 = Sun, 1 = Mon...
  // Adjust so Monday is 0 and Sunday is 6
  const adjustedDay = currentDayOfWeek === 0 ? 6 : currentDayOfWeek - 1;

  // Start date is the Monday of the previous week
  const startDate = normalizeDateUTC(new Date(today));
  startDate.setUTCDate(startDate.getUTCDate() - adjustedDay - 7);
  
  for (let i = 0; i < 14; i++) {
    const d = new Date(startDate);
    d.setUTCDate(d.getUTCDate() + i);
    dates.push(d);
  }
  return dates;
});


// --- Methods: Status and Actions ---

const getDayStatus = (habit: HabitWithCompletionSet, date: Date): string => {
  const normalizedDate = normalizeDateUTC(date);
  const normalizedTimestamp = normalizedDate.getTime();
  const dayIndex = normalizedDate.getUTCDay(); // 0 = Sunday
  
  // Rule a) FUTURE
  if (normalizedTimestamp > today.getTime()) {
    return 'NEUTRAL';
  }
  
  // Rule b) BEFORE_CREATED
  if (normalizedTimestamp < habit.createdAtTimestamp) {
    return 'NEUTRAL';
  }

  // Rule c) NOT_SCHEDULED
  const isActiveDay = habit.daysOfWeek.includes(dayIndex);
  if (!isActiveDay) {
    return 'NEUTRAL';
  }
  
  // Rule d) COMPLETED
  if (habit.completionDates.has(normalizedTimestamp)) {
    return 'COMPLETED';
  }
  
  // Rule e) MISSED
  // All previous conditions failed, and we know date <= today.
  // Therefore, if it's an active day that wasn't completed, it was missed.
  return 'MISSED';
};

const isCompleteToday = (habit: HabitWithCompletionSet) => {
  return habit.completionDates.has(today.getTime());
};

const fetchHabits = async () => {
  loading.value = true;
  try {
    allHabits.value = await api<Habit[]>('/habits');
  } catch (error) {
    console.error("Failed to fetch habits:", error);
    allHabits.value = [];
  } finally {
    loading.value = false;
  }
};

const completeHabit = async (habitId: number) => {
  completing.value = habitId;
  try {
    await api(`/habits/${habitId}/complete`, { method: 'POST' });
    await fetchHabits(); // Re-fetch the list to update UI
  } catch (error) {
    console.error(`Failed to complete habit ${habitId}:`, error);
  } finally {
    completing.value = null;
  }
};


// --- Lifecycle ---
onMounted(() => {
  if (isAuthenticated.value) {
    fetchHabits();
  }
  watch(isAuthenticated, (isAuth) => {
    if (isAuth && allHabits.value.length === 0) {
      fetchHabits();
    }
  });
});
</script>

<style scoped>
.dashboard {
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
}
.habits-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}
.habit-card {
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  text-align: left;
}
.habit-details {
  width: 100%;
}
.habit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.habit-name {
  font-size: 1.2em;
  font-weight: bold;
}
.complete-btn {
  padding: 8px 12px;
  border: none;
  border-radius: 5px;
  background-color: #88c0d0;
  color: #2e3440;
  cursor: pointer;
  flex-shrink: 0;
}
.completed-text {
  color: #a3be8c;
  font-weight: bold;
}
.empty-state {
  margin-top: 40px;
  color: #666;
}
.empty-state a {
  margin-top: 10px;
  display: inline-block;
}

/* Calendar Grid Styles */
.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px; /* Slightly more gap */
}
.calendar-cell {
  width: 100%;
  aspect-ratio: 1 / 1;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.date-label {
  font-size: 0.75em;
  color: #4c566a;
}
.calendar-cell.COMPLETED .date-label,
.calendar-cell.MISSED .date-label {
  color: white;
}
.calendar-cell.NEUTRAL {
  background-color: #eceff4; /* Gray */
}
.calendar-cell.COMPLETED {
  background-color: #a3be8c; /* Green */
}
.calendar-cell.MISSED {
  background-color: #bf616a; /* Red */
}
</style>
