// ============================================================ // STATE // ============================================================ const STORAGE_KEY = 'gym_tracker_v4'; const App = { state: { workouts: [], exerciseRef: [], // [{id, name, workoutType}] bodyMetrics: [], expandedWorkoutId: null, expandedExerciseId: null, nextId: 1, }, init() { this.load(); this.render(); }, load() { const saved = localStorage.getItem(STORAGE_KEY); if (saved) { try { this.state = JSON.parse(saved); if (!Array.isArray(this.state.workouts)) this.state.workouts = []; if (!this.state.exerciseRef) this.state.exerciseRef = []; if (!this.state.bodyMetrics) this.state.bodyMetrics = []; // Добиваем поля, которых может не быть в старых сохранениях this.state.workouts.forEach(w => { if (!Array.isArray(w.exercises)) w.exercises = []; if (!Array.isArray(w.cardio)) w.cardio = []; if (!Array.isArray(w.setGroups)) w.setGroups = []; }); } catch (e) { console.error('Failed to load state', e); } } }, save() { localStorage.setItem(STORAGE_KEY, JSON.stringify(this.state)); this.updateSyncStatus(); }, genId() { return (this.state.nextId++).toString(); }, // ============================================================ // SYNC // ============================================================ getDirtyWorkouts() { return this.state.workouts.filter(w => !w.synced); }, updateSyncStatus() { const dirty = this.getDirtyWorkouts(); const el = document.getElementById('sync-status'); if (dirty.length === 0) { el.textContent = '● Всё синхронизировано'; el.className = 'sync-status synced'; } else { el.textContent = `● ${dirty.length} не сохран.`; el.className = 'sync-status pending'; } }, async sync() { // Отправляем ВСЕ тренировки, включая уже синхронизированные: // синхронизация возможна в разгар тренировки, и данные после неё меняются const all = this.state.workouts; if (all.length === 0) { alert('Нет данных для синхронизации'); return; } console.log('Syncing:', JSON.stringify(all, null, 2)); all.forEach(w => w.synced = true); this.save(); this.render(); alert(`Отправлено тренировок: ${all.length}`); }, // ============================================================ // WORKOUT CRUD // ============================================================ startWorkout() { const w = { id: this.genId(), startTime: new Date().toISOString(), endTime: null, type: '', exercises: [], cardio: [], setGroups: [], notes: '', synced: false, }; this.state.workouts.unshift(w); this.state.expandedWorkoutId = w.id; this.save(); this.render(); }, finishWorkout(workoutId) { if (!confirm('Завершить тренировку?')) return; const w = this.getWorkout(workoutId); w.endTime = new Date().toISOString(); this.save(); this.render(); }, deleteWorkout(workoutId) { if (!confirm('Удалить тренировку полностью?')) return; this.state.workouts = this.state.workouts.filter(w => w.id !== workoutId); this.save(); this.render(); }, toggleWorkout(workoutId) { this.state.expandedWorkoutId = this.state.expandedWorkoutId === workoutId ? null : workoutId; this.render(); }, getWorkout(id) { return this.state.workouts.find(w => w.id === id); }, getActiveWorkout() { return this.state.workouts.find(w => !w.endTime); }, editWorkoutDate(workoutId) { const w = this.getWorkout(workoutId); if (!w) return; Modal.showEditWorkoutDateDialog(w, (newDates) => { if (!newDates) return; w.startTime = newDates.startTime; w.endTime = newDates.endTime; this.save(); this.render(); }); }, // ============================================================ // EXERCISE CRUD // ============================================================ addExercise(workoutId) { const w = this.getWorkout(workoutId); Modal.showExerciseDialog(w.type, (name) => { if (!name) return; const ex = { id: this.genId(), name: name, sets: [], }; w.exercises.push(ex); this._addToExerciseRef(name, w.type); this.state.expandedExerciseId = ex.id; this.save(); this.render(); }); }, _addToExerciseRef(name, workoutType = '', group = '') { const normalizedName = name.trim().toLowerCase(); const exists = this.state.exerciseRef.find( e => e.name.trim().toLowerCase() === normalizedName ); if (!exists) { this.state.exerciseRef.push({ id: this.genId(), name: name.trim(), workoutType: workoutType, group: group.trim(), }); } else { // Дополняем пустые поля, существующие значения не перетираем if (!exists.workoutType && workoutType) exists.workoutType = workoutType; if (!exists.group && group) exists.group = group.trim(); } }, toggleExercise(exerciseId) { this.state.expandedExerciseId = this.state.expandedExerciseId === exerciseId ? null : exerciseId; this.render(); }, deleteExercise(workoutId, exerciseId) { if (!confirm('Удалить упражнение?')) return; const w = this.getWorkout(workoutId); w.exercises = w.exercises.filter(e => e.id !== exerciseId); // Упражнение удалилось — чистим сеты, где оно состояло w.setGroups = (w.setGroups || []) .map(g => ({ ...g, exerciseIds: g.exerciseIds.filter(id => id !== exerciseId) })) .filter(g => g.exerciseIds.length >= 2); this.save(); this.render(); }, // ============================================================ // СЕТЫ (суперсеты): упражнения, подходы которых идут по очереди // ============================================================ showGroupDialog(workoutId, groupId) { const w = this.getWorkout(workoutId); if (!w) return; if (!Array.isArray(w.setGroups)) w.setGroups = []; const group = groupId ? w.setGroups.find(g => g.id === groupId) : null; if (groupId && !group) return; Modal.showGroupDialog(w, group, (data) => { if (!data) return; if (group) { group.name = data.name; group.exerciseIds = data.exerciseIds; } else { w.setGroups.push({ id: this.genId(), name: data.name, exerciseIds: data.exerciseIds }); } this.save(); this.render(); }); }, removeGroup(workoutId, groupId) { if (!confirm('Разъединить сет? Упражнения останутся в тренировке.')) return; const w = this.getWorkout(workoutId); if (!w) return; w.setGroups = (w.setGroups || []).filter(g => g.id !== groupId); this.save(); this.render(); }, // Имена вариантов того же упражнения: справочная запись с непустой // «группой вариантов» объединяет упражнения в одну статистику _refVariantNames(exerciseName) { const norm = s => (s || '').trim().toLowerCase(); const names = new Set([norm(exerciseName)]); const self = this.state.exerciseRef.find(e => norm(e.name) === norm(exerciseName)); if (self && self.group) { const g = norm(self.group); this.state.exerciseRef.forEach(e => { if (!e.group || norm(e.group) !== g) return; // в рамках одного типа тренировки (пустой тип у одной из записей — не препятствие) if (self.workoutType && e.workoutType && self.workoutType !== e.workoutType) return; names.add(norm(e.name)); }); } return names; }, getExerciseHistory(exerciseName) { const norm = s => (s || '').trim().toLowerCase(); const names = this._refVariantNames(exerciseName); const history = []; for (const w of this.state.workouts) { for (const ex of w.exercises) { if (names.has(norm(ex.name)) && ex.sets.length > 0) { history.push({ date: w.startTime, name: ex.name, sets: ex.sets, }); } } } history.sort((a, b) => new Date(b.date) - new Date(a.date)); return history.slice(0, 5); }, // ============================================================ // SET CRUD // ============================================================ addSet(workoutId, exerciseId) { const w = this.getWorkout(workoutId); const ex = w.exercises.find(e => e.id === exerciseId); const lastSet = ex.sets[ex.sets.length - 1]; const history = this.getExerciseHistory(ex.name); // lastSet передаём как предзаполнение (не как редактирование) Modal.showSetDialog(null, history, (setData) => { if (!setData) return; setData.id = this.genId(); setData.timestamp = new Date().toISOString(); ex.sets.push(setData); this.save(); this.render(); }, { prefill: lastSet, historyLabel: ex.name }); }, editSet(workoutId, exerciseId, setId) { const w = this.getWorkout(workoutId); const ex = w.exercises.find(e => e.id === exerciseId); const set = ex.sets.find(s => s.id === setId); const history = this.getExerciseHistory(ex.name); Modal.showSetDialog(set, history, (setData) => { if (!setData) return; Object.assign(set, setData); this.save(); this.render(); }, { historyLabel: ex.name, onDelete: () => this.deleteSet(workoutId, exerciseId, setId), }); }, deleteSet(workoutId, exerciseId, setId) { if (!confirm('Удалить подход?')) return; const w = this.getWorkout(workoutId); const ex = w.exercises.find(e => e.id === exerciseId); ex.sets = ex.sets.filter(s => s.id !== setId); this.save(); this.render(); }, // ============================================================ // CARDIO CRUD // ============================================================ addCardio(workoutId) { Modal.showCardioDialog(null, (cardio) => { if (!cardio) return; const w = this.getWorkout(workoutId); cardio.id = this.genId(); w.cardio.push(cardio); this.save(); this.render(); }); }, editCardio(workoutId, cardioId) { const w = this.getWorkout(workoutId); const cardio = w.cardio.find(c => c.id === cardioId); Modal.showCardioDialog(cardio, (newData) => { if (!newData) return; Object.assign(cardio, newData); this.save(); this.render(); }); }, deleteCardio(workoutId, cardioId) { if (!confirm('Удалить кардио?')) return; const w = this.getWorkout(workoutId); w.cardio = w.cardio.filter(c => c.id !== cardioId); this.save(); this.render(); }, // ============================================================ // BODY METRICS // ============================================================ showBodyMetrics() { Modal.showBodyMetricsDialog(this.state.bodyMetrics, (newMetric) => { if (!newMetric) return; newMetric.id = this.genId(); this.state.bodyMetrics.unshift(newMetric); // Сортируем по дате (новые сверху) this.state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date)); this.save(); this.render(); alert('Замеры сохранены!'); }); }, editBodyMetric(metricId) { const metric = this.state.bodyMetrics.find(m => m.id === metricId); if (!metric) return; Modal.showBodyMetricsDialog(this.state.bodyMetrics, (updatedData) => { if (!updatedData) return; Object.assign(metric, updatedData); this.state.bodyMetrics.sort((a, b) => new Date(b.date) - new Date(a.date)); this.save(); this._renderBodyMetricsList(); }, metric); // передаём редактируемый замер }, // ============================================================ // SETTINGS // ============================================================ showSettings() { const app = document.getElementById('app'); app.innerHTML = ''; const screen = document.createElement('div'); screen.className = 'settings-screen'; screen.innerHTML = `

⚙️ Настройки

📋 Справочник упражнений

Управляйте списком упражнений и привязывайте их к типам тренировок.

📏 Замеры тела

🗑 Данные

`; app.appendChild(screen); this._renderRefExercises(); this._renderBodyMetricsList(); }, addRefExercise() { const input = document.getElementById('new-ref-exercise'); const typeSelect = document.getElementById('new-ref-type'); const groupInput = document.getElementById('new-ref-group'); const name = input.value.trim(); if (!name) return; this._addToExerciseRef(name, typeSelect.value, groupInput.value.trim()); this.save(); input.value = ''; typeSelect.value = ''; groupInput.value = ''; this._renderRefExercises(); }, deleteRefExercise(id) { if (!confirm('Удалить из справочника? (в тренировках останется)')) return; this.state.exerciseRef = this.state.exerciseRef.filter(e => e.id !== id); this.save(); this._renderRefExercises(); }, updateRefExerciseType(id, newType) { const ex = this.state.exerciseRef.find(e => e.id === id); if (ex) { ex.workoutType = newType; this.save(); } }, updateRefExerciseGroup(id, newGroup) { const ex = this.state.exerciseRef.find(e => e.id === id); if (ex) { ex.group = newGroup.trim(); this.save(); this._renderRefExercises(); // пересортировать: варианты должны стоять вместе } }, editRefExercise(id) { const ex = this.state.exerciseRef.find(e => e.id === id); if (!ex) return; Modal.showEditExerciseDialog(ex, (updatedData) => { if (!updatedData) return; Object.assign(ex, updatedData); this.save(); this._renderRefExercises(); }); }, _renderRefExercises() { const list = document.getElementById('ref-exercises-list'); if (!list) return; if (this.state.exerciseRef.length === 0) { list.innerHTML = '

Справочник пуст

'; return; } const esc = s => Modal.esc(s); const types = ['', 'грудь-руки', 'ноги', 'спина-плечи', 'круговая', 'силовая', 'многоповторная']; const groupNames = [...new Set(this.state.exerciseRef.map(e => e.group).filter(Boolean))].sort(); // Сортировка: тип → группа вариантов → имя (варианты стоят вместе) const sorted = [...this.state.exerciseRef].sort((a, b) => { const t = (a.workoutType || '').localeCompare(b.workoutType || ''); if (t !== 0) return t; const g = (a.group || '').localeCompare(b.group || ''); if (g !== 0) return g; return a.name.localeCompare(b.name); }); let html = `${ groupNames.map(g => ``).join('') }`; let curType = null, curGroup = null; sorted.forEach(ex => { if ((ex.workoutType || '') !== curType) { curType = ex.workoutType || ''; curGroup = null; html += `
${curType ? esc(curType) : 'без типа'}
`; } if ((ex.group || '') !== curGroup) { curGroup = ex.group || ''; html += curGroup ? `
🧩 ${esc(curGroup)}
` : ''; } let count = 0; this.state.workouts.forEach(w => { w.exercises.forEach(e => { if (e.name.trim().toLowerCase() === ex.name.trim().toLowerCase()) { count++; } }); }); html += `
${esc(ex.name)} (${count}×)
`; }); list.innerHTML = html; }, _renderBodyMetricsList() { const list = document.getElementById('body-metrics-list'); if (!list) return; if (this.state.bodyMetrics.length === 0) { list.innerHTML = '

Нет замеров

'; return; } list.innerHTML = this.state.bodyMetrics.map(m => { const date = new Date(m.date); const dateStr = date.toLocaleDateString('ru-RU') + ' ' + date.toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'}); const parts = []; if (m.weight) parts.push(`⚖️ ${m.weight} кг`); if (m.chest) parts.push(`📏 ${m.chest} см`); if (m.waist) parts.push(`📏 ${m.waist} см`); if (m.hips) parts.push(`📏 ${m.hips} см`); if (m.arms) parts.push(`💪 ${m.arms} см`); if (m.legs) parts.push(`🦵 ${m.legs} см`); return `
${dateStr}
${parts.join(' • ') || '—'}
`; }).join(''); }, deleteMetric(id) { if (!confirm('Удалить замер?')) return; this.state.bodyMetrics = this.state.bodyMetrics.filter(m => m.id !== id); this.save(); this._renderBodyMetricsList(); }, clearAllData() { if (!confirm('Удалить ВСЕ данные? Это действие необратимо!')) return; if (!confirm('Точно уверены?')) return; localStorage.removeItem(STORAGE_KEY); location.reload(); }, // ============================================================ // RENDER // ============================================================ render() { const app = document.getElementById('app'); app.innerHTML = ''; if (this.state.workouts.length === 0) { app.innerHTML = `

🏋️ Нет тренировок

Начните первую тренировку

`; return; } const sorted = [...this.state.workouts].sort((a, b) => { if (!a.endTime && b.endTime) return -1; if (a.endTime && !b.endTime) return 1; return new Date(b.startTime) - new Date(a.startTime); }); if (!this.getActiveWorkout()) { const btn = document.createElement('button'); btn.className = 'btn mb-10'; btn.textContent = '▶ Начать новую тренировку'; btn.onclick = () => this.startWorkout(); app.appendChild(btn); } sorted.forEach(w => { app.appendChild(this.renderWorkoutItem(w)); }); this.updateSyncStatus(); }, renderWorkoutItem(w) { const isActive = !w.endTime; const isExpanded = this.state.expandedWorkoutId === w.id; const isReadOnly = w.synced && w.endTime; // синхронизирована и завершена const div = document.createElement('div'); div.className = 'workout-accordion'; const headerClass = `workout-header ${isActive ? 'active' : 'completed'} ${isReadOnly ? 'read-only-overlay' : ''}`; const start = new Date(w.startTime); const dateStr = start.toLocaleDateString('ru-RU') + ' ' + start.toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'}); const typeStr = w.type || 'тип не выбран'; const exCount = w.exercises.length; const cardioCount = w.cardio.length; let statusBadge; if (isReadOnly) { statusBadge = '✓ архив'; } else if (w.synced) { statusBadge = '✓'; } else { statusBadge = '● не сохранено'; } const editDateBtn = !isReadOnly ? ` ✎ ` : ''; div.innerHTML = `
${isActive ? '🔥 Тренировка' : '✅ Завершена'}
${dateStr} ${editDateBtn} • ${typeStr}
Упр: ${exCount} • Кардио: ${cardioCount}
${statusBadge} ›
`; const body = document.createElement('div'); body.className = `workout-body ${isExpanded ? 'expanded' : ''}`; if (isExpanded) { body.appendChild(this.renderWorkoutDetails(w)); } div.appendChild(body); return div; }, renderWorkoutDetails(w) { const wrap = document.createElement('div'); const isActive = !w.endTime; const isReadOnly = w.synced && w.endTime; // Баннер read-only if (isReadOnly) { const banner = document.createElement('div'); banner.className = 'read-only-banner'; banner.textContent = '🔒 Тренировка в архиве — только просмотр'; wrap.appendChild(banner); } // Тип тренировки const typeCard = document.createElement('div'); typeCard.className = 'card'; if (isReadOnly) { typeCard.innerHTML = `
Тип тренировки
${w.type || '—'}
`; } else { typeCard.innerHTML = ` `; } wrap.appendChild(typeCard); // Кнопки добавления (только для активной и не read-only) if (isActive && !isReadOnly) { const addSection = document.createElement('div'); addSection.className = 'add-section'; addSection.innerHTML = ` ${w.exercises.length >= 2 ? `` : ''} `; wrap.appendChild(addSection); } // === Сортировка кардио: warmup/separate сверху, cooldown внизу === const cardioWarmup = w.cardio.filter(c => c.purpose === 'warmup' || c.purpose === 'separate'); const cardioCooldown = w.cardio.filter(c => c.purpose === 'cooldown'); // Разминка/отдельная — перед упражнениями if (cardioWarmup.length > 0) { const title = document.createElement('h4'); title.style.margin = '16px 0 8px'; title.textContent = '🔥 Разминка / Кардио'; wrap.appendChild(title); cardioWarmup.forEach(c => { wrap.appendChild(this.renderCardioItem(w.id, c, isReadOnly)); }); } // Упражнения: обычные + объединённые в сеты (по очереди) const groups = (w.setGroups || []) .map(g => ({ g, members: g.exerciseIds .map(id => w.exercises.find(e => e.id === id)) .filter(Boolean), })) .filter(x => x.members.length >= 2); const seenGroups = new Set(); [...w.exercises].reverse().forEach(ex => { const owner = groups.find(x => x.g.exerciseIds.includes(ex.id)); if (owner) { if (!seenGroups.has(owner.g.id)) { seenGroups.add(owner.g.id); wrap.appendChild(this.renderCircuit(w, owner.g, owner.members, isReadOnly)); } } else { wrap.appendChild(this.renderExercise(w, ex, isReadOnly)); } }); if (!isReadOnly && w.exercises.length >= 2) { const groupBtn = document.createElement('button'); groupBtn.className = 'btn btn-ghost mt-10'; groupBtn.style.width = '100%'; groupBtn.textContent = '🔗 Объединить упражнения в сет'; groupBtn.onclick = () => this.showGroupDialog(w.id); wrap.appendChild(groupBtn); } // Заминка — в самом низу (перед комментарием) if (cardioCooldown.length > 0) { const title = document.createElement('h4'); title.style.margin = '16px 0 8px'; title.textContent = '🧘 Заминка'; wrap.appendChild(title); cardioCooldown.forEach(c => { wrap.appendChild(this.renderCardioItem(w.id, c, isReadOnly)); }); } // Комментарий const notesCard = document.createElement('div'); notesCard.className = 'card mt-10'; if (isReadOnly) { notesCard.innerHTML = `
Комментарий
${w.notes || '—'}
`; } else { notesCard.innerHTML = ` `; notesCard.querySelector('textarea').oninput = (e) => { w.notes = e.target.value; this.save(); }; } wrap.appendChild(notesCard); // Блок завершения / удаления const finishBlock = document.createElement('div'); finishBlock.className = 'finish-block'; if (isReadOnly) { finishBlock.innerHTML = `

🔒 Архив

Тренировка синхронизирована и завершена. Редактирование недоступно.

`; } else if (isActive) { finishBlock.innerHTML = `

Завершение тренировки

После завершения данные останутся локально до синхронизации

`; } else { finishBlock.innerHTML = `

Тренировка завершена

До синхронизации можно редактировать

`; } wrap.appendChild(finishBlock); return wrap; }, // Карточка сета: подходы участников выполняются по очереди (раундами) renderCircuit(w, group, members, isReadOnly) { const card = document.createElement('div'); card.className = 'circuit-card'; const header = document.createElement('div'); header.className = 'circuit-header'; header.innerHTML = `
`; if (!isReadOnly) { const controls = document.createElement('div'); controls.className = 'circuit-controls'; const editBtn = document.createElement('button'); editBtn.className = 'btn btn-small btn-secondary'; editBtn.textContent = '✎ состав'; editBtn.onclick = () => this.showGroupDialog(w.id, group.id); const unlinkBtn = document.createElement('button'); unlinkBtn.className = 'btn btn-small btn-danger'; unlinkBtn.textContent = '✕ разъединить'; unlinkBtn.onclick = () => this.removeGroup(w.id, group.id); controls.appendChild(editBtn); controls.appendChild(unlinkBtn); header.appendChild(controls); } // Текст — через textContent, чтобы кавычки и скобки в названиях ломали разметку header.querySelector('.circuit-name').textContent = '🔗 ' + group.name; header.querySelector('.circuit-members').textContent = members.map(m => m.name).join(' + '); card.appendChild(header); const maxLen = Math.max(0, ...members.map(m => m.sets.length)); const roundsWrap = document.createElement('div'); roundsWrap.className = 'circuit-rounds'; for (let k = 0; k < maxLen; k++) { const row = document.createElement('div'); row.className = 'circuit-round'; const num = document.createElement('span'); num.className = 'round-num'; num.textContent = k + 1; row.appendChild(num); members.forEach(ex => { const set = ex.sets[k]; const chip = document.createElement('span'); if (!set) { chip.className = 'circuit-chip empty'; chip.textContent = ex.name + ': —'; } else { chip.className = 'circuit-chip'; chip.innerHTML = ' '; chip.querySelector('b').textContent = ex.name; chip.querySelector('.circuit-val').textContent = (set.isDropset && set.subSets && set.subSets.length) ? '🔥' + set.subSets.map(s => `${s.weight}×${s.reps}`).join('→') : `${set.weight}×${set.reps}`; chip.querySelector('.circuit-stars').textContent = '★'.repeat(set.rating || 5); if (!isReadOnly) { chip.onclick = () => this.editSet(w.id, ex.id, set.id); } } row.appendChild(chip); }); roundsWrap.appendChild(row); } if (maxLen === 0) { const p = document.createElement('p'); p.className = 'text-muted text-small'; p.style.padding = '10px 12px'; p.textContent = 'Пока нет подходов'; roundsWrap.appendChild(p); } card.appendChild(roundsWrap); if (!isReadOnly) { const footRow = document.createElement('div'); footRow.className = 'circuit-add'; if (!w.endTime) { members.forEach(ex => { const b = document.createElement('button'); b.className = 'btn btn-small btn-secondary'; b.textContent = `+ ${ex.name}`; b.onclick = () => this.addSet(w.id, ex.id); footRow.appendChild(b); }); } const unlinkFoot = document.createElement('button'); unlinkFoot.className = 'btn btn-small btn-ghost'; unlinkFoot.textContent = '⛓️ Разъединить сет'; unlinkFoot.onclick = () => this.removeGroup(w.id, group.id); footRow.appendChild(unlinkFoot); card.appendChild(footRow); } return card; }, renderExercise(w, ex, isReadOnly = false) { const isExpanded = this.state.expandedExerciseId === ex.id; const totalSets = ex.sets.length; const summary = totalSets > 0 ? `${totalSets} подх.` : ''; const card = document.createElement('div'); card.className = 'exercise-card'; card.innerHTML = `
${ex.name} ${summary}
›
`; const body = document.createElement('div'); body.className = `exercise-body ${isExpanded ? 'expanded' : ''}`; if (isExpanded) { if (ex.sets.length > 0) { const table = document.createElement('div'); table.className = 'sets-table'; [...ex.sets].reverse().forEach((set, idx) => { const realIdx = ex.sets.length - 1 - idx; table.appendChild(this.renderSetRow(w.id, ex.id, set, realIdx, isReadOnly)); }); body.appendChild(table); } else { body.innerHTML += `

Пока нет подходов

`; } if (!isReadOnly) { if (!w.endTime) { const addBtn = document.createElement('button'); addBtn.className = 'btn mt-10'; addBtn.textContent = '+ Добавить подход'; addBtn.onclick = () => this.addSet(w.id, ex.id); body.appendChild(addBtn); } const delBtn = document.createElement('button'); delBtn.className = 'btn btn-ghost mt-10'; delBtn.style.width = '100%'; delBtn.textContent = 'Удалить упражнение'; delBtn.onclick = (e) => { e.stopPropagation(); this.deleteExercise(w.id, ex.id); }; body.appendChild(delBtn); } } card.appendChild(body); return card; }, renderSetRow(workoutId, exerciseId, set, index, isReadOnly = false) { const row = document.createElement('div'); const timeStr = set.timestamp ? new Date(set.timestamp).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' }) : ''; const timeHtml = timeStr ? `
${timeStr}
` : ''; const actionsHtml = isReadOnly ? '' : `
`; if (set.isDropset && set.subSets && set.subSets.length > 0) { row.className = 'dropset-group'; const subsText = set.subSets.map(s => `${s.weight}×${s.reps}`).join(' → '); const ratingStars = '★'.repeat(set.rating || 5); row.innerHTML = `
${index + 1}
🔥 ${subsText}
${ratingStars}${timeHtml}
${actionsHtml}
`; } else { row.innerHTML = `
${index + 1}
${set.weight || '—'} кг
${set.reps || '—'}
${'★'.repeat(set.rating || 5)}${timeHtml}
${actionsHtml}
`; } return row; }, renderCardioItem(workoutId, c, isReadOnly = false) { const card = document.createElement('div'); card.className = 'card'; const purposeLabels = { warmup: '🔥 Разминка', cooldown: '🧘 Заминка', separate: '➕ Отдельная' }; const metrics = []; if (c.duration) metrics.push(`${c.duration} мин`); if (c.distance) metrics.push(`${c.distance} км`); if (c.speed) metrics.push(`${c.speed} км/ч`); if (c.incline) metrics.push(`наклон ${c.incline}`); if (c.resistance) metrics.push(`сопр. ${c.resistance}`); const actionsHtml = isReadOnly ? '' : `
`; card.innerHTML = `
${c.type || '—'} ${purposeLabels[c.purpose] || ''}
${metrics.join(' • ') || '—'}
${c.notes ? `
"${c.notes}"
` : ''}
${actionsHtml}
`; return card; }, }; App.init();