import { useState, useEffect, useMemo, useRef } from 'react'
import { useQuery } from '@tanstack/react-query'
import { motion, AnimatePresence } from 'framer-motion'
import { ChevronDown, Flame, Trophy, CheckCircle2, TrendingUp, BarChart3, Calendar, Sparkles, Target, Zap } from 'lucide-react'
import { format, subDays, parseISO, startOfDay, differenceInDays, isBefore, isAfter, eachDayOfInterval, startOfMonth, getDay, addDays } from 'date-fns'
import { ru } from 'date-fns/locale'
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell, Area, AreaChart, CartesianGrid } from 'recharts'
import { habitsApi } from '../api/habits'
import Navigation from '../components/Navigation'
import clsx from 'clsx'

// Получить дату начала привычки
function getHabitStartDate(habit) {
  if (habit.start_date) return startOfDay(parseISO(habit.start_date))
  if (habit.created_at) return startOfDay(parseISO(habit.created_at))
  return startOfDay(new Date())
}

// Check if habit is frozen on date
function isHabitFrozenOnDate(freezes, date) {
  if (!freezes || freezes.length === 0) return false
  const checkDate = startOfDay(date)
  return freezes.some(freeze => {
    const start = startOfDay(parseISO(freeze.start_date))
    const end = startOfDay(parseISO(freeze.end_date))
    return !isBefore(checkDate, start) && !isAfter(checkDate, end)
  })
}

// Проверить ожидается ли привычка в дату
function isHabitExpectedOnDate(habit, date, freezes) {
  const checkDate = startOfDay(date)
  const startDate = getHabitStartDate(habit)
  if (checkDate < startDate || checkDate > startOfDay(new Date())) return false
  if (isHabitFrozenOnDate(freezes, date)) return false
  
  const dayOfWeek = checkDate.getDay() || 7
  if (habit.frequency === "daily") return true
  if (habit.frequency === "weekly") {
    if (habit.target_days?.length > 0) return habit.target_days.includes(dayOfWeek)
    return true
  }
  if (habit.frequency === "interval" && habit.target_count > 0) {
    const daysSinceStart = differenceInDays(checkDate, startDate)
    return daysSinceStart % habit.target_count === 0
  }
  return true
}

// Custom Tooltip Component
const CustomTooltip = ({ active, payload, label }) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-gray-900/95 backdrop-blur-sm px-4 py-3 rounded-xl shadow-2xl border border-gray-700/50">
        <p className="text-gray-400 text-xs mb-1">{label}</p>
        <p className="text-white font-bold text-lg">{payload[0].value}%</p>
      </div>
    )
  }
  return null
}

// Stat Card Component
const StatCard = ({ icon, value, label, emoji, color, delay = 0 }) => (
  <motion.div
    initial={{ opacity: 0, y: 20, scale: 0.95 }}
    animate={{ opacity: 1, y: 0, scale: 1 }}
    transition={{ delay, duration: 0.4, ease: "easeOut" }}
    className="relative overflow-hidden group"
  >
    <div className="absolute inset-0 bg-gradient-to-br from-white/80 to-white/40 dark:from-gray-800/80 dark:to-gray-900/40 backdrop-blur-xl rounded-2xl" />
    <div className={clsx(
      "absolute inset-0 opacity-[0.03] group-hover:opacity-[0.06] transition-opacity duration-500",
      `bg-gradient-to-br ${color}`
    )} />
    <div className="relative p-5 flex items-center gap-4">
      <div className={clsx(
        "w-14 h-14 rounded-2xl flex items-center justify-center text-2xl",
        "bg-gradient-to-br shadow-lg",
        color
      )}>
        {emoji}
      </div>
      <div className="flex-1">
        <p className="text-4xl font-bold text-gray-900 dark:text-white tracking-tight">
          {value}
        </p>
        <p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">{label}</p>
      </div>
    </div>
    <div className="absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r opacity-50 rounded-b-2xl" 
         style={{ background: `linear-gradient(to right, var(--tw-gradient-stops))` }} />
  </motion.div>
)

// Heatmap Cell Component
const HeatmapCell = ({ day, getColor, index }) => {
  const [showTooltip, setShowTooltip] = useState(false)
  const cellRef = useRef(null)
  
  return (
    <div className="relative" ref={cellRef}>
      <motion.div
        initial={{ scale: 0, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        transition={{ delay: index * 0.003, duration: 0.2 }}
        className={clsx(
          "w-full aspect-square rounded-[4px] cursor-pointer transition-all duration-200",
          "hover:ring-2 hover:ring-primary-400 hover:ring-offset-2 hover:ring-offset-gray-900",
          "hover:scale-110 hover:z-10",
          getColor(day.count, day.expected)
        )}
        onMouseEnter={() => setShowTooltip(true)}
        onMouseLeave={() => setShowTooltip(false)}
      />
      <AnimatePresence>
        {showTooltip && (
          <motion.div
            initial={{ opacity: 0, y: 5, scale: 0.9 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 5, scale: 0.9 }}
            className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 z-50 pointer-events-none"
          >
            <div className="bg-gray-900 text-white px-3 py-2 rounded-lg shadow-xl text-xs whitespace-nowrap">
              <p className="font-medium">{format(day.date, 'd MMMM', { locale: ru })}</p>
              <p className="text-primary-400 mt-0.5">
                {day.count}/{day.expected} выполнено
              </p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}

// Section Header Component
const SectionHeader = ({ icon: Icon, title, subtitle }) => (
  <div className="flex items-center gap-3 mb-5">
    <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-500/20 to-primary-600/10 flex items-center justify-center">
      <Icon className="text-primary-500" size={20} />
    </div>
    <div>
      <h3 className="text-lg font-bold text-gray-900 dark:text-white">{title}</h3>
      {subtitle && <p className="text-xs text-gray-500 dark:text-gray-400">{subtitle}</p>}
    </div>
  </div>
)

export default function Stats({ embedded = false }) {
  const [selectedHabitId, setSelectedHabitId] = useState(null)
  const [allHabitLogs, setAllHabitLogs] = useState({})
  const [allHabitStats, setAllHabitStats] = useState({})
  const [allHabitFreezes, setAllHabitFreezes] = useState({})
  const [dropdownOpen, setDropdownOpen] = useState(false)

  const { data: habits = [] } = useQuery({
    queryKey: ['habits'],
    queryFn: habitsApi.list,
  })

  useEffect(() => {
    if (habits.length > 0) loadAllHabitsData()
  }, [habits])

  const loadAllHabitsData = async () => {
    const logsMap = {}
    const statsMap = {}
    const freezesMap = {}
    
    await Promise.all(habits.map(async (habit) => {
      try {
        const [logs, stats, freezes] = await Promise.all([
          habitsApi.getLogs(habit.id, 90),
          habitsApi.getHabitStats(habit.id),
          habitsApi.getFreezes(habit.id),
        ])
        logsMap[habit.id] = logs
        statsMap[habit.id] = stats
        freezesMap[habit.id] = freezes
      } catch (e) {
        logsMap[habit.id] = []
        statsMap[habit.id] = null
        freezesMap[habit.id] = []
      }
    }))
    
    setAllHabitLogs(logsMap)
    setAllHabitStats(statsMap)
    setAllHabitFreezes(freezesMap)
  }

  // Combined stats for all or selected habit
  const computedStats = useMemo(() => {
    const targetHabits = selectedHabitId 
      ? habits.filter(h => h.id === selectedHabitId) 
      : habits
    
    let totalLogs = 0
    let totalExpected = 0
    let currentStreak = 0
    let bestStreak = 0
    
    targetHabits.forEach(habit => {
      const logs = allHabitLogs[habit.id] || []
      const stats = allHabitStats[habit.id]
      const freezes = allHabitFreezes[habit.id] || []
      
      totalLogs += logs.length
      
      for (let i = 0; i < 30; i++) {
        const date = subDays(new Date(), i)
        if (isHabitExpectedOnDate(habit, date, freezes)) totalExpected++
      }
      
      if (stats) {
        currentStreak = Math.max(currentStreak, stats.current_streak || 0)
        bestStreak = Math.max(bestStreak, stats.longest_streak || 0)
      }
    })
    
    const rate = totalExpected > 0 ? Math.round((totalLogs / totalExpected) * 100) : 0
    
    return { totalLogs, currentStreak, bestStreak, rate }
  }, [selectedHabitId, habits, allHabitLogs, allHabitStats, allHabitFreezes])

  // Heatmap data (12 weeks = 84 days)
  const heatmapData = useMemo(() => {
    const today = startOfDay(new Date())
    const startDate = subDays(today, 83)
    const days = eachDayOfInterval({ start: startDate, end: today })
    
    // Align to week start (Monday)
    const firstDayOfWeek = getDay(startDate) || 7
    const paddingDays = firstDayOfWeek - 1
    
    return days.map(day => {
      const dateStr = format(day, 'yyyy-MM-dd')
      let count = 0
      let expected = 0
      
      const targetHabits = selectedHabitId 
        ? habits.filter(h => h.id === selectedHabitId) 
        : habits
      
      targetHabits.forEach(habit => {
        const logs = allHabitLogs[habit.id] || []
        const freezes = allHabitFreezes[habit.id] || []
        
        if (logs.some(l => l.date.split('T')[0] === dateStr)) count++
        if (isHabitExpectedOnDate(habit, day, freezes)) expected++
      })
      
      return { date: day, dateStr, count, expected }
    })
  }, [selectedHabitId, habits, allHabitLogs, allHabitFreezes])

  // Get unique months for heatmap labels
  const heatmapMonths = useMemo(() => {
    const months = []
    let currentMonth = null
    heatmapData.forEach((day, index) => {
      const month = format(day.date, 'MMM', { locale: ru })
      if (month !== currentMonth) {
        months.push({ month, index: Math.floor(index / 7) })
        currentMonth = month
      }
    })
    return months
  }, [heatmapData])

  // Line chart data (30 days completion rate)
  const lineChartData = useMemo(() => {
    const data = []
    for (let i = 29; i >= 0; i--) {
      const date = subDays(new Date(), i)
      const dateStr = format(date, 'yyyy-MM-dd')
      let completed = 0
      let expected = 0
      
      const targetHabits = selectedHabitId 
        ? habits.filter(h => h.id === selectedHabitId) 
        : habits
      
      targetHabits.forEach(habit => {
        const logs = allHabitLogs[habit.id] || []
        const freezes = allHabitFreezes[habit.id] || []
        
        if (logs.some(l => l.date.split('T')[0] === dateStr)) completed++
        if (isHabitExpectedOnDate(habit, date, freezes)) expected++
      })
      
      const rate = expected > 0 ? Math.round((completed / expected) * 100) : 0
      data.push({ date: format(date, 'dd.MM'), fullDate: format(date, 'd MMM', { locale: ru }), rate, completed, expected })
    }
    return data
  }, [selectedHabitId, habits, allHabitLogs, allHabitFreezes])

  // Bar chart data (habits comparison)
  const barChartData = useMemo(() => {
    return habits.map(habit => {
      const logs = allHabitLogs[habit.id] || []
      const freezes = allHabitFreezes[habit.id] || []
      
      let expected = 0
      for (let i = 0; i < 30; i++) {
        const date = subDays(new Date(), i)
        if (isHabitExpectedOnDate(habit, date, freezes)) expected++
      }
      
      const completed = logs.filter(l => {
        const logDate = parseISO(l.date.split('T')[0])
        return differenceInDays(new Date(), logDate) < 30
      }).length
      
      const rate = expected > 0 ? Math.round((completed / expected) * 100) : 0
      
      return {
        name: habit.name,
        icon: habit.icon,
        rate,
        color: habit.color || '#0d9488',
        completed,
        expected
      }
    }).sort((a, b) => b.rate - a.rate)
  }, [habits, allHabitLogs, allHabitFreezes])

  // Heatmap intensity color - 5 levels
  const getHeatmapColor = (count, expected) => {
    if (expected === 0) return 'bg-[#1a1a1a]'
    const ratio = count / expected
    if (ratio === 0) return 'bg-[#1f1f1f] dark:bg-[#1a1a1a]'
    if (ratio < 0.4) return 'bg-teal-900/80'
    if (ratio < 0.7) return 'bg-teal-700'
    if (ratio < 1) return 'bg-teal-600'
    return 'bg-teal-400 shadow-sm shadow-teal-400/30'
  }

  const selectedHabit = habits.find(h => h.id === selectedHabitId)

  // Group heatmap by weeks (columns)
  const heatmapWeeks = useMemo(() => {
    const weeks = []
    for (let i = 0; i < heatmapData.length; i += 7) {
      weeks.push(heatmapData.slice(i, i + 7))
    }
    return weeks
  }, [heatmapData])

  return (
    <div className={embedded ? "" : "min-h-screen bg-gray-950 pb-24 transition-colors duration-300"}>
      {/* Gradient Background */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-0 left-1/4 w-96 h-96 bg-primary-500/10 rounded-full blur-3xl" />
        <div className="absolute bottom-1/4 right-0 w-80 h-80 bg-teal-500/5 rounded-full blur-3xl" />
      </div>
      
      {!embedded && <header className="relative bg-gray-900/50 backdrop-blur-xl border-b border-gray-800/50 sticky top-0 z-20">
        <div className="max-w-lg mx-auto px-5 py-5">
          <div className="flex items-center gap-3">
            <div className="w-11 h-11 rounded-2xl bg-gradient-to-br from-primary-500 to-teal-600 flex items-center justify-center shadow-lg shadow-primary-500/25">
              <BarChart3 className="text-white" size={22} />
            </div>
            <div>
              <h1 className="text-xl font-bold text-white flex items-center gap-2">
                Статистика
                <Sparkles className="text-primary-400" size={16} />
              </h1>
              <p className="text-sm text-gray-400">Отслеживай свой прогресс</p>
            </div>
          </div>
        </div>
      </header>}

      <main className="relative max-w-lg mx-auto px-5 py-6 space-y-8">
        
        {/* Habit Selector Dropdown */}
        <motion.div 
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="relative"
        >
          <button
            onClick={() => setDropdownOpen(!dropdownOpen)}
            className="w-full bg-gray-900/80 backdrop-blur-xl border border-gray-800 rounded-2xl p-4 flex items-center justify-between hover:border-gray-700 transition-all duration-300"
          >
            <div className="flex items-center gap-3">
              {selectedHabit ? (
                <>
                  <div 
                    className="w-10 h-10 rounded-xl flex items-center justify-center text-xl"
                    style={{ backgroundColor: selectedHabit.color + '20' }}
                  >
                    {selectedHabit.icon}
                  </div>
                  <div className="text-left">
                    <span className="font-semibold text-white block">{selectedHabit.name}</span>
                    <span className="text-xs text-gray-500">Выбранная привычка</span>
                  </div>
                </>
              ) : (
                <>
                  <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-500/20 to-teal-500/10 flex items-center justify-center">
                    <Target className="text-primary-400" size={20} />
                  </div>
                  <div className="text-left">
                    <span className="font-semibold text-white block">Все привычки</span>
                    <span className="text-xs text-gray-500">{habits.length} привычек</span>
                  </div>
                </>
              )}
            </div>
            <ChevronDown className={clsx(
              "text-gray-500 transition-transform duration-300",
              dropdownOpen && "rotate-180"
            )} size={20} />
          </button>
          
          <AnimatePresence>
            {dropdownOpen && (
              <motion.div
                initial={{ opacity: 0, y: -10, scale: 0.95 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                exit={{ opacity: 0, y: -10, scale: 0.95 }}
                transition={{ duration: 0.2 }}
                className="absolute top-full left-0 right-0 mt-2 bg-gray-900 backdrop-blur-xl rounded-2xl shadow-2xl border border-gray-800 z-30 overflow-hidden max-h-80 overflow-y-auto"
              >
                <button
                  onClick={() => { setSelectedHabitId(null); setDropdownOpen(false) }}
                  className={clsx(
                    "w-full p-4 flex items-center gap-3 hover:bg-gray-800 transition-colors border-b border-gray-800/50",
                    !selectedHabitId && "bg-primary-500/10"
                  )}
                >
                  <Target className="text-primary-400" size={20} />
                  <span className="font-medium text-white">Все привычки</span>
                  {!selectedHabitId && <div className="ml-auto w-2 h-2 rounded-full bg-primary-400" />}
                </button>
                {habits.map(habit => (
                  <button
                    key={habit.id}
                    onClick={() => { setSelectedHabitId(habit.id); setDropdownOpen(false) }}
                    className={clsx(
                      "w-full p-4 flex items-center gap-3 hover:bg-gray-800 transition-colors",
                      selectedHabitId === habit.id && "bg-primary-500/10"
                    )}
                  >
                    <span className="text-xl">{habit.icon}</span>
                    <span className="font-medium text-white">{habit.name}</span>
                    {selectedHabitId === habit.id && <div className="ml-auto w-2 h-2 rounded-full bg-primary-400" />}
                  </button>
                ))}
              </motion.div>
            )}
          </AnimatePresence>
        </motion.div>

        {/* Stats Cards */}
        <section>
          <div className="grid grid-cols-2 gap-4">
            <StatCard
              emoji="🔥"
              value={computedStats.currentStreak}
              label="Текущий streak"
              color="from-orange-500/20 to-red-500/10"
              delay={0}
            />
            <StatCard
              emoji="🏆"
              value={computedStats.bestStreak}
              label="Лучший streak"
              color="from-yellow-500/20 to-amber-500/10"
              delay={0.1}
            />
            <StatCard
              emoji="✅"
              value={computedStats.totalLogs}
              label="Всего выполнено"
              color="from-green-500/20 to-emerald-500/10"
              delay={0.2}
            />
            <StatCard
              emoji="📈"
              value={`${computedStats.rate}%`}
              label="Completion rate"
              color="from-primary-500/20 to-teal-500/10"
              delay={0.3}
            />
          </div>
        </section>

        {/* Heatmap Calendar */}
        <motion.section
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="bg-gray-900/60 backdrop-blur-xl border border-gray-800/50 rounded-3xl p-6"
        >
          <SectionHeader 
            icon={Calendar} 
            title="Активность" 
            subtitle="Последние 12 недель"
          />
          
          {/* Month labels */}
          <div className="flex mb-2 ml-8">
            {heatmapMonths.map((m, i) => (
              <div 
                key={i} 
                className="text-[10px] text-gray-500 capitalize"
                style={{ 
                  position: 'absolute',
                  left: `${32 + m.index * 18}px`
                }}
              >
                {m.month}
              </div>
            ))}
          </div>
          
          <div className="flex gap-1 mt-6">
            {/* Day labels */}
            <div className="flex flex-col gap-[3px] pr-2">
              {['Пн', '', 'Ср', '', 'Пт', '', 'Вс'].map((d, i) => (
                <div key={i} className="h-[14px] text-[10px] text-gray-500 flex items-center">
                  {d}
                </div>
              ))}
            </div>
            
            {/* Heatmap grid */}
            <div className="flex gap-[3px] flex-1">
              {heatmapWeeks.map((week, weekIndex) => (
                <div key={weekIndex} className="flex flex-col gap-[3px] flex-1">
                  {week.map((day, dayIndex) => (
                    <HeatmapCell
                      key={day.dateStr}
                      day={day}
                      getColor={getHeatmapColor}
                      index={weekIndex * 7 + dayIndex}
                    />
                  ))}
                </div>
              ))}
            </div>
          </div>
          
          {/* Legend */}
          <div className="flex items-center justify-end gap-2 mt-5 pt-4 border-t border-gray-800/50">
            <span className="text-xs text-gray-500">Меньше</span>
            <div className="flex gap-1">
              <div className="w-3.5 h-3.5 rounded-[3px] bg-[#1f1f1f]" />
              <div className="w-3.5 h-3.5 rounded-[3px] bg-teal-900/80" />
              <div className="w-3.5 h-3.5 rounded-[3px] bg-teal-700" />
              <div className="w-3.5 h-3.5 rounded-[3px] bg-teal-600" />
              <div className="w-3.5 h-3.5 rounded-[3px] bg-teal-400" />
            </div>
            <span className="text-xs text-gray-500">Больше</span>
          </div>
        </motion.section>

        {/* Line Chart - Completion Rate */}
        <motion.section
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="bg-gray-900/60 backdrop-blur-xl border border-gray-800/50 rounded-3xl p-6"
        >
          <SectionHeader 
            icon={TrendingUp} 
            title="Completion Rate" 
            subtitle="Динамика за 30 дней"
          />
          
          <div className="h-56">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={lineChartData}>
                <defs>
                  <linearGradient id="colorRate" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#0d9488" stopOpacity={0.4} />
                    <stop offset="100%" stopColor="#0d9488" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid 
                  strokeDasharray="3 3" 
                  stroke="#374151" 
                  strokeOpacity={0.3}
                  vertical={false}
                />
                <XAxis 
                  dataKey="date" 
                  tick={{ fontSize: 10, fill: '#6b7280' }}
                  axisLine={false}
                  tickLine={false}
                  interval="preserveStartEnd"
                />
                <YAxis 
                  tick={{ fontSize: 10, fill: '#6b7280' }}
                  axisLine={false}
                  tickLine={false}
                  domain={[0, 100]}
                  width={30}
                  tickFormatter={(v) => `${v}%`}
                />
                <Tooltip content={<CustomTooltip />} />
                <Area
                  type="monotone"
                  dataKey="rate"
                  stroke="#0d9488"
                  strokeWidth={2.5}
                  fill="url(#colorRate)"
                  dot={false}
                  activeDot={{ 
                    r: 6, 
                    fill: '#0d9488', 
                    stroke: '#fff',
                    strokeWidth: 2,
                    className: 'drop-shadow-lg'
                  }}
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </motion.section>

        {/* Bar Chart - Habits Comparison */}
        {!selectedHabitId && habits.length > 1 && (
          <motion.section
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.4 }}
            className="bg-gray-900/60 backdrop-blur-xl border border-gray-800/50 rounded-3xl p-6"
          >
            <SectionHeader 
              icon={BarChart3} 
              title="По привычкам" 
              subtitle="Рейтинг за 30 дней"
            />
            
            <div className="space-y-3">
              {barChartData.map((habit, index) => (
                <motion.div
                  key={habit.name}
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.1 * index }}
                  className="relative"
                >
                  <div className="flex items-center gap-3 mb-2">
                    <span className="text-lg">{habit.icon}</span>
                    <span className="text-sm font-medium text-white flex-1 truncate">{habit.name}</span>
                    <span className="text-sm font-bold text-primary-400">{habit.rate}%</span>
                  </div>
                  <div className="h-2 bg-gray-800 rounded-full overflow-hidden">
                    <motion.div
                      initial={{ width: 0 }}
                      animate={{ width: `${habit.rate}%` }}
                      transition={{ delay: 0.2 + 0.1 * index, duration: 0.8, ease: "easeOut" }}
                      className="h-full rounded-full"
                      style={{ 
                        backgroundColor: habit.color,
                        boxShadow: `0 0 10px ${habit.color}50`
                      }}
                    />
                  </div>
                  <div className="flex justify-between mt-1">
                    <span className="text-[10px] text-gray-500">{habit.completed} выполнено</span>
                    <span className="text-[10px] text-gray-500">{habit.expected} ожидалось</span>
                  </div>
                </motion.div>
              ))}
            </div>
          </motion.section>
        )}

        {habits.length === 0 && (
          <motion.div 
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-gray-900/60 backdrop-blur-xl border border-gray-800/50 rounded-3xl p-12 text-center"
          >
            <div className="w-16 h-16 rounded-2xl bg-gray-800 flex items-center justify-center mx-auto mb-4">
              <Zap className="text-gray-600" size={32} />
            </div>
            <p className="text-gray-400 font-medium">Создайте привычки,</p>
            <p className="text-gray-500 text-sm">чтобы видеть статистику</p>
          </motion.div>
        )}
      </main>

      {!embedded && <Navigation />}
    </div>
  )
}
