import { RECIPES, INGREDIENTS } from '../data/catalog.js';
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]));

export function getRecipeDetailHTML() {
    return `
    <div id="recipe-detail-view" class="absolute inset-0 bg-white z-30 transition-all duration-300 ease-in-out translate-x-full opacity-0 pointer-events-none flex flex-col overflow-hidden">
        <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 bg-white/90 backdrop-blur rounded-full flex items-center justify-center shadow-sm text-gray-800 hover:bg-white transition-colors">
                <i class="fas fa-arrow-left text-[13px]"></i>
            </button>
            <button id="rd-add-to-planner-btn" class="h-9 px-3 bg-white/90 backdrop-blur rounded-full flex items-center justify-center gap-1.5 shadow-sm text-gray-800 hover:bg-white transition-colors text-[12px] font-semibold">
                <i class="fas fa-calendar-plus text-[11px]"></i> Zaplanuj
            </button>
        </div>

        <div id="rd-hero" class="h-[220px] shrink-0 w-full bg-[#d4d4d4] relative overflow-hidden">
            <img id="rd-hero-img" src="" alt="" class="w-full h-full object-cover hidden">
            <span id="rd-hero-label" class="absolute inset-0 flex items-center justify-center text-white font-medium text-[15px]"></span>
        </div>

        <div class="bg-white rounded-t-3xl -mt-6 relative z-30 pt-6 flex flex-col flex-1 overflow-hidden">
            <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 text-gray-900"></h1>
                </div>
                <div id="rd-tags" class="flex flex-wrap gap-1.5 mb-3"></div>
                <div class="flex justify-between items-center text-[13px] text-gray-600 font-medium">
                    <div class="flex gap-3.5">
                        <div class="flex items-center gap-1.5"><i class="fas fa-clock text-gray-400 text-xs"></i><span id="rd-time"></span></div>
                    </div>
                    <div class="flex items-center gap-0.5 bg-gray-100 p-0.5 rounded-lg">
                        <button id="rd-serv-minus" class="w-6 h-6 bg-white rounded-md shadow-sm flex items-center justify-center text-gray-600 hover:text-black hover:bg-gray-50"><i class="fas fa-minus text-[9px]"></i></button>
                        <div class="flex items-center gap-1 px-1.5">
                            <span id="rd-servings" class="font-bold text-gray-900 text-[13px] w-3 text-center tabular-nums">1</span>
                            <span class="text-[11px] text-gray-500"><i class="fas fa-user-friends"></i></span>
                        </div>
                        <button id="rd-serv-plus" class="w-6 h-6 bg-white rounded-md shadow-sm flex items-center justify-center text-gray-600 hover:text-black hover:bg-gray-50"><i class="fas fa-plus text-[9px]"></i></button>
                    </div>
                </div>
            </div>

            <div class="flex border-b border-gray-200 mb-2 px-5 shrink-0">
                <button class="flex-1 pb-2.5 text-[13px] font-semibold text-gray-900 border-b-2 border-gray-900 rd-tab-btn" data-rd-tab="ingredients">Składniki</button>
                <button class="flex-1 pb-2.5 text-[13px] font-medium text-gray-500 border-b-2 border-transparent hover:text-gray-700 rd-tab-btn" data-rd-tab="steps">Kroki</button>
            </div>

            <div class="flex-1 overflow-y-auto px-5 pt-2 pb-10 no-scrollbar relative">
                <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`;
    updateKcalDisplay();

    const tagsHtml = [];
    for (const slotId of recipe.allowedSlots) {
        const label = slotLabelMap[slotId];
        if (label) tagsHtml.push(`<span class="px-2.5 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded-md font-medium">${escapeHtml(label)}</span>`);
    }
    for (const tag of (recipe.tags || [])) {
        tagsHtml.push(`<span class="px-2.5 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded-md font-medium">${escapeHtml(tag)}</span>`);
    }
    document.getElementById('rd-tags').innerHTML = tagsHtml.join('');
    document.getElementById('rd-servings').textContent = '1';

    renderIngredients(recipe);
    renderSteps(recipe);

    const tabBtns = document.querySelectorAll('.rd-tab-btn');
    const tabs = document.querySelectorAll('.rd-tab-content');
    tabBtns.forEach((b) => {
        b.classList.remove('text-gray-900', 'border-gray-900', 'font-semibold');
        b.classList.add('text-gray-500', 'border-transparent', 'font-medium');
    });
    tabBtns[0]?.classList.remove('text-gray-500', 'border-transparent', 'font-medium');
    tabBtns[0]?.classList.add('text-gray-900', 'border-gray-900', 'font-semibold');
    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 updateKcalDisplay() {
    const el = document.getElementById('rd-kcal');
    if (!el) return;
    const recipe = RECIPES[currentRecipeId];
    if (!recipe) return;
    const kcal = Math.round(recipe.nutritionPerServing.kcal * currentServings);
    el.textContent = `${kcal} kcal`;
}

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

/* ── 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 s = currentServings;
    const total = computeEffectiveNutritionTotals(recipe);

    return `
        <div class="mb-4 pt-1 pb-3 border-b border-gray-100">
            ${s > 1 ? `<p class="text-[10px] text-gray-400 font-medium mb-2">Wartości dla ${s} porcji</p>` : ''}
            <div class="grid grid-cols-4 gap-3 text-center">
                <div>
                    <span class="block text-[14px] font-bold text-gray-900 tabular-nums">${total.kcal}</span>
                    <span class="text-[10px] text-gray-500">Kalorie</span>
                </div>
                <div>
                    <span class="block text-[14px] font-bold text-gray-900 tabular-nums">${total.protein} g</span>
                    <span class="text-[10px] text-gray-500">Białko</span>
                </div>
                <div>
                    <span class="block text-[14px] font-bold text-gray-900 tabular-nums">${total.carbs} g</span>
                    <span class="text-[10px] text-gray-500">Węglo.</span>
                </div>
                <div>
                    <span class="block text-[14px] font-bold text-gray-900 tabular-nums">${total.fat} g</span>
                    <span class="text-[10px] text-gray-500">Tłuszcze</span>
                </div>
            </div>
        </div>`;
}

function renderIngredientCard(name, amount, unit, nutrition, extra) {
    const displayAmount = Number.isInteger(amount) ? amount : parseFloat(amount.toFixed(1));
    const macroHtml = nutrition
        ? `<div class="flex flex-wrap gap-x-2.5 text-[10px] text-gray-400 tabular-nums">
            <span>${nutrition.protein}g B</span><span>${nutrition.fat}g T</span><span>${nutrition.carbs}g W</span>
        </div>`
        : '';
    const kcalHtml = nutrition
        ? `<span class="text-[10px] font-medium text-gray-400 tabular-nums whitespace-nowrap">${nutrition.kcal} kcal</span>`
        : '';

    return `
        <div class="${extra?.cls || 'bg-white'} rounded-xl p-2.5 border ${extra?.border || 'border-gray-200'} flex items-center gap-2.5" ${extra?.dataAttrs || ''}>
            <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2">
                    ${extra?.prefix || ''}
                    <span class="text-[12px] font-semibold text-gray-900 truncate">${escapeHtml(name)}</span>
                    ${extra?.suffix || ''}
                </div>
                ${macroHtml}
                ${extra?.badge || ''}
            </div>
            <div class="flex flex-col items-end shrink-0 gap-0.5">
                <span class="text-[12px] font-semibold text-gray-900 tabular-nums whitespace-nowrap">${displayAmount} ${escapeHtml(unit)}</span>
                ${kcalHtml}
            </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 nutrition = nutritionForAmount(effectiveId, scaledAmount, ing.unit);
        const isSwapped = effectiveId !== origId;
        const isExpanded = expandedAlternatives.has(origId);

        const toggleBtn = hasAlts
            ? `<button type="button" class="rd-alt-toggle shrink-0 w-5 h-5 rounded-full ${isExpanded ? 'bg-amber-50 text-amber-500' : isSwapped ? 'bg-amber-50 text-amber-500' : 'bg-gray-100 text-gray-400 hover:bg-gray-200'} flex items-center justify-center transition-colors" data-original-id="${escapeHtml(origId)}"><i class="fas fa-shuffle text-[8px]"></i></button>`
            : '';

        const cardBorder = isSwapped ? 'border-amber-200' : 'border-gray-200';
        const cardCls = isSwapped ? 'bg-amber-50/30' : 'bg-white';
        const cardHtml = renderIngredientCard(effectiveName, scaledAmount, ing.unit, nutrition, {
            suffix: toggleBtn,
            border: cardBorder,
            cls: cardCls,
        });

        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 isOriginal = altId === origId;
                const altNutrition = nutritionForAmount(altId, scaledAmount, ing.unit);

                const radioDot = `<div class="w-3.5 h-3.5 rounded-full border-2 shrink-0 ${isSelected ? 'border-gray-900' : 'border-gray-300'} flex items-center justify-center">${isSelected ? '<div class="w-1.5 h-1.5 rounded-full bg-gray-900"></div>' : ''}</div>`;
                const defaultTag = isOriginal ? `<span class="text-[9px] px-1.5 py-0.5 rounded ${isSelected ? 'bg-gray-200 text-gray-600' : 'bg-gray-100 text-gray-400'} font-medium ml-1">Domyślny</span>` : '';

                return renderIngredientCard(altName, scaledAmount, ing.unit, altNutrition, {
                    cls: isSelected ? 'bg-gray-50' : 'bg-white hover:bg-gray-50 cursor-pointer',
                    border: isSelected ? 'border-gray-900 ring-1 ring-gray-900' : 'border-gray-100',
                    prefix: radioDot,
                    badge: defaultTag,
                    dataAttrs: `data-original-id="${escapeHtml(origId)}" data-alt-id="${escapeHtml(altId)}"`,
                });
            });
            altListHtml = `
            <div class="mt-1.5 space-y-1.5 rd-alt-options" data-original-id="${escapeHtml(origId)}">
                ${optionCards.join('')}
            </div>`;
        }

        return `<li>${cardHtml}${altListHtml}</li>`;
    }).join('');

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

    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-gray-500 text-center py-8">Brak kroków przygotowania.</p>';
        return;
    }

    container.innerHTML = `
        <div class="space-y-5 pb-5">
            ${steps.map((step, i) => `
            <div class="flex gap-3">
                <div class="w-6 h-6 rounded-full bg-gray-900 text-white flex items-center justify-center text-[11px] font-bold shrink-0 shadow-sm">${i + 1}</div>
                <div class="pt-0.5"><p class="text-[13px] text-gray-600 leading-relaxed">${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) => {
                b.classList.remove('text-gray-900', 'border-gray-900', 'font-semibold');
                b.classList.add('text-gray-500', 'border-transparent', 'font-medium');
            });
            btn.classList.remove('text-gray-500', 'border-transparent', 'font-medium');
            btn.classList.add('text-gray-900', 'border-gray-900', 'font-semibold');
        });
    });

    document.getElementById('rd-serv-minus')?.addEventListener('click', () => {
        if (currentServings <= 1) return;
        currentServings--;
        document.getElementById('rd-servings').textContent = currentServings;
        const recipe = RECIPES[currentRecipeId];
        if (recipe) {
            renderIngredients(recipe);
            updateKcalDisplay();
        }
    });

    document.getElementById('rd-serv-plus')?.addEventListener('click', () => {
        if (currentServings >= 12) return;
        currentServings++;
        document.getElementById('rd-servings').textContent = currentServings;
        const recipe = RECIPES[currentRecipeId];
        if (recipe) {
            renderIngredients(recipe);
            updateKcalDisplay();
        }
    });

    /* ── 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');
    };
}
