/* =====================================================================
   Дизайн-токены.
   Telegram прокидывает цвета темы пользователя в CSS-переменные --tg-theme-*,
   поэтому Mini App выглядит "родной" в любой теме. Второе значение в var(...) —
   запасное, если открыть страницу вне Telegram.
   ===================================================================== */
:root {
    --bg: var(--tg-theme-bg-color, #fff);
    --text: var(--tg-theme-text-color, #000);
    --hint: var(--tg-theme-hint-color, #8e8e93);
    --card: var(--tg-theme-secondary-bg-color, #f2f2f5);
    --accent: var(--tg-theme-button-color, #2481cc);
    --accent-text: var(--tg-theme-button-text-color, #fff);
    --link: var(--tg-theme-link-color, #2481cc);
    --danger: var(--tg-theme-destructive-text-color, #e53935);
    --success: #31a24c;
    --separator: color-mix(in srgb, var(--hint) 22%, transparent);

    /* Полупрозрачные "подложки" под иконки — из тех же цветов темы.
       color-mix смешивает цвет с прозрачным: получается мягкий оттенок, работает и в тёмной теме. */
    --tint-accent: color-mix(in srgb, var(--accent) 14%, transparent);
    --tint-success: color-mix(in srgb, var(--success) 16%, transparent);
    --tint-danger: color-mix(in srgb, var(--danger) 14%, transparent);
    --tint-neutral: color-mix(in srgb, var(--hint) 16%, transparent);

    /* Градиент карточки баланса: акцентный цвет Telegram -> он же, сдвинутый к фиолетовому */
    --hero-gradient: linear-gradient(135deg, var(--accent) 0%, color-mix(in oklab, var(--accent) 55%, #8e44ff) 100%);

    /* Скругления */
    --r-sm: 10px;
    --r-md: 14px;
    --r-lg: 18px;
    --r-xl: 24px;

    --shadow-lg: 0 8px 24px rgb(0 0 0 / .18);

    /* Кривые анимации: ease — плавное торможение, spring — с лёгким "перелётом" */
    --ease: cubic-bezier(.2, .8, .2, 1);
    --spring: cubic-bezier(.34, 1.56, .64, 1);

    /* Цвета графиков. Акцент — проверенный "слот 1" палитры для визуализаций;
       серый — фон/контекст. Для тёмной темы — свои значения (не просто инверсия).
       Тема (data-theme) выставляется из Telegram в app.js. */
    --viz-accent: #2a78d6;
    --viz-context: #c3c2b7;
    --viz-track: #e1e0d9;
}
:root[data-theme="dark"] {
    --viz-accent: #3987e5;
    --viz-context: #52514e;
    --viz-track: #2c2c2a;
}

* { box-sizing: border-box; }

body {
    font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
    margin: 0;
    padding: 16px 16px 32px;
    background: var(--bg);
    color: var(--text);
    -webkit-tap-highlight-color: transparent;
    overflow-x: hidden;
}

button { font: inherit; color: inherit; }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }

.hint { color: var(--hint); font-size: 14px; }
.error { color: var(--danger); }
.screen[hidden] { display: none; }

/* =====================================================================
   Анимации
   ===================================================================== */

/* Экран появляется плавно. Анимация запускается заново каждый раз, когда
   экран переходит из display:none в видимое состояние (атрибут hidden снят). */
.screen { animation: screen-in .32s var(--ease); }
@keyframes screen-in {
    from { opacity: 0; transform: translateY(10px); }
}

/* Элементы списка "выезжают" по очереди: задержка = номер элемента (--i) × 35 мс */
.animate-in {
    animation: item-in .42s var(--ease) both;
    animation-delay: calc(var(--i, 0) * 35ms);
}
@keyframes item-in {
    from { opacity: 0; transform: translateY(8px); }
}

@keyframes pop {
    0% { transform: scale(.92); }
    100% { transform: scale(1); }
}

/* "Нажимаемые" элементы слегка уменьшаются под пальцем — тактильный отклик */
.balance-card, .quick-action, .account-card, .nav-tile, .chip, .cal-nav,
.icon-choice, .danger-button, .link-button, .section-action, .trend-col {
    transition: transform .18s var(--ease), background-color .2s, box-shadow .2s, opacity .2s;
}
:is(.balance-card, .quick-action, .account-card, .nav-tile, .chip, .cal-nav,
    .icon-choice, .danger-button, .link-button, .section-action, .trend-col):active {
    transform: scale(.96);
}

/* Скелетоны — мерцающие заглушки на время загрузки (вместо текста "Загрузка…") */
.skeleton {
    border-radius: var(--r-lg);
    background: linear-gradient(90deg,
        var(--card) 25%, color-mix(in srgb, var(--card), var(--hint) 14%) 50%, var(--card) 75%);
    background-size: 200% 100%;
    animation: shimmer 1.3s linear infinite;
}
.skeleton-card { height: 168px; border-radius: var(--r-xl); }
.skeleton-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 14px 0; }
.skeleton-pill { height: 76px; }
.skeleton-list { height: 240px; margin-top: 14px; }
@keyframes shimmer {
    from { background-position: 200% 0; }
    to { background-position: -200% 0; }
}

/* Всплывающее уведомление сверху ("Сохранено") */
.toast {
    position: fixed; top: 12px; left: 50%; z-index: 100;
    max-width: calc(100% - 32px);
    padding: 10px 18px; border-radius: 999px;
    background: var(--text); color: var(--bg);
    font-size: 14px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    box-shadow: var(--shadow-lg);
    transform: translate(-50%, -160%);
    transition: transform .4s var(--spring);
    pointer-events: none;
}
.toast.show { transform: translate(-50%, 0); }

/* Уважение к системной настройке "уменьшить движение" (важно для людей с вестибулярными нарушениями) */
@media (prefers-reduced-motion: reduce) {
    *, *::before, *::after {
        animation-duration: .01ms !important;
        animation-delay: 0s !important;
        animation-iteration-count: 1 !important;
        transition-duration: .01ms !important;
    }
}

/* =====================================================================
   Шапка
   ===================================================================== */
header {
    display: flex; justify-content: space-between; align-items: center; gap: 12px;
    margin-bottom: 16px;
}
.hello { display: flex; align-items: center; gap: 12px; min-width: 0; }
.avatar {
    position: relative; flex-shrink: 0;
    width: 42px; height: 42px; border-radius: 50%; overflow: hidden;
    display: grid; place-items: center;
    background: var(--hero-gradient); color: var(--accent-text);
    font-size: 18px; font-weight: 700;
}
.avatar img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.hello-hint { color: var(--hint); font-size: 13px; }
.hello-name { font-size: 17px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

header select {
    width: auto; flex-shrink: 0;
    font-size: 14px; font-weight: 600;
    padding: 8px 30px 8px 12px; border-radius: 999px;
}

/* =====================================================================
   Главный экран
   ===================================================================== */

/* Карточка баланса */
.balance-card {
    position: relative; overflow: hidden;
    display: block; width: 100%; padding: 20px;
    border: none; border-radius: var(--r-xl);
    background: var(--hero-gradient); color: var(--accent-text);
    text-align: left; cursor: pointer;
    box-shadow: 0 14px 30px -14px color-mix(in srgb, var(--accent) 75%, transparent);
}
/* Декоративные полупрозрачные круги */
.balance-card::before, .balance-card::after {
    content: ''; position: absolute; border-radius: 50%; pointer-events: none;
    background: rgb(255 255 255 / .12);
}
.balance-card::before { width: 190px; height: 190px; right: -60px; top: -80px; }
.balance-card::after { width: 120px; height: 120px; right: 50px; bottom: -75px; background: rgb(255 255 255 / .08); }

.balance-label { position: relative; font-size: 14px; opacity: .85; }
.balance-value {
    position: relative;
    font-size: 36px; font-weight: 800; letter-spacing: -.02em; margin: 4px 0 16px;
    font-variant-numeric: tabular-nums; /* одинаковая ширина цифр — число не "дрожит" при анимации */
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.balance-month { position: relative; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.balance-stat {
    min-width: 0; padding: 10px 12px; border-radius: var(--r-md);
    background: rgb(255 255 255 / .16);
}
.balance-stat-label { display: flex; align-items: center; gap: 6px; font-size: 12px; opacity: .9; }
.balance-stat-icon {
    width: 18px; height: 18px; border-radius: 50%; flex-shrink: 0;
    display: grid; place-items: center;
    background: rgb(255 255 255 / .25); font-size: 11px; font-weight: 700;
}
.balance-stat-value {
    margin-top: 4px; font-size: 15px; font-weight: 700;
    font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}

/* Быстрые действия: Расход / Доход / Перевод */
.quick-actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 14px; }
.quick-action {
    display: flex; flex-direction: column; align-items: center; gap: 6px;
    padding: 12px 4px; border: none; border-radius: var(--r-lg);
    background: var(--card); font-size: 13px; font-weight: 600; cursor: pointer;
}
.quick-action-icon {
    width: 42px; height: 42px; border-radius: 50%;
    display: grid; place-items: center; font-size: 22px; font-weight: 700; line-height: 1;
}
.quick-action.expense .quick-action-icon { background: var(--tint-danger); color: var(--danger); }
.quick-action.income .quick-action-icon { background: var(--tint-success); color: var(--success); }
.quick-action.transfer .quick-action-icon { background: var(--tint-accent); color: var(--accent); }

/* Заголовок секции с действием справа */
.section-header {
    display: flex; justify-content: space-between; align-items: baseline;
    margin: 26px 4px 10px;
}
.section-header h2 { margin: 0; font-size: 19px; font-weight: 700; }
.section-action {
    background: none; border: none; padding: 4px 0;
    color: var(--link); font-size: 14px; font-weight: 600; cursor: pointer;
}

/* Лента карточек счетов — прокручивается пальцем вбок, "прилипает" к карточкам */
.accounts-scroll {
    display: flex; gap: 10px;
    overflow-x: auto; scroll-snap-type: x mandatory; scroll-padding: 0 16px;
    margin: 0 -16px; padding: 2px 16px 6px;
    scrollbar-width: none;
}
.accounts-scroll::-webkit-scrollbar { display: none; }
.account-card {
    flex: 0 0 auto; width: 152px; scroll-snap-align: start;
    display: flex; flex-direction: column; align-items: flex-start; gap: 12px;
    padding: 14px; border: none; border-radius: var(--r-lg);
    background: var(--card); text-align: left; cursor: pointer;
}
.account-card .row-icon { width: 36px; height: 36px; font-size: 18px; }
.account-name {
    width: 100%; color: var(--hint); font-size: 13px;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.account-balance {
    width: 100%; margin-top: 2px; font-size: 16px; font-weight: 700;
    font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.account-card.add {
    width: 104px; justify-content: center; align-items: center; gap: 6px;
    background: transparent; border: 1.5px dashed var(--separator);
    color: var(--link); font-size: 14px; font-weight: 600;
}
.account-card.add span:first-child { font-size: 24px; line-height: 1; }

/* Плитки навигации */
.nav-tiles { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 14px; }
.nav-tile {
    display: flex; align-items: center; gap: 8px;
    padding: 10px; border: none; border-radius: var(--r-md);
    background: var(--card); font-size: 13px; font-weight: 600; cursor: pointer;
    min-width: 0;
}
.nav-tile span:first-child { font-size: 18px; flex-shrink: 0; }
.nav-tile span:last-child { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.total { font-size: 34px; font-weight: 700; margin: 2px 0 0; font-variant-numeric: tabular-nums; }

.section-title {
    font-size: 13px; text-transform: uppercase; letter-spacing: .04em;
    color: var(--hint); margin: 24px 4px 8px;
}

/* =====================================================================
   Списки
   ===================================================================== */
.list { background: var(--card); border-radius: var(--r-lg); overflow: hidden; }

/* Строка списка — это <button>, чтобы она была кликабельной и доступной с клавиатуры */
.row {
    display: flex; align-items: center; gap: 12px;
    width: 100%; padding: 10px 14px;
    background: none; border: none; text-align: left; cursor: pointer;
    transition: background-color .15s;
}
.row + .row { border-top: 1px solid var(--separator); }
.row:active { background: var(--separator); }

/* Иконка в цветной "плашке" */
.row-icon {
    width: 40px; height: 40px; border-radius: 12px; flex-shrink: 0;
    display: grid; place-items: center;
    font-size: 20px; line-height: 1;
    background: var(--tint-accent);
}
.row-icon.expense { background: var(--tint-neutral); }
.row-icon.income { background: var(--tint-success); }
.row-icon.transfer { background: var(--tint-accent); }

.row-main { flex: 1; min-width: 0; }
.row-title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.row-subtitle {
    color: var(--hint); font-size: 13px; margin-top: 2px;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}

.amount { font-weight: 700; font-variant-numeric: tabular-nums; white-space: nowrap; }
.amount.income { color: var(--success); }
.amount.transfer { color: var(--hint); }
.negative { color: var(--danger); }

.date-heading { color: var(--hint); font-size: 13px; font-weight: 600; padding: 14px 4px 6px; }
.empty { color: var(--hint); text-align: center; padding: 28px 16px; white-space: pre-line; }
.empty-icon { display: block; font-size: 40px; margin-bottom: 8px; }

.link-button {
    background: none; border: none; padding: 12px 4px;
    color: var(--link); font-weight: 600; cursor: pointer;
}

/* =====================================================================
   Формы
   ===================================================================== */
.form-title { font-size: 22px; font-weight: 800; letter-spacing: -.01em; margin: 4px 0 16px; }
.form-error {
    color: var(--danger); margin: 0 0 16px; padding: 10px 14px; white-space: pre-line;
    background: var(--tint-danger); border-radius: var(--r-md);
    animation: pop .3s var(--spring);
}
.form-error[hidden] { display: none; }

.field { display: block; margin-bottom: 16px; }
.field[hidden] { display: none; }
.field-label { display: block; font-size: 13px; font-weight: 600; color: var(--hint); margin: 0 4px 6px; }

input, select {
    width: 100%;
    font: inherit; font-size: 16px; /* 16px — иначе iOS зумит страницу при фокусе */
    color: var(--text); background: var(--card);
    border: 1.5px solid transparent; border-radius: var(--r-md);
    padding: 12px 14px; outline: none;
    appearance: none;
    transition: border-color .2s, box-shadow .2s;
}
select {
    /* своя стрелка вместо системной (её убрали через appearance: none) */
    background-image: linear-gradient(45deg, transparent 50%, var(--hint) 50%),
                      linear-gradient(135deg, var(--hint) 50%, transparent 50%);
    background-position: calc(100% - 18px) 50%, calc(100% - 13px) 50%;
    background-size: 5px 5px;
    background-repeat: no-repeat;
    padding-right: 32px;
}
input:focus, select:focus {
    border-color: var(--accent);
    box-shadow: 0 0 0 4px var(--tint-accent);
}

/* Крупная сумма по центру; цвет зависит от типа операции (data-type на экране) */
.amount-input {
    font-size: 34px; font-weight: 800; text-align: center; letter-spacing: -.01em;
    padding: 16px; font-variant-numeric: tabular-nums;
    transition: color .25s, border-color .2s, box-shadow .2s;
}
.screen[data-type="Income"] .amount-input { color: var(--success); }
.screen[data-type="Transfer"] .amount-input { color: var(--accent); }

/* Переключатель с "ползунком": подложка ::before едет под выбранную кнопку.
   --count (число вариантов) и --index (выбранный) задаёт app.js. */
.segmented {
    position: relative;
    display: grid; grid-template-columns: repeat(var(--count, 2), 1fr);
    background: var(--card); border-radius: var(--r-md); padding: 3px; margin-bottom: 16px;
}
.segmented::before {
    content: ''; position: absolute; top: 3px; bottom: 3px; left: 3px;
    width: calc((100% - 6px) / var(--count, 2));
    border-radius: 11px;
    background: var(--bg);
    box-shadow: 0 1px 4px rgb(0 0 0 / .14);
    transform: translateX(calc(var(--index, 0) * 100%));
    transition: transform .35s var(--ease);
}
.segmented button {
    position: relative; z-index: 1; /* поверх ползунка */
    padding: 9px 4px; border: none; background: none;
    font-size: 14px; cursor: pointer; color: var(--hint);
    transition: color .2s;
}
.segmented button.active { color: var(--text); font-weight: 600; }

/* Категории — "чипсы" */
.chips { display: flex; flex-wrap: wrap; gap: 8px; }
.chip {
    border: none; border-radius: 999px; padding: 8px 14px;
    background: var(--card); font-size: 14px; cursor: pointer;
}
.chip.active {
    background: var(--accent); color: var(--accent-text); font-weight: 600;
    animation: pop .3s var(--spring);
}

/* Выбор иконки категории — сетка эмодзи */
.icon-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 6px; }
.icon-choice {
    aspect-ratio: 1; font-size: 22px; padding: 0;
    border: 2px solid transparent; border-radius: 12px;
    background: var(--card); cursor: pointer;
}
.icon-choice.active { border-color: var(--accent); background: var(--tint-accent); animation: pop .3s var(--spring); }

.danger-button {
    width: 100%; margin-top: 8px; padding: 13px;
    border: none; border-radius: var(--r-md);
    background: var(--tint-danger); color: var(--danger);
    font-weight: 600; cursor: pointer;
}

/* =====================================================================
   Календарь
   ===================================================================== */
.cal-header { display: flex; align-items: center; justify-content: space-between; margin: 4px 0 14px; }
.cal-title { font-size: 20px; font-weight: 800; }
.cal-nav {
    width: 40px; height: 40px; font-size: 22px; line-height: 1;
    border: none; border-radius: 50%; background: var(--card); cursor: pointer;
}
.cal-grid {
    display: grid; grid-template-columns: repeat(7, 1fr); gap: 4px;
    background: var(--card); border-radius: var(--r-lg); padding: 10px 8px;
}
.cal-weekday { text-align: center; font-size: 12px; font-weight: 600; color: var(--hint); padding-bottom: 4px; }
.cal-day {
    aspect-ratio: 1; padding: 0;
    display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px;
    border: none; border-radius: 50%; background: none;
    font-size: 15px; cursor: pointer;
    transition: background-color .2s, color .2s;
}
.cal-day.today { font-weight: 800; color: var(--accent); }
.cal-day.selected {
    background: var(--accent); color: var(--accent-text);
    box-shadow: 0 6px 14px -6px color-mix(in srgb, var(--accent) 80%, transparent);
}
.cal-day.future { opacity: .4; }
.cal-dots { display: flex; gap: 3px; height: 5px; }
.dot { width: 5px; height: 5px; border-radius: 50%; }
.dot.expense { background: var(--danger); }
.dot.income { background: var(--success); }
.dot.transfer { background: var(--hint); }
.cal-day.selected .dot { box-shadow: 0 0 0 1px var(--accent-text); }

/* Итоги месяца / дня: две колонки */
.summary {
    display: flex; gap: 12px; margin-top: 12px;
    background: var(--card); border-radius: var(--r-lg); padding: 12px 16px;
}
.summary > div { flex: 1; min-width: 0; }
.summary .amount { font-size: 17px; }
.day-title { font-size: 18px; font-weight: 800; margin: 24px 4px 0; }
.day-title::first-letter { text-transform: uppercase; }

/* =====================================================================
   Статистика
   ===================================================================== */
/* Пока грузится новый месяц — держим старые данные полупрозрачными, без "прыжка" вёрстки */
.stats-body { transition: opacity .2s; }
.stats-body.loading { opacity: .5; }

/* Главное число месяца */
.hero-label { color: var(--hint); font-size: 14px; margin-top: 4px; }
.hero-value { font-size: 36px; font-weight: 800; letter-spacing: -.02em; margin: 2px 0 4px; }
.delta { font-size: 14px; color: var(--hint); }
.delta .up-bad, .delta .down-bad { color: var(--danger); font-weight: 600; }
.delta .up-good, .delta .down-good { color: var(--success); font-weight: 600; }

/* Горизонтальные полосы по категориям: одна шкала, один цвет, отсортированы по убыванию */
.cat-row { padding: 10px 14px; }
.cat-row + .cat-row { border-top: 1px solid var(--separator); }
.cat-line { display: flex; align-items: center; gap: 10px; }
.cat-line .row-main { font-weight: 600; }
.cat-meta { color: var(--hint); font-size: 13px; font-weight: 400; }
.bar-line { display: flex; align-items: center; gap: 10px; margin-top: 6px; padding-left: 50px; }
.bar-track { flex: 1; height: 6px; border-radius: 3px; background: var(--viz-track); overflow: hidden; }
.bar-fill { height: 100%; border-radius: 3px; background: var(--viz-accent); transform-origin: left; }
.bar-percent { width: 36px; text-align: right; font-size: 13px; color: var(--hint); font-variant-numeric: tabular-nums; }

/* Столбцы динамики за 6 месяцев: выбранный месяц — акцентом, остальные — серым контекстом */
.trend { display: flex; gap: 8px; background: var(--card); border-radius: var(--r-lg); padding: 12px 12px 8px; }
.trend-col {
    flex: 1; min-width: 0; padding: 0;
    display: flex; flex-direction: column; align-items: stretch;
    border: none; background: none; cursor: pointer;
}
.trend-value { height: 16px; font-size: 11px; font-weight: 600; text-align: center; white-space: nowrap; }
.trend-area {
    height: 110px; display: flex; align-items: flex-end;
    border-bottom: 1px solid var(--viz-context); /* базовая линия */
}
.trend-bar {
    width: 100%; border-radius: 4px 4px 0 0; background: var(--viz-context);
    transform-origin: bottom;
}
.trend-col.current .trend-bar { background: var(--viz-accent); }
.trend-label { font-size: 12px; color: var(--hint); text-align: center; margin-top: 6px; }
.trend-col.current .trend-label { color: var(--text); font-weight: 600; }

/* Полосы и столбцы "вырастают" — но только когда пришли свежие данные (не во время загрузки) */
.stats-body:not(.loading) .bar-fill { animation: grow-x .6s var(--ease) both; }
.stats-body:not(.loading) .trend-bar { animation: grow-y .6s var(--ease) both; animation-delay: calc(var(--i, 0) * 45ms); }
@keyframes grow-x { from { transform: scaleX(0); } }
@keyframes grow-y { from { transform: scaleY(0); } }
