All files / pages Stats.jsx

75.39% Statements 144/191
65.89% Branches 85/129
66.66% Functions 30/45
79.75% Lines 130/163

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696                          348x 348x 348x         8x                     348x 348x 348x 8x   8x 348x 8x       8x       8x       1x                         1x 24x                                                               1x 504x 504x   504x                                                                         1x 12x                       7x 7x 7x 7x 7x   7x         7x 5x     7x 1x 1x 1x   1x 1x 1x                 1x 1x 1x       1x 1x 1x       7x 6x       6x 6x 6x 6x   6x 2x 2x 2x   2x   2x 60x 60x     2x           6x   6x       7x 6x 6x 6x     6x 6x   6x 504x 504x 504x   504x       504x 168x 168x   168x 168x     504x         7x 6x 6x 6x 504x 504x 18x 18x     6x       7x 6x 6x 180x 180x 180x 180x   180x       180x 60x 60x   60x 60x     180x 180x   180x       7x 6x 2x 2x   2x 2x 60x 60x     2x         2x   2x                       7x 504x 2x 2x             7x     7x 6x 6x 72x   6x     7x                                                                   1x                                                                                                               2x                                                                                                                                       18x                                 42x                 72x   504x                                                                                                                                                                                                                                                                                                                              
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) {
  Iif (habit.start_date) return startOfDay(parseISO(habit.start_date))
  Iif (habit.created_at) return startOfDay(parseISO(habit.created_at))
  return startOfDay(new Date())
}
 
// Check if habit is frozen on date
function isHabitFrozenOnDate(freezes, date) {
  Eif (!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
  Iif (isHabitFrozenOnDate(freezes, date)) return false
  
  const dayOfWeek = checkDate.getDay() || 7
  Iif (habit.frequency === "daily") return true
  Iif (habit.frequency === "weekly") {
    if (habit.target_days?.length > 0) return habit.target_days.includes(dayOfWeek)
    return true
  }
  Iif (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++
      }
      
      Iif (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] || []
        
        Iif (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] || []
        
        Iif (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
    Eif (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>
  )
}