import {
addFreeformLine,
addFreeformList,
applyCheckedKitchenListToPantry,
categoryLabel,
clearCheckedInList,
deleteList,
getActiveList,
getListSummaries,
KITCHEN_LIST_ID,
removeItemFromList,
setActiveListId,
toggleItemInList,
updateKitchenItemAmount,
} from '../services/pantryShopping.js';
import { showAppToast } from '../ui/toast.js';
function escapeHtml(s) {
return String(s)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"');
}
export function getShoppingHTML() {
return `
`;
}
function syncListSelect() {
const sel = document.getElementById('shopping-list-select');
if (!sel) return;
const { lists, activeListId } = getListSummaries();
sel.innerHTML = lists.map((l) => {
const suffix = l.openCount ? ` (${l.openCount})` : '';
const label = `${l.name}${suffix}`;
return ``;
}).join('');
sel.value = activeListId;
}
function syncChromeForList() {
const list = getActiveList();
const isKitchen = list.type === 'kitchen';
const delBtn = document.getElementById('shopping-delete-list');
const ffAdd = document.getElementById('shopping-freeform-add');
const kitchenActions = document.getElementById('shopping-kitchen-actions');
if (ffAdd) ffAdd.classList.toggle('hidden', isKitchen);
if (delBtn) delBtn.classList.toggle('hidden', isKitchen);
if (kitchenActions) {
const hasChecked = isKitchen && list.items.some((i) => i.checked);
kitchenActions.classList.toggle('hidden', !hasChecked);
}
}
function renderKitchenItems() {
const root = document.getElementById('shopping-list-root');
if (!root) return;
const list = getActiveList();
if (list.type !== 'kitchen') return;
const items = list.items;
if (items.length === 0) {
root.innerHTML = 'Brak pozycji.
';
return;
}
const groups = {};
for (const it of items) {
const c = it.category || 'inne';
if (!groups[c]) groups[c] = [];
groups[c].push(it);
}
root.innerHTML = Object.keys(groups)
.sort((a, b) => categoryLabel(a).localeCompare(categoryLabel(b)))
.map((cat) => `
${escapeHtml(categoryLabel(cat))}
${groups[cat].map((it) => `
-
${escapeHtml(it.name)}
${it.sourceNote ? `
${escapeHtml(it.sourceNote)}
` : ''}
`).join('')}
`)
.join('');
bindItemButtons(list.id);
}
function renderFreeformItems() {
const root = document.getElementById('shopping-list-root');
if (!root) return;
const list = getActiveList();
if (list.type !== 'freeform') return;
const items = list.items;
if (items.length === 0) {
root.innerHTML = 'Dodaj dowolny tekst powyżej — bez powiązania z katalogiem składników.
';
return;
}
root.innerHTML = `
${items.map((it) => `
-
${escapeHtml(it.text)}
${it.note ? `
${escapeHtml(it.note)}
` : ''}
`).join('')}
`;
bindItemButtons(list.id);
}
function bindItemButtons(listId) {
const root = document.getElementById('shopping-list-root');
if (!root) return;
root.querySelectorAll('[data-shop-toggle]').forEach((btn) => {
btn.addEventListener('click', () => {
const id = btn.getAttribute('data-shop-toggle');
if (id) toggleItemInList(listId, id);
refreshShopping();
});
});
root.querySelectorAll('[data-shop-remove]').forEach((btn) => {
btn.addEventListener('click', () => {
const id = btn.getAttribute('data-shop-remove');
if (id) removeItemFromList(listId, id);
refreshShopping();
});
});
root.querySelectorAll('[data-shop-edit-amount]').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const itemId = btn.getAttribute('data-shop-edit-amount');
const current = btn.getAttribute('data-current-amount');
const unit = btn.getAttribute('data-unit');
const newVal = window.prompt(`Nowa ilość (${unit}):`, current);
if (newVal === null) return;
const num = parseFloat(newVal.replace(',', '.'));
if (!Number.isFinite(num) || num < 0) {
showAppToast('Nieprawidłowa wartość.');
return;
}
updateKitchenItemAmount(listId, itemId, num);
refreshShopping();
});
});
}
export function refreshShopping() {
syncListSelect();
syncChromeForList();
const list = getActiveList();
if (list.type === 'kitchen') renderKitchenItems();
else renderFreeformItems();
}
export function setupShopping() {
const sel = document.getElementById('shopping-list-select');
sel?.addEventListener('change', () => {
const v = sel.value;
if (v) setActiveListId(v);
refreshShopping();
});
document.getElementById('shopping-new-list')?.addEventListener('click', () => {
const name = window.prompt('Nazwa nowej listy (dowolne zakupy):', 'Nowa lista');
if (name === null) return;
addFreeformList(name);
showAppToast('Utworzono listę.');
refreshShopping();
});
document.getElementById('shopping-delete-list')?.addEventListener('click', () => {
const list = getActiveList();
if (list.id === KITCHEN_LIST_ID) return;
if (!window.confirm(`Usunąć listę „${list.name}”?`)) return;
deleteList(list.id);
showAppToast('Lista usunięta.');
refreshShopping();
});
const submitFreeform = () => {
const list = getActiveList();
if (list.type !== 'freeform') return;
const input = document.getElementById('shopping-freeform-input');
const note = document.getElementById('shopping-freeform-note');
const text = input?.value || '';
addFreeformLine(list.id, text, note?.value || '');
if (input) input.value = '';
if (note) note.value = '';
refreshShopping();
};
document.getElementById('shopping-freeform-submit')?.addEventListener('click', submitFreeform);
document.getElementById('shopping-freeform-input')?.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
submitFreeform();
}
});
document.getElementById('shopping-to-pantry')?.addEventListener('click', () => {
const list = getActiveList();
if (list.type !== 'kitchen') return;
const checked = list.items.filter((i) => i.checked);
if (checked.length === 0) return;
const preview = checked.map((i) => ` • ${i.name}: ${i.amount} ${i.unit}`).join('\n');
if (!window.confirm(`Przenieść do spiżarni?\n\n${preview}`)) return;
applyCheckedKitchenListToPantry();
showAppToast(`Przeniesiono ${checked.length} pozycji do spiżarni.`);
window.refreshPantry?.();
refreshShopping();
});
document.getElementById('shopping-clear-checked')?.addEventListener('click', () => {
const list = getActiveList();
const checkedCount = list.items.filter((i) => i.checked).length;
if (checkedCount === 0) return;
clearCheckedInList(list.id);
showAppToast(`Usunięto ${checkedCount} kupionych pozycji.`);
refreshShopping();
});
refreshShopping();
window.refreshShopping = refreshShopping;
}