import { INGREDIENTS, RECIPES } from '../data/catalog.js?v=2';
import { MEAL_SLOTS } from '../planner/mealSlots.js';
import {
addDays,
addMonths,
sameDay,
sameMonth,
startOfDay,
startOfWeekMonday,
} from '../services/dateUtils.js';
import {
dateKey,
loadPlans,
newPlanEntryId,
savePlans,
} from '../services/planStore.js';
import { dayHasAnyMeal } from '../services/planIngredients.js';
import { showAppToast } from './toast.js';
import {
bindCalendarDayClicks,
createCalendarTopbarHTML,
createCalendarWeekdayHeaderHTML,
formatCalendarMonthYear,
formatCalendarSelectedDate,
isCalendarOnToday,
renderCalendarGrid,
syncCalendarTodayButton,
} from './mealCalendar.js?v=1';
function esc(s) {
return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
}
const slotLabel = Object.fromEntries(MEAL_SLOTS.map((s) => [s.id, s.label]));
/* ── HTML template ──────────────────────────────────── */
export function getMealPlanEditorHTML() {
return `
${createCalendarTopbarHTML({
titleId: 'mpe-cal-title',
prevId: 'mpe-cal-prev',
todayId: 'mpe-cal-today',
nextId: 'mpe-cal-next',
wrapperClass: 'mb-2 flex items-center gap-3',
})}
${createCalendarWeekdayHeaderHTML()}
Pora posiłku
`;
}
/* ── Setup ──────────────────────────────────────────── */
export function setupMealPlanEditor() {
const overlay = document.getElementById('mpe-overlay');
const sheet = document.getElementById('mpe-sheet');
if (!overlay || !sheet) return;
const S = {
mode: null,
recipeId: null,
date: null,
slotId: null,
originalDate: null,
originalSlotId: null,
servings: 1,
subs: {},
excluded: new Set(),
overrides: {},
added: [],
entryId: null,
showCal: false,
calDate: null,
calExpanded: false,
altOpen: new Set(),
addOpen: false,
addQuery: '',
};
/* ── helpers ───────────────────────────────────── */
function nutFor(ingredientId, amount, unit) {
const def = INGREDIENTS[ingredientId];
if (!def?.nutritionPer100g) return null;
let g = amount;
if ((unit === 'szt.' || unit === 'szt') && def.weightPerPiece) g = amount * def.weightPerPiece;
const f = g / 100;
return {
kcal: Math.round(def.nutritionPer100g.kcal * f),
protein: Math.round(def.nutritionPer100g.protein * f * 10) / 10,
fat: Math.round(def.nutritionPer100g.fat * f * 10) / 10,
carbs: Math.round(def.nutritionPer100g.carbs * f * 10) / 10,
};
}
function totalNutrition() {
const r = RECIPES[S.recipeId];
if (!r) return { kcal: 0, protein: 0, fat: 0, carbs: 0 };
let kcal = 0, protein = 0, fat = 0, carbs = 0;
for (const ing of r.ingredients) {
if (S.excluded.has(ing.ingredientId)) continue;
const eid = S.subs[ing.ingredientId] || ing.ingredientId;
const base = S.overrides[ing.ingredientId] ?? ing.amount;
const n = nutFor(eid, base * S.servings, ing.unit);
if (n) { kcal += n.kcal; protein += n.protein; fat += n.fat; carbs += n.carbs; }
}
for (const a of S.added) {
const n = nutFor(a.ingredientId, a.amount * S.servings, a.unit);
if (n) { kcal += n.kcal; protein += n.protein; fat += n.fat; carbs += n.carbs; }
}
return { kcal: Math.round(kcal), protein: Math.round(protein * 10) / 10, fat: Math.round(fat * 10) / 10, carbs: Math.round(carbs * 10) / 10 };
}
function fmtAmt(n) { return Number.isInteger(n) ? String(n) : String(parseFloat(n.toFixed(1))); }
/* ── Calendar ──────────────────────────────────── */
function renderCal() {
const wrap = document.getElementById('mpe-cal-wrap');
const sec = document.getElementById('mpe-cal-section');
const summary = document.getElementById('mpe-summary-wrap');
if (!sec || !wrap) return;
if (summary) summary.style.paddingTop = S.showCal ? '0' : '0.75rem';
if (!S.showCal) {
wrap.classList.add('hidden');
sec.classList.add('hidden');
syncScrollShadows();
return;
}
wrap.classList.remove('hidden');
sec.classList.remove('hidden');
const grid = document.getElementById('mpe-cal-grid');
const title = document.getElementById('mpe-cal-title');
const todayBtn = document.getElementById('mpe-cal-today');
const icon = document.getElementById('mpe-cal-toggle-icon');
if (!grid || !title) return;
const today = startOfDay(new Date());
const plans = loadPlans();
const mode = S.calExpanded ? 'month' : 'week';
title.textContent = S.calExpanded ? formatCalendarMonthYear(S.calDate) : formatCalendarSelectedDate(S.date);
if (icon) {
icon.className = S.calExpanded ? 'fas fa-chevron-up text-[10px]' : 'fas fa-chevron-down text-[10px]';
}
syncCalendarTodayButton(
todayBtn,
isCalendarOnToday(mode, startOfWeekMonday(S.calDate), S.calDate, S.date),
);
renderCalendarGrid({
gridEl: grid,
mode,
anchorDate: S.calDate,
selectedDate: S.date,
resolveDayState: (day, meta) => {
const isSelected = S.date && sameDay(day, S.date);
const isPast = day.getTime() < today.getTime();
return {
disabled: isPast && !isSelected,
dimmed: (isPast || (meta.mode === 'month' && !meta.inCurrentMonth)) && !isSelected,
showIndicator: meta.mode === 'month'
? meta.inCurrentMonth && dayHasAnyMeal(plans, day)
: dayHasAnyMeal(plans, day),
};
},
});
syncScrollShadows();
}
function renderSlots() {
const el = document.getElementById('mpe-slot-chips');
if (!el || !S.showCal) return;
const r = RECIPES[S.recipeId];
if (!r) return;
el.innerHTML = MEAL_SLOTS.filter((s) => r.allowedSlots.includes(s.id)).map((s) => {
const sel = s.id === S.slotId;
const bg = sel ? '#23221e' : '#2f2f2d';
const border = sel ? '#787876' : '#444442';
const text = sel ? '#f2efe8' : '#d7d2c8';
return ``;
}).join('');
}
function syncScrollShadows() {
const body = document.getElementById('mpe-ing-scroll');
const topShadow = document.getElementById('mpe-top-shadow');
const bottomShadow = document.getElementById('mpe-footer-shadow');
if (!body) {
if (topShadow) topShadow.style.opacity = '0';
if (bottomShadow) bottomShadow.style.opacity = '0';
return;
}
if (topShadow) topShadow.style.opacity = body.scrollTop > 6 ? '1' : '0';
if (bottomShadow) {
const remaining = body.scrollHeight - body.clientHeight - body.scrollTop;
bottomShadow.style.opacity = remaining > 6 ? '1' : '0';
}
}
/* ── Servings ──────────────────────────────────── */
function renderServings() {
const el = document.getElementById('mpe-servings-row');
if (!el) return;
el.innerHTML = `
`;
}
/* ── Ingredients list ──────────────────────────── */
function renderIngList() {
const list = document.getElementById('mpe-ing-list');
if (!list) return;
const r = RECIPES[S.recipeId];
if (!r) return;
let html = '';
const removeBtn = (cls, attrs) =>
``;
for (const ing of r.ingredients) {
const id = ing.ingredientId;
if (S.excluded.has(id)) continue;
const eid = S.subs[id] || id;
const eDef = INGREDIENTS[eid];
const eName = eDef?.name || eid;
const hasAlts = ing.alternatives?.length > 0;
const swapped = eid !== id;
const altOpen = S.altOpen.has(id);
const base = S.overrides[id] ?? ing.amount;
const disp = base * S.servings;
const modified = id in S.overrides;
const rowStyle = 'background:#393937 !important; background-image:none !important; box-shadow:none !important; border:none !important;';
const shuffleBtn = hasAlts
? ``
: '';
const modDot = modified ? '' : '';
html += ``;
html += `
`;
html += `
${esc(eName)}
`;
html += `
`;
html += shuffleBtn;
html += ``;
html += removeBtn('mpe-remove-ing', `data-orig-id="${esc(id)}" data-type="recipe"`);
html += `
`;
html += `
`;
if (hasAlts && altOpen) {
const opts = [id, ...ing.alternatives];
html += '
';
for (const altId of opts) {
const def = INGREDIENTS[altId];
const name = def?.name || altId;
const isSel = eid === altId;
const checkbox = `
${isSel ? '' : ''}
`;
const n = nutFor(altId, disp, ing.unit);
const nLine = n ? `
${n.kcal} kcal · ${n.protein}g B · ${n.fat}g T · ${n.carbs}g W
` : '';
html += `
`;
}
html += '
';
}
html += '
';
}
for (const a of S.added) {
const def = INGREDIENTS[a.ingredientId];
const name = def?.name || a.ingredientId;
const disp = a.amount * S.servings;
html += ``;
html += `
`;
html += `
${esc(name)}
`;
html += `
`;
html += removeBtn('mpe-remove-ing', `data-ing-id="${esc(a.ingredientId)}" data-type="added"`);
html += `
`;
}
if (S.excluded.size > 0) {
const cnt = S.excluded.size;
const label = cnt === 1 ? '1 składnik usunięty' : cnt < 5 ? `${cnt} składniki usunięte` : `${cnt} składników usuniętych`;
html += ``;
html += `${label}`;
html += ``;
html += `
`;
}
list.innerHTML = html;
}
function renderAddArea() {
const el = document.getElementById('mpe-add-area');
if (!el) return;
if (!S.addOpen) {
el.innerHTML = ``;
return;
}
const recipe = RECIPES[S.recipeId];
const usedIds = new Set([
...(recipe?.ingredients.map((i) => i.ingredientId) || []),
...S.added.map((a) => a.ingredientId),
]);
const q = S.addQuery.toLowerCase().trim();
const avail = Object.values(INGREDIENTS).filter((i) => !usedIds.has(i.id) && (!q || i.name.toLowerCase().includes(q)));
el.innerHTML = `
`;
}
function updateAddResults() {
const results = document.getElementById('mpe-add-results');
if (!results) return;
const recipe = RECIPES[S.recipeId];
const usedIds = new Set([
...(recipe?.ingredients.map((i) => i.ingredientId) || []),
...S.added.map((a) => a.ingredientId),
]);
const q = S.addQuery.toLowerCase().trim();
const avail = Object.values(INGREDIENTS).filter((i) => !usedIds.has(i.id) && (!q || i.name.toLowerCase().includes(q)));
results.innerHTML = avail.length === 0
? 'Brak wyników
'
: avail.slice(0, 20).map((i) => ``).join('');
}
function renderIngredients() {
renderIngList();
renderAddArea();
requestAnimationFrame(syncScrollShadows);
}
/* ── Nutrition summary ─────────────────────────── */
function renderNutrition() {
const el = document.getElementById('mpe-nutrition-section');
if (!el) return;
const n = totalNutrition();
el.innerHTML = `
Wartości odżywcze
${n.kcal}kcal
${n.protein}gBiałko
${n.carbs}gWęgle
${n.fat}gTłuszcze
`;
requestAnimationFrame(syncScrollShadows);
}
/* ── Render all ────────────────────────────────── */
function renderAll() { renderCal(); renderSlots(); renderServings(); renderIngredients(); renderNutrition(); }
/* ── Open / Close ─────────────────────────────── */
function openEditor(opts) {
const recipe = RECIPES[opts.recipeId];
if (!recipe) return;
S.mode = opts.mode || 'add';
S.recipeId = opts.recipeId;
S.originalDate = opts.date ? startOfDay(new Date(opts.date)) : null;
S.originalSlotId = opts.slotId || null;
S.servings = opts.servings || opts.entry?.servings || 1;
S.subs = { ...(opts.substitutions || opts.entry?.substitutions || {}) };
S.excluded = new Set(opts.entry?.excludedIngredients || []);
S.overrides = { ...(opts.entry?.amountOverrides || {}) };
S.added = (opts.entry?.addedIngredients || []).map((a) => ({ ...a }));
S.entryId = opts.entry?.id || null;
S.altOpen = new Set();
S.addOpen = false;
S.addQuery = '';
if (opts.date && opts.slotId) {
S.date = startOfDay(new Date(opts.date));
S.calDate = new Date(S.date);
S.calExpanded = false;
S.slotId = opts.slotId;
S.showCal = S.mode === 'edit';
} else {
const today = startOfDay(new Date());
S.date = today;
S.calDate = today;
S.calExpanded = false;
S.slotId = recipe.allowedSlots[0] || MEAL_SLOTS[0]?.id;
S.showCal = true;
}
document.getElementById('mpe-title').textContent = S.mode === 'edit' ? 'Edytuj posiłek' : 'Zaplanuj posiłek';
document.getElementById('mpe-subtitle').textContent = recipe.title;
document.getElementById('mpe-confirm-label').textContent = S.mode === 'edit' ? 'Zapisz zmiany' : 'Dodaj do planu';
renderAll();
const body = document.getElementById('mpe-ing-scroll');
if (body) body.scrollTop = 0;
syncScrollShadows();
overlay.classList.remove('hidden');
overlay.style.pointerEvents = 'auto';
requestAnimationFrame(() => { sheet.style.transform = 'translateY(0)'; });
}
function closeEditor() {
sheet.style.transform = 'translateY(100%)';
setTimeout(() => { overlay.classList.add('hidden'); overlay.style.pointerEvents = 'none'; }, 300);
}
/* ── Save ──────────────────────────────────────── */
function buildEntry() {
const entry = { id: S.entryId || newPlanEntryId(), recipeId: S.recipeId, servings: S.servings };
if (Object.keys(S.subs).length > 0) entry.substitutions = { ...S.subs };
if (S.excluded.size > 0) entry.excludedIngredients = [...S.excluded];
const recipe = RECIPES[S.recipeId];
if (recipe) {
const ov = {};
for (const [k, v] of Object.entries(S.overrides)) {
const orig = recipe.ingredients.find((i) => i.ingredientId === k);
if (orig && Math.abs(v - orig.amount) > 0.01) ov[k] = v;
}
if (Object.keys(ov).length > 0) entry.amountOverrides = ov;
}
if (S.added.length > 0) entry.addedIngredients = S.added.map((a) => ({ ingredientId: a.ingredientId, amount: a.amount, unit: a.unit }));
return entry;
}
function handleConfirm() {
if (!S.recipeId || !S.date || !S.slotId) return;
const plans = loadPlans();
const targetKey = dateKey(S.date);
const nextEntry = buildEntry();
if (S.mode === 'edit' && S.entryId) {
const sourceDate = S.originalDate || S.date;
const sourceSlotId = S.originalSlotId || S.slotId;
const sourceKey = dateKey(sourceDate);
const sameTarget = sourceKey === targetKey && sourceSlotId === S.slotId;
if (sameTarget) {
if (!plans[targetKey]) plans[targetKey] = {};
if (!plans[targetKey][S.slotId]) plans[targetKey][S.slotId] = [];
const arr = plans[targetKey][S.slotId];
const idx = arr.findIndex((e) => e.id === S.entryId);
if (idx >= 0) arr[idx] = nextEntry;
else arr.push(nextEntry);
} else {
const sourceArr = plans[sourceKey]?.[sourceSlotId];
if (Array.isArray(sourceArr)) {
const idx = sourceArr.findIndex((e) => e.id === S.entryId);
if (idx >= 0) sourceArr.splice(idx, 1);
if (sourceArr.length === 0 && plans[sourceKey]) delete plans[sourceKey][sourceSlotId];
if (plans[sourceKey] && Object.keys(plans[sourceKey]).length === 0) delete plans[sourceKey];
}
if (!plans[targetKey]) plans[targetKey] = {};
if (!plans[targetKey][S.slotId]) plans[targetKey][S.slotId] = [];
plans[targetKey][S.slotId].push(nextEntry);
}
} else {
if (!plans[targetKey]) plans[targetKey] = {};
if (!plans[targetKey][S.slotId]) plans[targetKey][S.slotId] = [];
plans[targetKey][S.slotId].push(nextEntry);
}
savePlans(plans);
closeEditor();
showAppToast(S.mode === 'edit' ? 'Zapisano zmiany!' : 'Dodano do planera!');
window.refreshPlanner?.();
}
/* ── Event bindings ───────────────────────────── */
document.getElementById('mpe-close-btn')?.addEventListener('click', closeEditor);
overlay?.addEventListener('click', (e) => { if (e.target === overlay) closeEditor(); });
document.getElementById('mpe-confirm-btn')?.addEventListener('click', handleConfirm);
bindCalendarDayClicks(document.getElementById('mpe-cal-grid'), (date) => {
S.date = date;
S.calDate = new Date(date);
renderCal();
});
document.getElementById('mpe-cal-prev')?.addEventListener('click', () => {
if (!S.showCal) return;
S.calDate = S.calExpanded ? addMonths(S.calDate, -1) : addDays(S.calDate, -7);
renderCal();
});
document.getElementById('mpe-cal-next')?.addEventListener('click', () => {
if (!S.showCal) return;
S.calDate = S.calExpanded ? addMonths(S.calDate, 1) : addDays(S.calDate, 7);
renderCal();
});
document.getElementById('mpe-cal-today')?.addEventListener('click', () => {
const today = startOfDay(new Date());
S.date = today; S.calDate = today;
renderCal();
});
document.getElementById('mpe-cal-toggle')?.addEventListener('click', () => {
S.calExpanded = !S.calExpanded;
renderCal();
});
document.getElementById('mpe-slot-chips')?.addEventListener('click', (e) => {
const btn = e.target.closest('.mpe-slot-btn');
if (!btn) return;
S.slotId = btn.dataset.slotId;
renderSlots();
});
document.getElementById('mpe-ing-scroll')?.addEventListener('scroll', syncScrollShadows);
document.getElementById('mpe-servings-row')?.addEventListener('click', (e) => {
if (e.target.closest('#mpe-serv-minus')) { if (S.servings <= 1) return; S.servings--; }
else if (e.target.closest('#mpe-serv-plus')) { if (S.servings >= 12) return; S.servings++; }
else return;
renderServings();
renderIngredients();
renderNutrition();
});
/* ── Ingredient section delegation ────────────── */
const ingSec = document.getElementById('mpe-ing-section');
ingSec?.addEventListener('click', (e) => {
const remove = e.target.closest('.mpe-remove-ing');
if (remove) {
if (remove.dataset.type === 'added') {
S.added = S.added.filter((a) => a.ingredientId !== remove.dataset.ingId);
} else {
S.excluded.add(remove.dataset.origId);
}
renderIngredients(); renderNutrition();
return;
}
if (e.target.closest('#mpe-restore-all')) {
S.excluded.clear();
renderIngredients(); renderNutrition();
return;
}
const shuffle = e.target.closest('.mpe-shuffle');
if (shuffle) {
const id = shuffle.dataset.origId;
if (S.altOpen.has(id)) S.altOpen.delete(id); else S.altOpen.add(id);
renderIngList();
return;
}
const altPick = e.target.closest('.mpe-alt-pick');
if (altPick) {
const origId = altPick.dataset.origId;
const altId = altPick.dataset.altId;
if (altId === origId) delete S.subs[origId]; else S.subs[origId] = altId;
S.altOpen.delete(origId);
renderIngList(); renderNutrition();
return;
}
const editAmt = e.target.closest('.mpe-edit-amt');
if (editAmt && !editAmt.disabled) {
startAmountEdit(editAmt);
return;
}
if (e.target.closest('#mpe-add-btn')) {
S.addOpen = true; S.addQuery = '';
renderAddArea();
document.getElementById('mpe-add-search')?.focus();
return;
}
if (e.target.closest('#mpe-add-cancel')) {
S.addOpen = false;
renderAddArea();
return;
}
const addPick = e.target.closest('.mpe-add-pick');
if (addPick) {
const ingId = addPick.dataset.ingId;
const def = INGREDIENTS[ingId];
if (!def) return;
const unit = def.pantryUnit === 'szt' ? 'szt.' : def.pantryUnit;
const amt = def.pantryUnit === 'szt' ? 1 : 100;
S.added.push({ ingredientId: ingId, amount: amt, unit });
S.addOpen = false;
renderIngredients(); renderNutrition();
}
});
ingSec?.addEventListener('input', (e) => {
if (e.target.id === 'mpe-add-search') {
S.addQuery = e.target.value;
updateAddResults();
}
});
/* ── Inline amount editing ────────────────────── */
function startAmountEdit(btn) {
const type = btn.dataset.type;
const id = btn.dataset.origId || btn.dataset.ingId;
const amtSpan = btn.querySelector('.tabular-nums');
if (!amtSpan) return;
const currentDisplay = parseFloat(amtSpan.textContent);
const spans = btn.querySelectorAll('span');
const unitText = spans.length > 0 ? spans[spans.length - 1].textContent.trim() : '';
const saved = btn.innerHTML;
btn.innerHTML = `${esc(unitText)}`;
const input = btn.querySelector('.mpe-amt-input');
if (!input) { btn.innerHTML = saved; return; }
input.focus();
input.select();
let done = false;
const finish = (save) => {
if (done) return;
done = true;
if (save) {
const raw = Math.max(0, parseFloat(input.value) || 0);
const newBase = S.servings > 0 ? raw / S.servings : raw;
const rounded = Math.round(newBase * 100) / 100;
if (type === 'recipe') {
const recipe = RECIPES[S.recipeId];
const orig = recipe?.ingredients.find((i) => i.ingredientId === id);
if (orig && Math.abs(rounded - orig.amount) > 0.01) S.overrides[id] = rounded;
else delete S.overrides[id];
} else if (type === 'added') {
const a = S.added.find((x) => x.ingredientId === id);
if (a) a.amount = rounded;
}
}
renderIngList();
renderNutrition();
};
input.addEventListener('blur', () => finish(true));
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
if (e.key === 'Escape') { e.preventDefault(); finish(false); }
});
}
/* ── Expose globally ──────────────────────────── */
window.openMealPlanEditor = openEditor;
window.closeMealPlanEditor = closeEditor;
}