import { RECIPES, INGREDIENTS } from '../data/catalog.js?v=8';
import { MEAL_SLOTS } from '../planner/mealSlots.js';

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

const slotLabelMap = Object.fromEntries(MEAL_SLOTS.map((s) => [s.id, s.label]));
const RD_THEME = Object.freeze({
    surface: '#393937',
    surfaceSoft: '#2f2f2d',
    surfaceActive: '#23221e',
    border: '#444442',
    borderSoft: '#56534f',
    borderStrong: '#787876',
    textPrimary: '#ddd6ca',
    textSecondary: '#d7d2c8',
    textMuted: '#9b978f',
});

function forceBg(bg) {
    return `background:${bg} !important; background-image:none !important; box-shadow:none !important;`;
}

function forceBgBorder(bg, border) {
    return `${forceBg(bg)} border:1px solid ${border} !important;`;
}

function renderTagChip(label) {
    return `<span class="px-3 py-1 rounded-full text-[11px] font-semibold inline-flex items-center" style="${forceBgBorder(RD_THEME.surfaceSoft, RD_THEME.border)} color:${RD_THEME.textSecondary} !important;">${escapeHtml(label)}</span>`;
}

function setTabButtonState(btn, active) {
    if (!btn) return;
    btn.style.color = active ? RD_THEME.textPrimary : RD_THEME.textMuted;
    btn.style.borderBottomColor = active ? RD_THEME.borderStrong : 'transparent';
    btn.style.fontWeight = active ? '600' : '500';
}

export function getRecipeDetailHTML() {
    return `
    <style>
        #rd-tab-bar::after {
            content: '';
            position: absolute;
            left: 0; right: 0; bottom: -8px;
            height: 8px;
            background: linear-gradient(to bottom, rgba(0,0,0,0.25), transparent);
            opacity: 0;
            transition: opacity 0.2s;
            pointer-events: none;
        }
        #rd-tab-bar.rd-scrolled::after {
            opacity: 1;
        }
    </style>
    <div id="recipe-detail-view" class="absolute inset-0 bg-[#2d2e2b] z-30 transition-all duration-300 ease-in-out translate-x-full opacity-0 pointer-events-none flex flex-col overflow-hidden" style="background:#2d2e2b !important; background-image:none !important;">
        <div class="absolute top-0 w-full p-3.5 flex justify-between z-40 mt-3">
            <button onclick="closeRecipeDetail()" class="w-9 h-9 rounded-full border flex items-center justify-center transition-opacity opacity-95 hover:opacity-100" style="background:rgba(47,47,45,0.92) !important; backdrop-filter:none !important; border-color:#444442 !important; color:#ddd6ca !important;">
                <i class="fas fa-arrow-left text-[13px]"></i>
            </button>
            <button id="rd-add-to-planner-btn" class="h-9 px-3 rounded-full border flex items-center justify-center gap-1.5 transition-opacity opacity-95 hover:opacity-100 text-[12px] font-semibold" style="background:rgba(47,47,45,0.92) !important; backdrop-filter:none !important; border-color:#444442 !important; color:#ddd6ca !important;">
                <i class="fas fa-calendar-plus text-[11px]"></i> Zaplanuj
            </button>
        </div>

        <div id="rd-hero" class="h-[236px] shrink-0 w-full relative overflow-hidden" style="background:linear-gradient(180deg, #3a3937 0%, #23221e 100%) !important;">
            <img id="rd-hero-img" src="" alt="" class="w-full h-full object-cover hidden">
            <div class="absolute inset-0 pointer-events-none" style="background:linear-gradient(to bottom, rgba(45,46,43,0.1), rgba(45,46,43,0.4), rgba(45,46,43,0.92));"></div>
            <span id="rd-hero-label" class="absolute inset-0 z-10 flex items-center justify-center font-medium text-[15px]" style="color:#ddd6ca;"></span>
        </div>

        <div class="bg-[#2d2e2b] rounded-t-3xl -mt-6 relative z-30 pt-6 flex flex-col flex-1 overflow-hidden" style="background:#2d2e2b !important; background-image:none !important; box-shadow:0 -8px 20px rgba(0,0,0,0.35) !important;">
            <div class="mb-3 px-5 shrink-0">
                <div class="flex justify-between items-start mb-2.5">
                    <h1 id="rd-title" class="text-xl font-bold leading-tight" style="color:#ddd6ca;"></h1>
                </div>
                <div id="rd-tags" class="flex flex-wrap gap-1.5 mb-3"></div>
                <div class="flex flex-wrap gap-2 text-[13px] font-medium">
                    <div class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border" style="background:#2f2f2d; border-color:#444442; color:#d7d2c8;">
                        <i class="fas fa-clock text-[10px]" style="color:#9b978f;"></i>
                        <span id="rd-time"></span>
                    </div>
                </div>
            </div>

            <div id="rd-tab-bar" class="flex border-b mb-2 px-5 shrink-0 relative z-10" style="border-color:#444442;">
                <button class="flex-1 pb-2.5 text-[13px] border-b-2 rd-tab-btn" data-rd-tab="ingredients" style="color:#ddd6ca; border-bottom-color:#787876; font-weight:600;">Składniki</button>
                <button class="flex-1 pb-2.5 text-[13px] border-b-2 rd-tab-btn" data-rd-tab="steps" style="color:#9b978f; border-bottom-color:transparent; font-weight:500;">Kroki</button>
            </div>

            <div class="flex-1 overflow-y-auto px-5 pt-2 pb-10 no-scrollbar relative" style="background:#2d2e2b !important; background-image:none !important; padding-bottom:calc(2.5rem + env(safe-area-inset-bottom));">
                <div id="rd-tab-ingredients" class="rd-tab-content block animate-fade-in"></div>
                <div id="rd-tab-steps" class="rd-tab-content hidden animate-fade-in"></div>
            </div>
        </div>
    </div>
    `;
}

/* ── state ─────────────────────────────────────────────── */

let currentRecipeId = null;
let currentServings = 1;
let currentSubstitutions = {};
let expandedAlternatives = new Set();

function getEffectiveIngredientId(originalId) {
    return currentSubstitutions[originalId] || originalId;
}

/* ── populate ──────────────────────────────────────────── */

function populateDetail(recipeId) {
    const recipe = RECIPES[recipeId];
    if (!recipe) return;

    currentRecipeId = recipeId;
    currentServings = 1;
    currentSubstitutions = {};
    expandedAlternatives.clear();

    const heroImg = document.getElementById('rd-hero-img');
    const heroLabel = document.getElementById('rd-hero-label');
    if (recipe.image) {
        heroImg.src = recipe.image;
        heroImg.alt = recipe.title;
        heroImg.classList.remove('hidden');
        heroLabel.textContent = '';
    } else {
        heroImg.classList.add('hidden');
        heroImg.src = '';
        heroLabel.textContent = `Zdjęcie: ${recipe.title}`;
    }
    document.getElementById('rd-title').textContent = recipe.title;
    document.getElementById('rd-time').textContent = `${recipe.minutes} min`;

    const tagsHtml = [];
    for (const slotId of recipe.allowedSlots) {
        const label = slotLabelMap[slotId];
        if (label) tagsHtml.push(renderTagChip(label));
    }
    for (const tag of (recipe.tags || [])) {
        tagsHtml.push(renderTagChip(tag));
    }
    document.getElementById('rd-tags').innerHTML = tagsHtml.join('');

    renderIngredients(recipe);
    renderSteps(recipe);

    const tabBtns = document.querySelectorAll('.rd-tab-btn');
    const tabs = document.querySelectorAll('.rd-tab-content');
    tabBtns.forEach((b) => {
        setTabButtonState(b, false);
    });
    setTabButtonState(tabBtns[0], true);
    tabs.forEach((t) => { t.classList.add('hidden'); t.classList.remove('block'); });
    document.getElementById('rd-tab-ingredients')?.classList.remove('hidden');
    document.getElementById('rd-tab-ingredients')?.classList.add('block');
}

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

function nutritionForAmount(ingredientId, amount, unit) {
    const def = INGREDIENTS[ingredientId];
    if (!def?.nutritionPer100g) return null;
    let grams = amount;
    if ((unit === 'szt.' || unit === 'szt') && def.weightPerPiece) {
        grams = amount * def.weightPerPiece;
    }
    const f = grams / 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 fmtAmt(n) {
    return Number.isInteger(n) ? String(n) : String(parseFloat(n.toFixed(1)));
}

/* ── ingredients tab with inline nutrition + summary ───── */

function computeEffectiveNutritionTotals(recipe) {
    let kcal = 0, protein = 0, fat = 0, carbs = 0;
    for (const ing of recipe.ingredients) {
        const effectiveId = getEffectiveIngredientId(ing.ingredientId);
        const n = nutritionForAmount(effectiveId, ing.amount * currentServings, ing.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 renderNutritionSummary(recipe) {
    const total = computeEffectiveNutritionTotals(recipe);

    return `
        <div class="mb-4">
            <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">${total.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">${total.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">${total.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">${total.carbs}g</p>
                            <p class="text-[9px] text-gray-500 font-medium">węgl.</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="mt-3 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="rd-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="rd-servings" class="flex-1 h-full inline-flex items-center justify-center px-0.5 text-[12px] font-semibold leading-none text-[#d7d2c8] tabular-nums">${currentServings}</span>
                    <button type="button" id="rd-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>
        </div>`;
}

function renderIngredients(recipe) {
    const container = document.getElementById('rd-tab-ingredients');
    if (!container) return;

    const rows = recipe.ingredients.map((ing) => {
        const origId = ing.ingredientId;
        const hasAlts = ing.alternatives && ing.alternatives.length > 0;
        const effectiveId = hasAlts ? getEffectiveIngredientId(origId) : origId;
        const effectiveDef = INGREDIENTS[effectiveId];
        const effectiveName = effectiveDef?.name || effectiveId;
        const scaledAmount = ing.amount * currentServings;
        const isExpanded = expandedAlternatives.has(origId);
        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 toggleBtn = hasAlts
            ? `<button type="button" class="rd-alt-toggle 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-original-id="${escapeHtml(origId)}" aria-label="Wybierz zamiennik składnika"><i class="fas fa-shuffle text-[10px]"></i></button>`
            : '';

        let rowHtml = `<div class="rd-ing-row rounded-xl p-2.5" style="${rowStyle}" data-original-id="${escapeHtml(origId)}">`;
        rowHtml += '<div class="flex items-center gap-2">';
        rowHtml += `<div class="flex-1 min-w-0"><span class="text-[12px] font-semibold text-gray-900 truncate block">${escapeHtml(effectiveName)}</span></div>`;
        rowHtml += '<div class="shrink-0 flex items-center gap-2">';
        rowHtml += toggleBtn;
        rowHtml += `<div class="shrink-0 flex items-center gap-1 px-2 py-1 rounded-lg">
            <span class="text-[12px] font-semibold text-gray-900 tabular-nums">${fmtAmt(scaledAmount)}</span>
            <span class="text-[11px] text-gray-500">${escapeHtml(ing.unit)}</span>
        </div>`;
        rowHtml += '</div>';
        rowHtml += '</div>';

        let altListHtml = '';
        if (hasAlts && isExpanded) {
            const allOptions = [origId, ...ing.alternatives];
            const optionCards = allOptions.map((altId) => {
                const def = INGREDIENTS[altId];
                const altName = def?.name || altId;
                const isSelected = effectiveId === altId;
                const altNutrition = nutritionForAmount(altId, scaledAmount, ing.unit);
                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;">
                        ${isSelected ? '<i class="fas fa-check" style="color:#9b978f; font-size:8px; line-height:1; display:block; transform:translateY(0.5px);"></i>' : ''}
                    </span>`;
                const nutritionLine = altNutrition
                    ? `<div class="text-[10px] text-gray-400 mt-0.5 tabular-nums">${altNutrition.kcal} kcal · ${altNutrition.protein}g B · ${altNutrition.fat}g T · ${altNutrition.carbs}g W</div>`
                    : '';

                return `<button type="button" class="rd-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-original-id="${escapeHtml(origId)}" data-alt-id="${escapeHtml(altId)}"><div class="flex items-center gap-3"><div class="min-w-0 flex-1"><div class="text-[11px] font-semibold text-gray-900">${escapeHtml(altName)}</div>${nutritionLine}</div>${checkbox}</div></button>`;
            });
            altListHtml = `
            <div class="mt-2 ml-1 space-y-1 rd-alt-options" data-original-id="${escapeHtml(origId)}">
                ${optionCards.join('')}
            </div>`;
        }

        rowHtml += altListHtml;
        rowHtml += '</div>';
        return `<li>${rowHtml}</li>`;
    }).join('');

    container.innerHTML = `
        ${renderNutritionSummary(recipe)}
        <ul class="space-y-1.5" id="rd-ingredient-list">${rows}</ul>`;

    container.querySelector('#rd-serv-minus')?.addEventListener('click', () => {
        if (currentServings <= 1) return;
        currentServings--;
        renderIngredients(recipe);
    });

    container.querySelector('#rd-serv-plus')?.addEventListener('click', () => {
        if (currentServings >= 12) return;
        currentServings++;
        renderIngredients(recipe);
    });

    container.querySelectorAll('.rd-alt-toggle').forEach((btn) => {
        btn.addEventListener('click', () => {
            const origId = btn.dataset.originalId;
            if (expandedAlternatives.has(origId)) {
                expandedAlternatives.delete(origId);
            } else {
                expandedAlternatives.add(origId);
            }
            renderIngredients(recipe);
        });
    });

    container.querySelectorAll('.rd-alt-options').forEach((group) => {
        group.querySelectorAll('[data-alt-id]').forEach((card) => {
            card.addEventListener('click', () => {
                const originalId = card.dataset.originalId;
                const altId = card.dataset.altId;
                if (altId === originalId) {
                    delete currentSubstitutions[originalId];
                } else {
                    currentSubstitutions[originalId] = altId;
                }
                expandedAlternatives.delete(originalId);
                renderIngredients(recipe);
            });
        });
    });
}

/* ── steps tab ─────────────────────────────────────────── */

function renderSteps(recipe) {
    const container = document.getElementById('rd-tab-steps');
    if (!container) return;

    const steps = recipe.steps || [];
    if (steps.length === 0) {
        container.innerHTML = `<p class="text-sm text-center py-8" style="color:${RD_THEME.textMuted};">Brak kroków przygotowania.</p>`;
        return;
    }

    container.innerHTML = `
        <div class="space-y-2 pb-5">
            ${steps.map((step, i) => `
            <div class="rounded-xl p-3 flex gap-3" style="background:transparent !important; background-image:none !important; box-shadow:none !important; border:none !important;">
                <div class="w-6 h-6 rounded-full flex items-center justify-center text-[11px] font-bold shrink-0" style="background:transparent !important; border:none !important; box-shadow:none !important; color:${RD_THEME.textSecondary} !important;">${i + 1}</div>
                <div class="pt-0.5"><p class="text-[13px] leading-relaxed" style="color:${RD_THEME.textSecondary};">${escapeHtml(step)}</p></div>
            </div>`).join('')}
        </div>`;
}

/* ── setup ─────────────────────────────────────────────── */

export function setupRecipeDetail() {
    document.querySelectorAll('.rd-tab-btn').forEach((btn) => {
        btn.addEventListener('click', () => {
            const tabId = btn.dataset.rdTab;
            document.querySelectorAll('.rd-tab-content').forEach((el) => {
                el.classList.add('hidden');
                el.classList.remove('block');
            });
            const target = document.getElementById(`rd-tab-${tabId}`);
            if (target) {
                target.classList.remove('hidden');
                target.classList.add('block');
                target.parentElement.scrollTop = 0;
            }

            document.querySelectorAll('.rd-tab-btn').forEach((b) => {
                setTabButtonState(b, false);
            });
            setTabButtonState(btn, true);
        });
    });

    /* ── tab-bar scroll shadow ─────────────────── */

    const scrollContainer = document.querySelector('#recipe-detail-view .overflow-y-auto');
    const tabBar = document.getElementById('rd-tab-bar');
    if (scrollContainer && tabBar) {
        scrollContainer.addEventListener('scroll', () => {
            tabBar.classList.toggle('rd-scrolled', scrollContainer.scrollTop > 2);
        });
    }

    /* ── planner — delegate to MealPlanEditor ─────── */

    document.getElementById('rd-add-to-planner-btn')?.addEventListener('click', () => {
        if (!currentRecipeId) return;
        window.openMealPlanEditor?.({
            mode: 'add',
            recipeId: currentRecipeId,
            servings: currentServings,
            substitutions: { ...currentSubstitutions },
        });
    });

    window.openRecipeDetail = (recipeId) => {
        if (!recipeId || !RECIPES[recipeId]) return;
        populateDetail(recipeId);
        const view = document.getElementById('recipe-detail-view');
        view.classList.remove('translate-x-full', 'opacity-0', 'pointer-events-none');
        view.classList.add('translate-x-0', 'opacity-100', 'pointer-events-auto');
    };

    window.closeRecipeDetail = () => {
        window.closeMealPlanEditor?.();
        const view = document.getElementById('recipe-detail-view');
        view.classList.remove('translate-x-0', 'opacity-100', 'pointer-events-auto');
        view.classList.add('translate-x-full', 'opacity-0', 'pointer-events-none');
    };
}
