import {
INGREDIENTS,
CATEGORY_LABELS,
getProductsForIngredient,
ingredientHasProducts,
} from '../data/catalog.js?v=8';
import {
categoryLabel,
loadPantry,
getPantryTotal,
} from '../services/pantryShopping.js?v=2';
import { createIngredientCardController, getIngredientCardHTML } from '../ui/ingredientCard.js?v=20260410-99';
/* ── helpers ── */
function esc(s) {
return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
}
function unitLabel(u) {
return u === 'szt' ? 'szt.' : u;
}
function normalizeSearch(q) {
return String(q).trim().toLowerCase();
}
function formatQty(n) {
const rounded = Math.round((Number(n) || 0) * 10) / 10;
return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1).replace(/\.0$/, '');
}
function formatQtyWithUnit(qty, unit) {
return `${formatQty(qty)} ${unitLabel(unit)}`;
}
function productCountShortLabel(count) {
return `${count} prod.`;
}
function mediaHtml(image, icon, sizeClass = 'w-11 h-11', radiusClass = 'rounded-2xl') {
if (image) {
return `
`;
}
return `
`;
}
const CATEGORY_ICONS = {
pieczywo: 'fa-bread-slice',
nabial: 'fa-cheese',
mieso_ryby: 'fa-drumstick-bite',
warzywa: 'fa-carrot',
owoce: 'fa-apple-whole',
suche: 'fa-wheat-awn',
przyprawy: 'fa-leaf',
inne: 'fa-jar',
};
const SEARCH_SHELL_SHADOW = '0 5px 10px rgba(0,0,0,0.16), 0 14px 22px rgba(0,0,0,0.24), 0 22px 34px rgba(0,0,0,0.18), inset 0 1px 0 rgba(255,255,255,0.04)';
/* ── state ── */
let ingredientCard = null;
/* ══════════════════════ HTML SHELL ══════════════════════ */
export function getPantryHTML() {
return `
${getIngredientCardHTML({
idBase: 'pv2-card',
overlayClass: 'absolute inset-0 z-[60] hidden opacity-0 transition-opacity duration-200 flex items-center justify-center p-5',
})}
`;
}
/* ══════════════════════ BOARD RENDERING ══════════════════════ */
function getFilteredIds(searchRaw) {
const q = normalizeSearch(searchRaw);
return Object.keys(INGREDIENTS).filter((id) => {
const d = INGREDIENTS[id];
if (!q) return true;
return d.name.toLowerCase().includes(q) || (CATEGORY_LABELS[d.category] || '').toLowerCase().includes(q);
}).sort((a, b) => INGREDIENTS[a].name.localeCompare(INGREDIENTS[b].name, 'pl'));
}
function getCategoryItemLabel(count) {
if (count === 1) return 'składnik';
const mod10 = count % 10;
const mod100 = count % 100;
if (mod10 >= 2 && mod10 <= 4 && !(mod100 >= 12 && mod100 <= 14)) return 'składniki';
return 'składników';
}
function ingredientRowHtml(id, pantry) {
const def = INGREDIENTS[id];
const icon = CATEGORY_ICONS[def.category] || 'fa-jar';
const qty = getPantryTotal(id, pantry);
const hasProducts = ingredientHasProducts(id);
const products = hasProducts ? getProductsForIngredient(id) : [];
const hasStock = qty > 0;
const accent = hasStock ? '#6ee7b7' : '#4b4a46';
const qtyColor = hasStock ? '#6ee7b7' : '#d7d2c8';
const badgeText = hasProducts ? productCountShortLabel(products.length) : unitLabel(def.pantryUnit);
return ``;
}
function groupByCategory(ids) {
/** @type {Map} */
const groups = new Map();
for (const id of ids) {
const cat = INGREDIENTS[id].category;
if (!groups.has(cat)) groups.set(cat, []);
groups.get(cat).push(id);
}
return [...groups.keys()]
.sort((a, b) => categoryLabel(a).localeCompare(categoryLabel(b)))
.map((cat) => ({ cat, ids: groups.get(cat) }));
}
function renderBoard() {
const root = document.getElementById('pantry-board');
if (!root) return;
const q = document.getElementById('pantry-search')?.value || '';
const pantry = loadPantry();
const visible = getFilteredIds(q);
if (visible.length === 0) {
root.innerHTML = `Brak wyników — zmień wyszukiwanie.
`;
return;
}
const groups = groupByCategory(visible);
root.innerHTML = groups.map(({ cat, ids }) => {
const icon = CATEGORY_ICONS[cat] || 'fa-jar';
return `
${esc(categoryLabel(cat))}
${ids.length} ${getCategoryItemLabel(ids.length)}
`;
}).join('');
root.querySelectorAll('.pv2-chip').forEach((btn) => {
btn.addEventListener('click', () => openIngredientCard(btn.dataset.id, null));
});
}
/* ══════════════════════ INGREDIENT SHEET ══════════════════════ */
function openIngredientCard(ingredientId, productId) {
ingredientCard?.open({
ingredientId,
productId,
sourceNote: 'Ze spiżarni',
onAfterChange: () => renderBoard(),
});
}
/* ══════════════════════ PUBLIC API ══════════════════════ */
export function refreshPantry() {
renderBoard();
ingredientCard?.refresh();
}
export function setupPantry() {
if (!ingredientCard) {
ingredientCard = createIngredientCardController({ idBase: 'pv2-card', defaultSourceNote: 'Ze spiżarni' });
ingredientCard.bind();
}
renderBoard();
document.getElementById('pantry-search')?.addEventListener('input', () => renderBoard());
window.refreshPantry = refreshPantry;
}