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-107';

/* ── helpers ── */

function esc(s) {
    return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

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 `<img src="${esc(image)}" alt="" class="${sizeClass} ${radiusClass} object-cover shrink-0">`;
    }
    return `<div class="${sizeClass} ${radiusClass} flex items-center justify-center shrink-0" style="background:#2f2f2d;"><i class="fas ${icon} text-sm" style="color:#8f8b84;"></i></div>`;
}

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 `
    <div id="pantry-view" class="hidden flex flex-col h-full absolute inset-0 overflow-hidden z-10" style="background:#2d2e2b !important;">

        <!-- ── floating search bar ── -->
        <div class="pointer-events-none absolute inset-x-0 top-0 z-[12] px-4 pt-4" style="background:transparent !important; border:none !important;">
            <div id="pantry-search-shell" class="pointer-events-auto relative z-[1] mx-auto flex items-center w-full overflow-hidden" style="width:min(calc(100% - 0.5rem), 22.4rem); background:#393937 !important; border:1px solid #41423f !important; border-radius:999px !important; box-shadow:${SEARCH_SHELL_SHADOW} !important;">
                <input type="search" id="pantry-search" autocomplete="off" placeholder="Szukaj w spiżarni…"
                    class="w-full bg-transparent outline-none text-[15px] text-center py-[12px] px-8" style="background:transparent !important; border:none !important; box-shadow:none !important; color:#ddd6ca;">
            </div>
        </div>

        <!-- ── scrollable content ── -->
        <div id="pantry-scroll" class="flex-1 overflow-y-auto no-scrollbar px-4 pt-[5.5rem] pb-24" style="background:#2d2e2b !important;">
            <div id="pantry-board" class="space-y-4"></div>
        </div>

        ${getIngredientCardHTML({
        idBase: 'pv2-card',
        overlayClass: 'absolute inset-0 z-[60] hidden opacity-0 transition-opacity duration-200 flex items-center justify-center p-5',
    })}
    </div>`;
}

/* ══════════════════════ 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 `<button type="button" class="pv2-chip shrink-0 w-[9.5rem] rounded-2xl px-3 py-2.5 text-left transition-colors active:scale-[0.99]" style="background:#393937; border:1px solid #444442; box-shadow:inset 0 1px 0 rgba(255,255,255,0.02);" data-id="${esc(id)}">
        <div class="w-full h-1 rounded-full mb-2" style="background:${accent}; opacity:${hasStock ? '1' : '0.45'};"></div>
        <div class="flex items-start gap-2">
            ${mediaHtml(def.image, icon, 'w-8 h-8', 'rounded-lg')}
            <div class="min-w-0 flex-1">
                <span class="block text-[12px] font-semibold leading-[1.2] overflow-hidden" style="color:#ddd6ca; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical;">
                    ${esc(def.name)}
                </span>
            </div>
        </div>
        <div class="mt-4">
            <div class="flex items-end justify-between gap-2">
                <span class="text-[14px] font-bold tabular-nums leading-none block" style="color:${qtyColor};">${esc(formatQtyWithUnit(qty, def.pantryUnit))}</span>
                <span class="inline-flex items-center rounded-full px-1.5 py-0.5 text-[9px] font-semibold shrink-0" style="background:#2f2f2d; color:#9b978f;">${esc(badgeText)}</span>
            </div>
        </div>
    </button>`;
}

function groupByCategory(ids) {
    /** @type {Map<string, string[]>} */
    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 = `<p class="text-sm text-center py-10" style="color:#9b978f;">Brak wyników — zmień wyszukiwanie.</p>`;
        return;
    }

    const groups = groupByCategory(visible);
    root.innerHTML = groups.map(({ cat, ids }) => {
        const icon = CATEGORY_ICONS[cat] || 'fa-jar';
        return `
        <section class="mb-4 last:mb-0">
            <div class="mb-2 px-0.5">
                <p class="text-[10px] font-bold uppercase tracking-wider" style="color:#9b978f;">
                    <i class="fas ${icon} text-[10px] mr-1"></i>${esc(categoryLabel(cat))}
                </p>
                <p class="text-[10px] mt-1" style="color:#6d6c67;">${ids.length} ${getCategoryItemLabel(ids.length)}</p>
            </div>
            <div class="overflow-x-auto no-scrollbar -mx-4 px-4">
                <div class="flex gap-2.5 pb-1">
                    ${ids.map((rowId) => ingredientRowHtml(rowId, pantry)).join('')}
                </div>
            </div>
        </section>`;
    }).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;
}
