import { INGREDIENTS, RECIPES, PRODUCTS, CATEGORY_LABELS, getProductsForIngredient } from '../data/catalog.js?v=8';
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?v=2';
import { dayHasAnyMeal, autoSelectProducts, saveLastProductSelection } from '../services/planIngredients.js?v=4';
import { loadPantry, getPantryTotal, getPantryProducts, setPantryQty, setPantryProductQty, addOrMergeShoppingLines } from '../services/pantryShopping.js?v=2';
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

const slotLabel = Object.fromEntries(MEAL_SLOTS.map((s) => [s.id, s.label]));

/* ── Product Card Popup ────────────────────────────── */

function getProductCardHTML() {
    return `
    <div id="mpe-product-card-overlay" class="fixed inset-0 z-[70] bg-black/50 hidden flex items-center justify-center p-6" style="pointer-events:none">
        <div id="mpe-product-card" class="relative w-full max-w-xs bg-[#2d2e2b] rounded-2xl shadow-2xl overflow-hidden" style="pointer-events:auto; max-height:80vh; overflow-y:auto;">
            <div id="mpe-pc-hero" class="relative w-full h-[180px] bg-gray-800 overflow-hidden">
                <img id="mpe-pc-img" class="w-full h-full object-cover hidden" alt="" />
                <div id="mpe-pc-fallback" class="w-full h-full flex items-center justify-center">
                    <i class="fas fa-box-open text-3xl text-gray-600"></i>
                </div>
                <button type="button" id="mpe-pc-close" class="absolute top-3 right-3 w-8 h-8 rounded-full bg-black/50 text-white flex items-center justify-center hover:bg-black/70 transition-colors">
                    <i class="fas fa-times text-sm"></i>
                </button>
            </div>
            <div class="px-4 pt-3 pb-4 space-y-3">
                <div>
                    <p id="mpe-pc-brand" class="text-[10px] font-semibold uppercase tracking-wider text-emerald-400"></p>
                    <h3 id="mpe-pc-name" class="text-[15px] font-bold text-gray-100 leading-snug mt-0.5"></h3>
                    <p id="mpe-pc-category" class="text-[11px] text-gray-500 mt-0.5"></p>
                </div>
                <div id="mpe-pc-pack" class="hidden">
                    <span class="text-[10px] font-semibold uppercase tracking-wider text-gray-500">Opakowanie</span>
                    <p id="mpe-pc-pack-val" class="text-[13px] font-semibold text-gray-300 mt-0.5"></p>
                </div>
                <div>
                    <span id="mpe-pc-nut-label" class="text-[10px] font-semibold uppercase tracking-wider text-gray-500">Wartości odżywcze na 100 g</span>
                    <div class="grid grid-cols-4 gap-2 mt-1.5">
                        <div class="bg-[#393937] rounded-xl px-2.5 py-2 text-center">
                            <p id="mpe-pc-kcal" class="text-[15px] font-bold text-gray-100 tabular-nums"></p>
                            <p class="text-[9px] text-gray-500 font-medium mt-0.5">kcal</p>
                        </div>
                        <div class="bg-[#393937] rounded-xl px-2.5 py-2 text-center">
                            <p id="mpe-pc-protein" class="text-[15px] font-bold text-blue-400 tabular-nums"></p>
                            <p class="text-[9px] text-gray-500 font-medium mt-0.5">białko</p>
                        </div>
                        <div class="bg-[#393937] rounded-xl px-2.5 py-2 text-center">
                            <p id="mpe-pc-fat" class="text-[15px] font-bold text-amber-400 tabular-nums"></p>
                            <p class="text-[9px] text-gray-500 font-medium mt-0.5">tłuszcz</p>
                        </div>
                        <div class="bg-[#393937] rounded-xl px-2.5 py-2 text-center">
                            <p id="mpe-pc-carbs" class="text-[15px] font-bold text-orange-400 tabular-nums"></p>
                            <p class="text-[9px] text-gray-500 font-medium mt-0.5">węgl.</p>
                        </div>
                    </div>
                </div>
                <div id="mpe-pc-stock" class="space-y-1.5"></div>
                <div id="mpe-pc-shop"></div>
            </div>
        </div>
    </div>`;
}

function openProductCard(ingredientId, productId) {
    const overlay = document.getElementById('mpe-product-card-overlay');
    if (!overlay) return;

    const def = INGREDIENTS[ingredientId];
    const product = productId ? PRODUCTS[productId] : null;
    const name = product?.name || def?.name || ingredientId;
    const brand = product?.brand || '';
    const category = CATEGORY_LABELS[def?.category] || '';
    const nutrition = product?.nutritionPer100g || def?.nutritionPer100g;
    const image = product?.image || def?.image;
    const packLabel = product?.packLabel || def?.purchasePack?.label || '';
    const nutUnit = def?.pantryUnit === 'ml' ? '100 ml' : '100 g';

    document.getElementById('mpe-pc-name').textContent = name;
    document.getElementById('mpe-pc-brand').textContent = brand;
    document.getElementById('mpe-pc-category').textContent = category;
    document.getElementById('mpe-pc-nut-label').textContent = `Wartości odżywcze na ${nutUnit}`;

    const img = document.getElementById('mpe-pc-img');
    const fallback = document.getElementById('mpe-pc-fallback');
    if (image) {
        img.src = image;
        img.alt = name;
        img.classList.remove('hidden');
        fallback.classList.add('hidden');
    } else {
        img.classList.add('hidden');
        fallback.classList.remove('hidden');
    }

    const packWrap = document.getElementById('mpe-pc-pack');
    if (packLabel) {
        packWrap.classList.remove('hidden');
        document.getElementById('mpe-pc-pack-val').textContent = packLabel;
    } else {
        packWrap.classList.add('hidden');
    }

    if (nutrition) {
        document.getElementById('mpe-pc-kcal').textContent = nutrition.kcal;
        document.getElementById('mpe-pc-protein').textContent = nutrition.protein + 'g';
        document.getElementById('mpe-pc-fat').textContent = nutrition.fat + 'g';
        document.getElementById('mpe-pc-carbs').textContent = nutrition.carbs + 'g';
    }

    // Stock section
    renderPlannerCardStock(ingredientId, productId);

    // Shop section
    renderPlannerCardShop(ingredientId, productId);

    overlay.classList.remove('hidden');
    overlay.style.pointerEvents = 'auto';
}

function renderPlannerCardStock(ingredientId, productId) {
    const wrap = document.getElementById('mpe-pc-stock');
    if (!wrap) return;
    const def = INGREDIENTS[ingredientId];
    if (!def) return;
    const u = def.pantryUnit === 'szt' ? 'szt.' : def.pantryUnit;
    const pantry = loadPantry();
    const product = productId ? PRODUCTS[productId] : null;

    let qty, step, pid;
    if (product) {
        const items = getPantryProducts(ingredientId, pantry);
        qty = items.find(i => i.productId === productId)?.qty || 0;
        step = product.packSize || 1;
        pid = productId;
    } else {
        qty = getPantryTotal(ingredientId, pantry);
        step = def.purchasePack?.amount || (def.pantryUnit === 'szt' ? 1 : 10);
        pid = '_generic';
    }

    wrap.innerHTML = `
        <p class="text-[9px] font-semibold uppercase tracking-wide mb-1.5 text-gray-500">Zapas</p>
        <div class="flex items-center justify-center gap-3 rounded-xl px-3 py-2 bg-[#393937]">
            <button type="button" class="mpe-pc-stock-btn w-9 h-9 rounded-xl flex items-center justify-center active:scale-95 bg-[#2f2f2d] text-[#d7d2c8]" data-pid="${esc(pid)}" data-step="${step}" data-dir="-1"><i class="fas fa-minus text-xs"></i></button>
            <span class="text-[17px] font-bold tabular-nums" style="color:#6ee7b7;">${Math.round(qty)} ${esc(u)}</span>
            <button type="button" class="mpe-pc-stock-btn w-9 h-9 rounded-xl flex items-center justify-center active:scale-95 bg-[#2f2f2d] text-[#d7d2c8]" data-pid="${esc(pid)}" data-step="${step}" data-dir="1"><i class="fas fa-plus text-xs"></i></button>
        </div>`;

    wrap.querySelectorAll('.mpe-pc-stock-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const bpid = btn.dataset.pid;
            const bstep = Number(btn.dataset.step) || 1;
            const dir = Number(btn.dataset.dir);
            const p = loadPantry();
            if (bpid === '_generic') {
                const cur = getPantryTotal(ingredientId, p);
                setPantryQty(ingredientId, Math.max(0, cur + bstep * dir));
            } else {
                const items = getPantryProducts(ingredientId, p);
                const cur = items.find(i => i.productId === bpid)?.qty || 0;
                setPantryProductQty(ingredientId, bpid, Math.max(0, cur + bstep * dir));
            }
            renderPlannerCardStock(ingredientId, productId);
        });
    });
}

function renderPlannerCardShop(ingredientId, productId) {
    const wrap = document.getElementById('mpe-pc-shop');
    if (!wrap) return;
    const def = INGREDIENTS[ingredientId];
    if (!def) return;
    const u = def.pantryUnit === 'szt' ? 'szt.' : def.pantryUnit;
    const product = productId ? PRODUCTS[productId] : null;
    const packSize = product?.packSize || def.purchasePack?.amount;
    const packLabel = product?.packLabel || def.purchasePack?.label;
    const usesPacks = Boolean(packSize && packSize > 0);
    const btnLabel = usesPacks ? `Dodaj na listę (${packLabel || `${packSize} ${u}`})` : 'Dodaj na listę';

    wrap.innerHTML = `
        <button type="button" id="mpe-pc-add-list" class="w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-[13px] font-semibold transition-colors active:scale-[0.98]" style="background:#ddd6ca; color:#2d2e2b;">
            <i class="fas fa-cart-plus text-[11px]"></i>${esc(btnLabel)}
        </button>`;

    document.getElementById('mpe-pc-add-list')?.addEventListener('click', () => {
        const amt = usesPacks ? packSize : (def.pantryUnit === 'szt' ? 1 : 10);
        const line = {
            ingredientId,
            amount: amt,
            unit: u,
            name: product?.name || def.name,
            category: def.category,
            sourceNote: packLabel || 'Z planera',
        };
        if (productId) line.productId = productId;
        addOrMergeShoppingLines([line]);
        // Quick visual feedback
        const btn = document.getElementById('mpe-pc-add-list');
        if (btn) { btn.textContent = '✓ Dodano'; setTimeout(() => { btn.innerHTML = `<i class="fas fa-cart-plus text-[11px]"></i>${esc(btnLabel)}`; }, 1200); }
        window.refreshShopping?.();
    });
}

function closeProductCard() {
    const overlay = document.getElementById('mpe-product-card-overlay');
    if (overlay) {
        overlay.classList.add('hidden');
        overlay.style.pointerEvents = 'none';
    }
}

/* ── HTML template ──────────────────────────────────── */

export function getMealPlanEditorHTML() {
    return `
    <div id="mpe-overlay" class="absolute inset-0 z-[55] bg-black/45 hidden flex items-end" style="pointer-events:none">
        <div id="mpe-sheet" class="w-full bg-[#2d2e2b] rounded-t-3xl shadow-lg flex flex-col overflow-hidden" style="pointer-events:auto; background:#2d2e2b !important; background-image:none !important; backdrop-filter:none !important; height:100dvh; max-height:100dvh; transform:translateY(100%); transition:transform 300ms cubic-bezier(0.32,0.72,0,1)">
            <div class="shrink-0 px-5 pt-3 pb-2.5 border-b border-gray-100 bg-[#2d2e2b]" style="background:#2d2e2b !important; background-image:none !important;">
                <div class="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-3"></div>
                <div class="flex items-center justify-between">
                    <div class="min-w-0 flex-1">
                        <h2 id="mpe-title" class="text-[15px] font-bold text-gray-900 leading-tight"></h2>
                        <p id="mpe-subtitle" class="text-[11px] text-gray-500 mt-0.5 truncate"></p>
                    </div>
                </div>
            </div>
            <div id="mpe-cal-wrap" class="hidden relative z-[1] shrink-0 px-5 pt-3 pb-3 bg-[#2d2e2b]" style="background:#2d2e2b !important; background-image:none !important;">
                <div id="mpe-cal-section" class="hidden">
                    ${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()}
                    <div id="mpe-cal-grid" class="grid grid-cols-7 gap-1.5"></div>
                    <button id="mpe-cal-toggle" type="button" class="w-full flex items-center justify-center py-1 mt-1 text-gray-400 hover:text-gray-600 transition-colors"><i id="mpe-cal-toggle-icon" class="fas fa-chevron-down text-[10px]"></i></button>
                    <p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mt-3 mb-2">Pora posiłku</p>
                    <div id="mpe-slot-chips" class="flex flex-wrap gap-1.5"></div>
                </div>
            </div>
            <div id="mpe-summary-wrap" class="relative z-[1] shrink-0 px-5 pb-3 bg-[#2d2e2b]" style="background:#2d2e2b !important; background-image:none !important;">
                <div id="mpe-nutrition-section"></div>
                <div id="mpe-servings-row" class="mt-3"></div>
                <div id="mpe-top-shadow" class="pointer-events-none absolute inset-x-0 -bottom-3 h-3 opacity-0 transition-opacity duration-200" style="background:linear-gradient(to bottom, rgba(0,0,0,0.12), rgba(0,0,0,0.03), rgba(0,0,0,0));"></div>
            </div>
            <div id="mpe-ing-scroll" class="flex-1 min-h-0 overflow-y-auto no-scrollbar px-5 pb-24 bg-[#2d2e2b]" style="background:#2d2e2b !important; background-image:none !important;">
                <div id="mpe-ing-section" class="mb-4">
                    <p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Składniki</p>
                    <div id="mpe-ing-list" class="space-y-1.5"></div>
                    <div id="mpe-add-area" class="mt-2"></div>
                </div>
            </div>
            <div id="mpe-footer-wrap" class="absolute bottom-0 left-0 right-0 z-[2] px-5 pb-4 flex justify-center" style="pointer-events:none; padding-bottom:calc(1.7rem + env(safe-area-inset-bottom));">
                <button id="mpe-confirm-btn" type="button" class="border h-10 px-9 rounded-full font-semibold text-[13px] transition-colors inline-flex items-center justify-center gap-2" style="pointer-events:auto; background:#dcd6cb !important; color:#2d2e2b !important; background-image:none !important; border-color:#dcd6cb !important; box-shadow:0 4px 16px rgba(0,0,0,0.28), 0 1px 4px rgba(0,0,0,0.2);">
                    <i id="mpe-confirm-icon" class="fas fa-calendar-plus text-[11px]" aria-hidden="true"></i>
                    <span id="mpe-confirm-label">Dodaj do planu</span>
                </button>
            </div>
        </div>
    </div>
    ${getProductCardHTML()}`;
}

/* ── 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: '',
        productSelections: {},
    };

    /* ── helpers ───────────────────────────────────── */

    function nutFor(ingredientId, amount, unit) {
        const def = INGREDIENTS[ingredientId];
        if (!def) return null;
        const productId = S.productSelections[ingredientId] || null;
        const product = productId ? PRODUCTS[productId] : null;
        const nutrition = product?.nutritionPer100g || def.nutritionPer100g;
        if (!nutrition) return null;
        let g = amount;
        if ((unit === 'szt.' || unit === 'szt') && def.weightPerPiece) g = amount * def.weightPerPiece;
        const f = g / 100;
        return {
            kcal: Math.round(nutrition.kcal * f),
            protein: Math.round(nutrition.protein * f * 10) / 10,
            fat: Math.round(nutrition.fat * f * 10) / 10,
            carbs: Math.round(nutrition.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 `<button type="button" class="mpe-slot-btn px-3 py-1.5 rounded-full border text-[12px] font-semibold transition-colors" data-slot-id="${s.id}" style="background:${bg} !important; background-image:none !important; box-shadow:none !important; border-color:${border} !important; color:${text} !important;">${esc(s.label)}</button>`;
        }).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 = `
            <div class="flex items-center justify-between gap-3">
                <p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider">Porcje</p>
                <div class="flex h-[2rem] w-[5.25rem] shrink-0 items-center gap-0.5 rounded-full border px-0.5" style="background:#2f2f2d;border-color:#444442;box-shadow:0 2px 8px rgba(0,0,0,0.25);">
                    <button type="button" id="mpe-serv-minus" class="shrink-0 w-7 h-full flex items-center justify-center rounded-full border-0 bg-transparent text-[#d7d2c8] transition-colors" aria-label="Zmniejsz liczbę porcji">
                        <i class="fas fa-minus text-[10px]"></i>
                    </button>
                    <span id="mpe-serv-count" class="flex-1 h-full inline-flex items-center justify-center px-0.5 text-[12px] font-semibold leading-none text-[#d7d2c8] tabular-nums">${S.servings}</span>
                    <button type="button" id="mpe-serv-plus" class="shrink-0 w-7 h-full flex items-center justify-center rounded-full border-0 bg-transparent text-[#d7d2c8] transition-colors" aria-label="Zwiększ liczbę porcji">
                        <i class="fas fa-plus text-[10px]"></i>
                    </button>
                </div>
            </div>`;
    }

    /* ── 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) =>
            `<button type="button" class="${cls} shrink-0 w-6 h-6 rounded-full border border-gray-200 text-gray-300 hover:text-red-500 hover:border-red-200 hover:bg-red-50 flex items-center justify-center transition-colors" ${attrs}><i class="fas fa-minus text-[8px]"></i></button>`;

        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:0 2px 8px rgba(0,0,0,0.25) !important; border:none !important;';

            const shuffleBtn = hasAlts
                ? `<button type="button" class="mpe-shuffle shrink-0 w-5 h-5 flex items-center justify-center transition-colors text-gray-400 hover:text-gray-300" style="background:transparent !important; box-shadow:none !important;" data-orig-id="${esc(id)}" aria-label="Wybierz zamiennik składnika"><i class="fas fa-shuffle text-[10px]"></i></button>`
                : '';
            const modDot = modified ? '<span class="w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"></span>' : '';

            html += `<div class="mpe-ing-row rounded-xl p-2.5" style="${rowStyle}" data-orig-id="${esc(id)}" data-type="recipe">`;
            const selectedProductId = S.productSelections[eid];
            const selectedProduct = selectedProductId ? PRODUCTS[selectedProductId] : null;
            const productBadge = selectedProduct
                ? `<div class="flex items-center gap-1 mt-0.5"><span class="text-[10px] text-emerald-400 truncate">${esc(selectedProduct.name)}</span><button type="button" class="mpe-change-product text-[9px] text-gray-500 hover:text-gray-300 transition-colors" data-eid="${esc(eid)}" data-orig-id="${esc(id)}">zmień</button></div>`
                : '';

            html += `<div class="flex items-center gap-2">`;
            html += `<div class="flex-1 min-w-0 mpe-open-product-card cursor-pointer" data-eid="${esc(eid)}" data-pid="${esc(selectedProductId || '')}"><span class="text-[12px] font-semibold text-gray-900 truncate block">${esc(eName)}</span>${productBadge}</div>`;
            html += `<div class="shrink-0 flex items-center gap-2">`;
            html += shuffleBtn;
            html += `<button type="button" class="mpe-edit-amt shrink-0 flex items-center gap-1 px-2 py-1 rounded-lg hover:bg-gray-100 transition-colors" data-orig-id="${esc(id)}" data-type="recipe">`;
            html += `${modDot}<span class="text-[12px] font-semibold text-gray-900 tabular-nums">${fmtAmt(disp)}</span>`;
            html += `<span class="text-[11px] text-gray-500">${esc(ing.unit)}</span></button>`;
            html += removeBtn('mpe-remove-ing', `data-orig-id="${esc(id)}" data-type="recipe"`);
            html += `</div>`;
            html += `</div>`;

            if (hasAlts && altOpen) {
                const opts = [id, ...ing.alternatives];
                html += '<div class="mt-2 ml-1 space-y-1">';
                for (const altId of opts) {
                    const def = INGREDIENTS[altId];
                    const name = def?.name || altId;
                    const isSel = eid === altId;
                    const checkbox = `
                        <span class="ml-auto self-center w-[18px] h-[18px] rounded-full shrink-0 flex items-center justify-center"
                              style="border:1.5px solid #56534f; background:transparent;">
                            ${isSel ? '<i class="fas fa-check" style="color:#9b978f; font-size:8px; line-height:1; display:block; transform:translateY(0.5px);"></i>' : ''}
                        </span>`;
                    const n = nutFor(altId, disp, ing.unit);
                    const nLine = n ? `<div class="text-[10px] text-gray-400 mt-0.5 tabular-nums">${n.kcal} kcal · ${n.protein}g B · ${n.fat}g T · ${n.carbs}g W</div>` : '';
                    html += `<button type="button" class="mpe-alt-pick w-full text-left p-2.5 rounded-lg transition-all" style="background:#2f2f2d !important; background-image:none !important; border:none !important; box-shadow:none !important;" data-orig-id="${esc(id)}" data-alt-id="${esc(altId)}"><div class="flex items-center gap-3"><div class="min-w-0 flex-1"><div class="text-[11px] font-semibold text-gray-900">${esc(name)}</div>${nLine}</div>${checkbox}</div></button>`;
                }
                html += '</div>';
            }

            html += '</div>';
        }

        for (const a of S.added) {
            const def = INGREDIENTS[a.ingredientId];
            const name = def?.name || a.ingredientId;
            const disp = a.amount * S.servings;
            html += `<div class="mpe-ing-row rounded-xl p-2.5" style="background:#393937 !important; background-image:none !important; box-shadow:0 2px 8px rgba(0,0,0,0.25) !important; border:none !important;" data-ing-id="${esc(a.ingredientId)}" data-type="added">`;
            html += `<div class="flex items-center gap-2">`;
            const addedPid = S.productSelections[a.ingredientId] || '';
            const addedProduct = addedPid ? PRODUCTS[addedPid] : null;
            const addedBadge = addedProduct
                ? `<div class="flex items-center gap-1 mt-0.5"><span class="text-[10px] text-emerald-400 truncate">${esc(addedProduct.name)}</span></div>`
                : '';
            html += `<div class="flex-1 min-w-0 mpe-open-product-card cursor-pointer" data-eid="${esc(a.ingredientId)}" data-pid="${esc(addedPid)}"><div class="flex items-center gap-1.5"><span class="text-[12px] font-semibold text-gray-900 truncate">${esc(name)}</span><span class="shrink-0 inline-flex items-center justify-center text-[#8f8b84]" title="Dodany składnik" aria-label="Dodany składnik"><i class="fas fa-plus text-[8px]"></i></span></div>${addedBadge}</div>`;
            html += `<button type="button" class="mpe-edit-amt shrink-0 flex items-center gap-1 px-2 py-1 rounded-lg hover:bg-gray-100 transition-colors" data-ing-id="${esc(a.ingredientId)}" data-type="added">`;
            html += `<span class="text-[12px] font-semibold text-gray-900 tabular-nums">${fmtAmt(disp)}</span>`;
            html += `<span class="text-[11px] text-gray-500">${esc(a.unit)}</span></button>`;
            html += removeBtn('mpe-remove-ing', `data-ing-id="${esc(a.ingredientId)}" data-type="added"`);
            html += `</div></div>`;
        }

        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 += `<div class="flex items-center justify-between py-2 px-1">`;
            html += `<span class="text-[11px] text-gray-400">${label}</span>`;
            html += `<button type="button" id="mpe-restore-all" class="text-[11px] font-semibold text-gray-500 hover:text-gray-900 transition-colors">Przywróć</button>`;
            html += `</div>`;
        }

        list.innerHTML = html;
    }

    function renderAddArea() {
        const el = document.getElementById('mpe-add-area');
        if (!el) return;
        if (!S.addOpen) {
            el.innerHTML = `<button type="button" id="mpe-add-btn" class="w-full py-2 rounded-xl border border-dashed text-[12px] font-semibold transition-colors" style="border-color:#444442; color:#9b978f; background:transparent !important; box-shadow:none !important; -webkit-tap-highlight-color:transparent;"><i class="fas fa-plus text-[10px] mr-1.5 opacity-70"></i>Dodaj składnik</button>`;
            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 = `
            <div class="rounded-xl p-3" style="background:#393937 !important; border:1px solid #444442;">
                <div class="flex items-center gap-2 mb-2">
                    <input type="text" id="mpe-add-search" class="flex-1 rounded-lg px-3 py-1.5 text-[12px] outline-none placeholder:text-[#8f8b84]" style="background:#2f2f2d !important; border:1px solid #444442; color:#ddd6ca;" placeholder="Szukaj składnika…" value="${esc(S.addQuery)}">
                    <button type="button" id="mpe-add-cancel" class="text-[11px] font-semibold px-2 py-1 transition-colors" style="color:#9b978f;">Anuluj</button>
                </div>
                <div class="max-h-40 overflow-y-auto space-y-1 no-scrollbar" id="mpe-add-results">
                    ${avail.length === 0
                        ? '<p class="rounded-lg px-2.5 py-3 text-[11px] text-center" style="background:#2f2f2d !important; color:#9b978f;">Brak wyników</p>'
                        : avail.slice(0, 20).map((i) => `<button type="button" class="mpe-add-pick w-full text-left px-2.5 py-2 rounded-lg transition-colors text-[12px] font-medium" style="background:#2f2f2d !important; color:#ddd6ca;" data-ing-id="${esc(i.id)}">${esc(i.name)} <span class="text-[10px]" style="color:#9b978f;">${esc(i.category)}</span></button>`).join('')}
                </div>
            </div>`;
    }

    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
            ? '<p class="rounded-lg px-2.5 py-3 text-[11px] text-center" style="background:#2f2f2d !important; color:#9b978f;">Brak wyników</p>'
            : avail.slice(0, 20).map((i) => `<button type="button" class="mpe-add-pick w-full text-left px-2.5 py-2 rounded-lg transition-colors text-[12px] font-medium" style="background:#2f2f2d !important; color:#ddd6ca;" data-ing-id="${esc(i.id)}">${esc(i.name)} <span class="text-[10px]" style="color:#9b978f;">${esc(i.category)}</span></button>`).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 = `
            <div class="h-full pb-2 flex flex-col" style="background:#2d2e2b !important; background-image:none !important; box-shadow:none !important;">
                <p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Wartości odżywcze</p>
                <div class="flex-1 flex items-center">
                    <div class="grid grid-cols-4 gap-1.5 w-full">
                        <div class="rounded-xl px-2 py-1.5 text-center" style="background:#393937;">
                            <p class="text-[15px] font-bold text-gray-100 tabular-nums leading-tight">${n.kcal}</p>
                            <p class="text-[9px] text-gray-500 font-medium">kcal</p>
                        </div>
                        <div class="rounded-xl px-2 py-1.5 text-center" style="background:#393937;">
                            <p class="text-[15px] font-bold text-blue-400 tabular-nums leading-tight">${n.protein}g</p>
                            <p class="text-[9px] text-gray-500 font-medium">białko</p>
                        </div>
                        <div class="rounded-xl px-2 py-1.5 text-center" style="background:#393937;">
                            <p class="text-[15px] font-bold text-amber-400 tabular-nums leading-tight">${n.fat}g</p>
                            <p class="text-[9px] text-gray-500 font-medium">tłuszcz</p>
                        </div>
                        <div class="rounded-xl px-2 py-1.5 text-center" style="background:#393937;">
                            <p class="text-[15px] font-bold text-orange-400 tabular-nums leading-tight">${n.carbs}g</p>
                            <p class="text-[9px] text-gray-500 font-medium">węgl.</p>
                        </div>
                    </div>
                </div>
            </div>`;
        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 = '';

        // Auto-select products from pantry, then apply saved selections
        const pantry = loadPantry();
        S.productSelections = autoSelectProducts(recipe, pantry);
        if (opts.entry?.productSelections) {
            Object.assign(S.productSelections, opts.entry.productSelections);
        }

        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';
        const confirmIcon = document.getElementById('mpe-confirm-icon');
        if (confirmIcon) {
            confirmIcon.className = S.mode === 'edit'
                ? 'fas fa-check text-[11px]'
                : 'fas fa-calendar-plus text-[11px]';
        }

        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 }));
        if (Object.keys(S.productSelections).length > 0) entry.productSelections = { ...S.productSelections };
        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();
        window.refreshPlanner?.();
    }

    /* ── Event bindings ───────────────────────────── */

    overlay?.addEventListener('click', (e) => { if (e.target === overlay) closeEditor(); });

    /* ── Swipe-to-dismiss ────────────────────────── */
    const header = sheet?.children[0];
    if (header && sheet) {
        let startY = 0, currentY = 0, dragging = false;
        header.addEventListener('touchstart', (e) => {
            startY = e.touches[0].clientY;
            currentY = 0;
            dragging = true;
            sheet.style.transition = 'none';
        }, { passive: true });
        header.addEventListener('touchmove', (e) => {
            if (!dragging) return;
            currentY = Math.max(0, e.touches[0].clientY - startY);
            sheet.style.transform = `translateY(${currentY}px)`;
        }, { passive: true });
        header.addEventListener('touchend', () => {
            if (!dragging) return;
            dragging = false;
            sheet.style.transition = 'transform 300ms cubic-bezier(0.32,0.72,0,1)';
            if (currentY > 120) {
                closeEditor();
            } else {
                sheet.style.transform = 'translateY(0)';
            }
        });
    }
    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();
    });

    /* ── Product card ────────────────────────────── */

    document.getElementById('mpe-pc-close')?.addEventListener('click', closeProductCard);
    document.getElementById('mpe-product-card-overlay')?.addEventListener('click', (e) => {
        if (e.target.id === 'mpe-product-card-overlay') closeProductCard();
    });

    /* ── Ingredient section delegation ────────────── */

    const ingSec = document.getElementById('mpe-ing-section');

    ingSec?.addEventListener('click', (e) => {
        // Check "zmień" and other inner buttons before the card wrapper
        const changeProdEarly = e.target.closest('.mpe-change-product');
        if (!changeProdEarly) {
            const cardBtn = e.target.closest('.mpe-open-product-card');
            if (cardBtn) {
                openProductCard(cardBtn.dataset.eid, cardBtn.dataset.pid || null);
                return;
            }
        }

        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;
            const prevEid = S.subs[origId] || origId;
            if (altId === origId) delete S.subs[origId]; else S.subs[origId] = altId;
            const newEid = S.subs[origId] || origId;
            // Update product selection for the new effective ingredient
            if (newEid !== prevEid) {
                delete S.productSelections[prevEid];
                const newProducts = getProductsForIngredient(newEid);
                if (newProducts.length > 0) {
                    const pantry = loadPantry();
                    const auto = autoSelectProducts({ ingredients: [{ ingredientId: newEid }] }, pantry);
                    if (auto[newEid]) S.productSelections[newEid] = auto[newEid];
                }
            }
            S.altOpen.delete(origId);
            renderIngList(); renderNutrition();
            return;
        }

        const changeProd = e.target.closest('.mpe-change-product');
        if (changeProd) {
            const eid = changeProd.dataset.eid;
            const products = getProductsForIngredient(eid);
            if (products.length === 0) return;
            // Toggle product picker open/closed using a data attribute on the row
            const row = changeProd.closest('.mpe-ing-row');
            const existing = row?.querySelector('.mpe-product-picker');
            if (existing) { existing.remove(); return; }

            const currentPid = S.productSelections[eid] || null;
            const origId = changeProd.dataset.origId || eid;
            const recipe = RECIPES[S.recipeId];
            const recipeIng = recipe?.ingredients.find(i => i.ingredientId === origId);
            const ingUnit = recipeIng?.unit || 'g';
            const ingBase = S.overrides[origId] ?? recipeIng?.amount ?? 0;
            const ingDisp = ingBase * S.servings;

            const checkmark = (sel) => `<span class="ml-auto self-center w-[18px] h-[18px] rounded-full shrink-0 flex items-center justify-center" style="border:1.5px solid #56534f; background:transparent;">${sel ? '<i class="fas fa-check" style="color:#9b978f; font-size:8px; line-height:1; display:block; transform:translateY(0.5px);"></i>' : ''}</span>`;

            let pickerHtml = '<div class="mpe-product-picker mt-2 ml-1 space-y-1">';
            for (const p of products) {
                const isSel = currentPid === p.id;
                const pNut = p.nutritionPer100g;
                // Calculate nutrition for the actual ingredient amount using product values
                const def = INGREDIENTS[eid];
                let g = ingDisp;
                if ((ingUnit === 'szt.' || ingUnit === 'szt') && def?.weightPerPiece) g = ingDisp * def.weightPerPiece;
                const f = g / 100;
                const n = pNut ? { kcal: Math.round(pNut.kcal * f), protein: Math.round(pNut.protein * f * 10) / 10, fat: Math.round(pNut.fat * f * 10) / 10, carbs: Math.round(pNut.carbs * f * 10) / 10 } : null;
                const nLine = n ? `<div class="text-[10px] text-gray-400 mt-0.5 tabular-nums">${n.kcal} kcal · ${n.protein}g B · ${n.fat}g T · ${n.carbs}g W</div>` : '';
                pickerHtml += `<button type="button" class="mpe-prod-pick w-full text-left p-2.5 rounded-lg transition-all" style="background:#2f2f2d !important; background-image:none !important; border:none !important; box-shadow:none !important;" data-eid="${esc(eid)}" data-prod-id="${esc(p.id)}">
                    <div class="flex items-center gap-3"><div class="min-w-0 flex-1"><div class="text-[11px] font-semibold text-gray-900">${esc(p.name)}</div>${nLine}</div>${checkmark(isSel)}</div>
                </button>`;
            }
            pickerHtml += '</div>';
            row?.insertAdjacentHTML('beforeend', pickerHtml);
            return;
        }

        const prodPick = e.target.closest('.mpe-prod-pick');
        if (prodPick) {
            const eid = prodPick.dataset.eid;
            const prodId = prodPick.dataset.prodId;
            if (prodId) {
                S.productSelections[eid] = prodId;
                saveLastProductSelection(eid, prodId);
            }
            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 = `<input type="number" class="mpe-amt-input w-16 text-right text-[12px] font-semibold text-gray-900 border border-gray-300 rounded-lg px-2 py-1 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 outline-none tabular-nums" value="${currentDisplay}" min="0" step="any"><span class="text-[11px] text-gray-500 ml-1">${esc(unitText)}</span>`;

        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;
}
