import { ref, set, push, remove } from "https://www.gstatic.com/firebasejs/11.9.0/firebase-database.js";

// Module-level variables to store dependencies from dashboard.js
let db;
let CURRENT_CLIENT_ID;
let showToast;
let updateImagePreview;
let allCategories = {};
let allProducts = {};

function normalizeSubcategoryHex(v, fallback) {
    const t = String(v || '').trim();
    if (/^#[0-9A-Fa-f]{6}$/i.test(t)) return t;
    if (/^#[0-9A-Fa-f]{3}$/i.test(t)) return t;
    return fallback;
}

function subcategoryRowMarkup(name, bgColor = '#ffffff', textColor = '#000000') {
    const esc = (s) => String(s).replace(/"/g, '&quot;').replace(/</g, '&lt;');
    const bg = normalizeSubcategoryHex(bgColor, '#ffffff');
    const tx = normalizeSubcategoryHex(textColor, '#000000');
    return `<div class="subcategory-row flex flex-wrap items-center gap-2">
        <input type="text" class="admin-form-input subcategory-name-input flex-1 min-w-[120px]" value="${esc(name)}">
        <input type="color" class="subcategory-bg-color w-9 h-9 p-0 border border-gray-200 rounded cursor-pointer shrink-0" value="${bg}" title="Background">
        <input type="color" class="subcategory-text-color w-9 h-9 p-0 border border-gray-200 rounded cursor-pointer shrink-0" value="${tx}" title="Text">
        <button type="button" class="remove-subcategory-btn text-red-600 hover:text-red-800 px-2 py-1 text-sm border border-red-200 rounded shrink-0">Remove</button>
    </div>`;
}

function normalizeSubcategories(subcategories) {
    if (subcategories == null) return {};
    const out = {};
    const row = (val, id) => {
        const name = (val && typeof val.name === 'string') ? val.name.trim() : '';
        if (!name) return;
        const rec = { name };
        const bg = val && val.bgColor ? String(val.bgColor).trim() : '';
        const tx = val && val.textColor ? String(val.textColor).trim() : '';
        if (bg) rec.bgColor = bg;
        if (tx) rec.textColor = tx;
        out[id] = rec;
    };
    if (Array.isArray(subcategories)) {
        subcategories.forEach((item, i) => {
            if (typeof item === 'string') {
                const name = item.trim();
                if (name) out[`sub_arr_${i}_${name.slice(0, 20)}`] = { name };
                return;
            }
            if (item && typeof item === 'object' && typeof item.name === 'string') {
                row(item, `sub_arr_${i}_${String(item.name).trim().slice(0, 20)}`);
            }
        });
        return out;
    }
    if (typeof subcategories !== 'object') return {};
    Object.entries(subcategories).forEach(([id, val]) => row(val, id));
    return out;
}

function readSubcategoriesFromDOM() {
    const rows = Array.from(document.querySelectorAll('#subcategory-list .subcategory-row'));
    const data = {};
    rows.forEach((row, i) => {
        const name = row.querySelector('.subcategory-name-input')?.value.trim();
        if (!name) return;
        const bg = normalizeSubcategoryHex(row.querySelector('.subcategory-bg-color')?.value, '#ffffff');
        const tx = normalizeSubcategoryHex(row.querySelector('.subcategory-text-color')?.value, '#000000');
        data[`sub_${Date.now()}_${i}`] = { name, bgColor: bg, textColor: tx };
    });
    return data;
}

// === CATEGORY MANAGEMENT LOGIC ===

function renderCategories(categoriesData) {
    allCategories = categoriesData; // Keep a local copy
    const container = document.getElementById('category-list-container');
    if (!container) return;

    if (!categoriesData || Object.keys(categoriesData).length === 0) {
        container.innerHTML = '<p class="text-center text-gray-500 p-4">No categories found. Add one now.</p>';
        return;
    }

    const table = document.createElement('table');
    table.className = "min-w-full divide-y divide-gray-200";
    table.innerHTML = `
        <thead class="bg-gray-50">
            <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Category</th>
                <th scope="col" class="relative px-6 py-3"><span class="sr-only">Actions</span></th>
            </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
            ${Object.entries(categoriesData).map(([id, cat]) => `
                <tr>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 h-10 w-10">
                                <img class="h-10 w-10 rounded-lg object-cover" src="${cat.imageUrl}" alt="${cat.name}">
                            </div>
                            <div class="ml-4">
                                <div class="text-sm font-medium text-gray-900">${cat.name}</div>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button data-action="editCategory" data-id="${id}" class="text-indigo-600 hover:text-indigo-900">Edit</button>
                        <button data-action="deleteCategory" data-id="${id}" class="text-red-600 hover:text-red-900 ml-4">Delete</button>
                    </td>
                </tr>
            `).join('')}
        </tbody>
    `;
    container.innerHTML = '';
    container.appendChild(table);
}

function resetCategoryForm() {
    const form = document.getElementById('category-form');
    form.reset();
    document.getElementById('category-id').value = '';
    const desc = document.getElementById('category-description');
    if (desc) desc.value = '';
    document.getElementById('category-form-title').textContent = 'Add New Category';
    document.querySelector('#save-category-btn .button-text').textContent = 'Save Category';
    document.getElementById('category-cancel-btn').classList.add('hidden');
    document.getElementById('category-image-preview').innerHTML = '';
    const lbPrev = document.getElementById('category-listing-banner-preview');
    if (lbPrev) lbPrev.innerHTML = '';
    const lbUrl = document.getElementById('category-listing-banner-url');
    if (lbUrl) lbUrl.value = '';
    const lbEn = document.getElementById('category-listing-banner-enabled');
    if (lbEn) lbEn.checked = true;
}

async function handleCategorySubmit(e) {
    e.preventDefault();
    const saveBtn = e.target.querySelector('button[type="submit"]');
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';

    try {
        const categoryId = document.getElementById('category-id').value;
        const lbUrlEl = document.getElementById('category-listing-banner-url');
        const lbEnEl = document.getElementById('category-listing-banner-enabled');
        const data = {
            name: document.getElementById('category-name').value.trim(),
            imageUrl: document.getElementById('category-image-url').value.trim(),
            description: (document.getElementById('category-description')?.value || '').trim(),
            subcategories: readSubcategoriesFromDOM(),
            listingBannerUrl: lbUrlEl ? lbUrlEl.value.trim() : '',
            listingBannerEnabled: !(lbEnEl && lbEnEl.checked === false)
        };

        if (!data.name || !data.imageUrl) {
            showToast("Category Name and Image URL are required.", false);
            return;
        }

        const path = `clients/${CURRENT_CLIENT_ID}/categories/${categoryId || push(ref(db, `clients/${CURRENT_CLIENT_ID}/categories`)).key}`;
        await set(ref(db, path), data);
        
        showToast(`Category ${categoryId ? 'updated' : 'added'} successfully!`);
        resetCategoryForm();
    } catch (error) {
        console.error("Error saving category:", error);
        showToast("An error occurred while saving the category.", false);
    } finally {
        saveBtn.disabled = false;
        saveBtn.innerHTML = '<i class="fa-solid fa-save"></i><span class="button-text">Save Category</span>';
    }
}


// === PRODUCTS MANAGEMENT LOGIC ===

function renderProducts(productsData) {
    allProducts = productsData; // Keep a local copy
    const container = document.getElementById('product-list-container');
    if (!container) return;

    if (!productsData || Object.keys(productsData).length === 0) {
        container.innerHTML = '<p class="text-center text-gray-500 p-4">No products found. Add one using the form.</p>';
        return;
    }
    
    const table = document.createElement('table');
    table.className = "min-w-full divide-y divide-gray-200";
    table.innerHTML = `
        <thead class="bg-gray-50">
            <tr>
                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Product</th>
                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Price</th>
                <th class="px-6 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Stock</th>
                <th class="relative px-6 py-3"><span class="sr-only">Actions</span></th>
            </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
            ${Object.entries(productsData).sort(([, a], [, b]) => (b.createdAt || 0) - (a.createdAt || 0)).map(([id, p]) => {
                let priceHtml = `${p.salePrice}৳`;
                if (p.hasVariants) {
                    const prices = Object.values(p.variants || {}).map(v => v.salePrice);
                    priceHtml = prices.length > 0 ? `${Math.min(...prices)}৳+` : 'N/A';
                } else if (p.regularPrice > 0) {
                    priceHtml = `<del class='text-red-400'>${p.regularPrice}৳</del> ${p.salePrice}৳`;
                }

                let stock = p.stock;
                if (p.hasVariants && p.variants) {
                    stock = Object.values(p.variants).reduce((total, variant) => total + (Number(variant.stock) || 0), 0);
                }

                const isUnlimited = stock === null || stock === undefined;
                const stockStatus = isUnlimited ? 'bg-blue-100 text-blue-800' : stock > 10 ? 'bg-green-100 text-green-800' : stock > 0 ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800';
                const stockText = isUnlimited ? 'Unlimited' : `${stock} units`;
                
                return `
                <tr>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 h-10 w-10"><img class="h-10 w-10 rounded-lg object-cover" src="${p.imageUrl}" alt="${p.name}"></div>
                            <div class="ml-4">
                                <div class="text-sm font-medium text-gray-900">${p.name}</div>
                                <div class="text-xs text-gray-500">${p.category}</div>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700">${priceHtml}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm"><span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${stockStatus}">${stockText}</span></td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button data-action="editProduct" data-id="${id}" class="text-indigo-600 hover:text-indigo-900">Edit</button>
                        <button data-action="deleteProduct" data-id="${id}" class="text-red-600 hover:text-red-900 ml-4">Delete</button>
                    </td>
                </tr>
            `}).join('')}
        </tbody>
    `;
    container.innerHTML = '';
    container.appendChild(table);
    const editingId = document.getElementById('product-id')?.value || null;
    const selectedUpsell = (editingId && allProducts[editingId] && Array.isArray(allProducts[editingId].upsellProductIds))
        ? allProducts[editingId].upsellProductIds
        : [];
    populateUpsellCheckboxes(editingId, selectedUpsell);
}

function escapeHtmlAdmin(s) {
    if (s == null) return '';
    return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

function addVariantRow(variant = { name: '', regularPrice: '', salePrice: '', stock: '' }) {
    const list = document.getElementById('product-variants-list');
    if (!list) return;

    const div = document.createElement('div');
    div.className = 'p-2 bg-gray-50 rounded-lg border grid grid-cols-12 gap-2 items-center variant-row';
    div.innerHTML = `
        <div class="col-span-5"><input type="text" placeholder="e.g., Red, L" class="admin-form-input variant-name !py-2" value="${variant.name || ''}" required></div>
        <div class="col-span-2"><input type="number" placeholder="Reg. ৳" class="admin-form-input variant-regular-price !py-2 text-center" value="${variant.regularPrice || ''}"></div>
        <div class="col-span-2"><input type="number" placeholder="Sale ৳" class="admin-form-input variant-sale-price !py-2 text-center" value="${variant.salePrice || ''}" required></div>
        <div class="col-span-2"><input type="number" placeholder="Stock" class="admin-form-input variant-stock !py-2 text-center" value="${variant.stock || ''}"></div>
        <button type="button" class="remove-variant-btn text-red-500 hover:text-red-700 p-2 rounded-full hover:bg-red-100 col-span-1 text-center"><i class="fa-solid fa-trash-can"></i></button>
    `;
    list.appendChild(div);
    div.querySelector('.remove-variant-btn').addEventListener('click', () => div.remove());
}

function populateUpsellCheckboxes(excludeProductId = null, selectedIds = null) {
    const wrap = document.getElementById('product-upsell-checkboxes');
    if (!wrap) return;
    const selected = selectedIds instanceof Set ? selectedIds : new Set(Array.isArray(selectedIds) ? selectedIds.map(String) : []);
    const entries = Object.entries(allProducts || {})
        .filter(([id]) => String(id) !== String(excludeProductId))
        .sort((a, b) => String(a[1].name || '').localeCompare(String(b[1].name || ''), undefined, { sensitivity: 'base' }));
    if (!entries.length) {
        wrap.innerHTML = '<p class="text-xs text-gray-500 p-2">No other products yet. Add more products to link them here.</p>';
        return;
    }
    wrap.innerHTML = entries.map(([id, p]) => {
        const name = escapeHtmlAdmin(p.name || 'Product');
        const img = escapeHtmlAdmin(p.imageUrl || '');
        const checked = selected.has(String(id)) ? ' checked' : '';
        return `<label class="flex items-center gap-3 p-2 rounded-lg hover:bg-white cursor-pointer border border-transparent hover:border-gray-200">
            <input type="checkbox" name="product-upsell" value="${escapeHtmlAdmin(id)}" class="product-upsell-cb h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"${checked}>
            <img src="${img}" alt="" class="w-9 h-9 object-contain rounded border bg-white flex-shrink-0" loading="lazy">
            <span class="text-sm text-gray-800 truncate flex-1 min-w-0">${name}</span>
        </label>`;
    }).join('');
}

function resetProductForm() {
    document.getElementById('product-form').reset();
    document.getElementById('product-id').value = '';
    document.getElementById('product-form-title').textContent = 'Add a new product';
    document.querySelector('#save-product-btn .button-text').textContent = 'Save Product';
    const bd = document.getElementById('product-bundle-discount');
    if (bd) bd.value = '0';
    populateUpsellCheckboxes(null, []);
    
    document.getElementById('product-variants-list').innerHTML = '';
    const hasVariantsCheckbox = document.getElementById('product-has-variants');
    hasVariantsCheckbox.checked = false;
    hasVariantsCheckbox.dispatchEvent(new Event('change'));

    document.getElementById('product-image-preview').innerHTML = '';
    const subSelect = document.getElementById('product-subcategory');
    if (subSelect) subSelect.innerHTML = '<option value="">Select a sub category...</option>';
    document.getElementById('product-cancel-btn').classList.add('hidden');
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

async function handleProductSubmit(e) {
    e.preventDefault();
    const saveBtn = document.getElementById('save-product-btn');
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<div class="spinner spinner-white mx-auto"></div><span class="button-text hidden">Saving...</span>';

    try {
        const productId = document.getElementById('product-id').value;
        const hasVariants = document.getElementById('product-has-variants').checked;
        
        const categoriesContainer = document.getElementById('product-categories-container');
        const categories = categoriesContainer
            ? Array.from(categoriesContainer.querySelectorAll('input[name="product-categories"]:checked')).map(c => c.value)
            : (document.getElementById('product-category')?.value ? [document.getElementById('product-category').value] : []);
        const subcategorySelect = document.getElementById('product-subcategory');
        const selectedSubOption = subcategorySelect ? subcategorySelect.options[subcategorySelect.selectedIndex] : null;
        let data = {
            name: document.getElementById('product-name').value.trim(),
            categories: categories,
            category: categories[0] || '',
            subcategory: selectedSubOption?.dataset?.subName || '',
            subcategoryParent: selectedSubOption?.dataset?.parentName || '',
            subcategoryKey: selectedSubOption?.value || '',
            imageUrl: document.getElementById('product-image-url').value.trim(),
            description: document.getElementById('product-description').value,
            hasVariants: hasVariants
        };

        // --- RIGOROUS VALIDATION ---
        if (!data.name || !data.imageUrl) {
            showToast("Product Name and Image URL are required.", false);
            return;
        }
        if (!data.categories.length) {
            showToast("Please select at least one category.", false);
            return;
        }
        if (data.subcategory && !data.subcategoryParent) {
            showToast("Invalid subcategory mapping. Please reselect.", false);
            return;
        }
        if (data.subcategoryParent && !data.categories.includes(data.subcategoryParent)) {
            showToast("Selected subcategory does not match selected categories.", false);
            return;
        }
        // --- END OF VALIDATION ---

        if (hasVariants) {
            const variantRows = document.querySelectorAll('#product-variants-list .variant-row');
            if (variantRows.length === 0) {
                showToast("Please add at least one variant.", false); return;
            }
            data.variants = {};
            let allVariantsValid = true;
            variantRows.forEach(row => {
                const name = row.querySelector('.variant-name').value.trim();
                const salePrice = parseFloat(row.querySelector('.variant-sale-price').value);
                if (!name || isNaN(salePrice) || salePrice <= 0) { allVariantsValid = false; return; }
                
                const variantKey = push(ref(db)).key;
                data.variants[variantKey] = { 
                    name: name, 
                    regularPrice: parseFloat(row.querySelector('.variant-regular-price').value) || 0, 
                    salePrice: salePrice,
                    stock: row.querySelector('.variant-stock').value === '' ? null : parseInt(row.querySelector('.variant-stock').value, 10)
                };
            });
            if (!allVariantsValid) { showToast("Each variant must have a name and a valid sale price.", false); return; }
            data.stock = null; // Main stock is irrelevant
            data.salePrice = Math.min(...Object.values(data.variants).map(v => v.salePrice)); // Store lowest price for sorting
        } else {
            const salePrice = parseFloat(document.getElementById('product-sale-price').value);
            if (isNaN(salePrice) || salePrice <= 0) {
                showToast("Sale Price is required and must be greater than 0.", false); return;
            }
            data.regularPrice = parseFloat(document.getElementById('product-regular-price').value) || 0;
            data.salePrice = salePrice;
            data.stock = document.getElementById('product-stock').value === '' ? null : parseInt(document.getElementById('product-stock').value, 10);
        }

        if (data.hasVariants && (!data.variants || Object.keys(data.variants).length === 0)) {
            showToast('Variant products must include at least one valid variant.', false);
            return;
        }

        const upsellWrap = document.getElementById('product-upsell-checkboxes');
        const upsellProductIds = upsellWrap
            ? [...new Set(Array.from(upsellWrap.querySelectorAll('input[name="product-upsell"]:checked')).map((cb) => cb.value).filter(Boolean))]
            : [];
        data.upsellProductIds = upsellProductIds;
        const bdp = document.getElementById('product-bundle-discount');
        data.bundleDiscountPercent = bdp ? Math.min(50, Math.max(0, parseInt(bdp.value, 10) || 0)) : 0;

        const existingCreatedAt = productId ? (allProducts[productId]?.createdAt || null) : null;
        data.createdAt = existingCreatedAt || Date.now();
        const path = `clients/${CURRENT_CLIENT_ID}/products/${productId || push(ref(db, `clients/${CURRENT_CLIENT_ID}/products`)).key}`;
        await set(ref(db, path), data);

        showToast(`Product ${productId ? 'updated' : 'added'} successfully!`);
        resetProductForm();
    } catch (error) {
        console.error("Error saving product:", error);
        showToast("An error occurred while saving the product.", false);
    } finally {
        saveBtn.disabled = false;
        saveBtn.innerHTML = '<i class="fa-solid fa-save"></i><span class="button-text">Save Product</span>';
    }
}

function populateCategoryDropdown(categoriesData) {
    const container = document.getElementById('product-categories-container');
    const categorySelect = document.getElementById('product-category');
    const noCategoryAlert = document.getElementById('no-category-alert');
    const hasCategories = categoriesData && Object.keys(categoriesData).length > 0;
    if (noCategoryAlert) noCategoryAlert.classList.toggle('hidden', hasCategories);

    if (container) {
        container.innerHTML = '';
        if (hasCategories) {
            Object.values(categoriesData).forEach(cat => {
                const label = document.createElement('label');
                label.className = 'flex items-center gap-2 cursor-pointer text-sm text-gray-700';
                const cb = document.createElement('input');
                cb.type = 'checkbox';
                cb.name = 'product-categories';
                cb.value = cat.name;
                label.appendChild(cb);
                label.appendChild(document.createTextNode(cat.name));
                container.appendChild(label);
            });
            const subSelect = document.getElementById('product-subcategory');
            if (subSelect) {
                const checked = Array.from(container.querySelectorAll('input[name="product-categories"]:checked')).map((cb) => cb.value);
                const entries = [];
                Object.values(categoriesData).forEach((cat) => {
                    if (!checked.includes(cat.name)) return;
                    Object.values(cat.subcategories || {}).forEach((sub) => {
                        const subName = sub?.name ? String(sub.name).trim() : '';
                        if (!subName) return;
                        entries.push({ key: `${cat.name}|||${subName}`, parent: cat.name, name: subName });
                    });
                });
                const uniq = new Map();
                entries.forEach((entry) => { if (!uniq.has(entry.key)) uniq.set(entry.key, entry); });
                subSelect.innerHTML = '<option value="">Select a sub category...</option>' + Array.from(uniq.values()).map((entry) => `<option value="${entry.key}" data-parent-name="${entry.parent}" data-sub-name="${entry.name}">${entry.parent} > ${entry.name}</option>`).join('');
            }
        } else {
            container.innerHTML = '<p class="text-sm text-gray-500">Please add a category first.</p>';
        }
        return;
    }
    if (!categorySelect) return;
    const currentValue = categorySelect.value;
    categorySelect.innerHTML = '';
    if (hasCategories) {
        categorySelect.innerHTML = '<option value="" disabled selected>Select a category...</option>';
        Object.values(categoriesData).forEach(cat => {
            const option = document.createElement('option');
            option.value = cat.name;
            option.textContent = cat.name;
            categorySelect.appendChild(option);
        });
        if (currentValue && Object.values(categoriesData).some(c => c.name === currentValue)) {
            categorySelect.value = currentValue;
        }
    } else {
        categorySelect.innerHTML = '<option value="">Please add a category first</option>';
    }
}


// === EVENT LISTENERS SETUP ===

function setupProductEventListeners() {
    // --- Form Submissions ---
    document.getElementById('product-form')?.addEventListener('submit', handleProductSubmit);
    document.getElementById('category-form')?.addEventListener('submit', handleCategorySubmit);
    
    // --- Cancel Buttons ---
    document.getElementById('category-cancel-btn')?.addEventListener('click', resetCategoryForm);
    document.getElementById('product-cancel-btn')?.addEventListener('click', resetProductForm);
    document.getElementById('add-subcategory-btn')?.addEventListener('click', () => {
        const input = document.getElementById('subcategory-name-input');
        const list = document.getElementById('subcategory-list');
        if (!input || !list) return;
        const name = input.value.trim();
        if (!name) return;
        const empty = list.querySelector('p');
        if (empty) list.innerHTML = '';
        const row = document.createElement('div');
        row.className = 'subcategory-row flex flex-wrap items-center gap-2';
        row.innerHTML = `
            <input type="text" class="admin-form-input subcategory-name-input flex-1 min-w-[120px]" value="${String(name).replace(/"/g, '&quot;').replace(/</g, '&lt;')}">
            <input type="color" class="subcategory-bg-color w-9 h-9 p-0 border border-gray-200 rounded cursor-pointer shrink-0" value="#ffffff" title="Background">
            <input type="color" class="subcategory-text-color w-9 h-9 p-0 border border-gray-200 rounded cursor-pointer shrink-0" value="#000000" title="Text">
            <button type="button" class="remove-subcategory-btn text-red-600 hover:text-red-800 px-2 py-1 text-sm border border-red-200 rounded shrink-0">Remove</button>
        `;
        list.appendChild(row);
        row.querySelector('.remove-subcategory-btn')?.addEventListener('click', () => row.remove());
        input.value = '';
    });

    // --- Product Form Specific Listeners ---
    document.getElementById('add-variant-btn')?.addEventListener('click', () => addVariantRow());
    document.getElementById('product-has-variants')?.addEventListener('change', (e) => {
        const isChecked = e.target.checked;
        document.getElementById('product-non-variant-options').classList.toggle('hidden', isChecked);
        document.getElementById('product-variant-options').classList.toggle('hidden', !isChecked);
        document.getElementById('product-sale-price').required = !isChecked;
    });
    document.addEventListener('change', (e) => {
        if (e.target?.name !== 'product-categories') return;
        const subSelect = document.getElementById('product-subcategory');
        const container = document.getElementById('product-categories-container');
        if (!subSelect || !container) return;
        const checked = Array.from(container.querySelectorAll('input[name="product-categories"]:checked')).map((cb) => cb.value);
        const entries = [];
        Object.values(allCategories || {}).forEach((cat) => {
            if (!checked.includes(cat.name)) return;
            Object.values(cat.subcategories || {}).forEach((sub) => {
                const subName = sub?.name ? String(sub.name).trim() : '';
                if (!subName) return;
                entries.push({ key: `${cat.name}|||${subName}`, parent: cat.name, name: subName });
            });
        });
        const uniq = new Map();
        entries.forEach((entry) => { if (!uniq.has(entry.key)) uniq.set(entry.key, entry); });
        subSelect.innerHTML = '<option value="">Select a sub category...</option>' + Array.from(uniq.values()).map((entry) => `<option value="${entry.key}" data-parent-name="${entry.parent}" data-sub-name="${entry.name}">${entry.parent} > ${entry.name}</option>`).join('');
    });

    // --- Delegated Event Listener for Edit/Delete actions ---
    document.addEventListener('click', (e) => {
        const target = e.target.closest('button[data-action]');
        if (!target) return;
        
        const { action, id } = target.dataset;

        // Category Actions
        if (action === 'editCategory') {
            const data = allCategories[id];
            if (data) {
                document.getElementById('category-id').value = id;
                document.getElementById('category-name').value = data.name;
                document.getElementById('category-image-url').value = data.imageUrl;
                const descEl = document.getElementById('category-description');
                if (descEl) descEl.value = (data.description != null) ? String(data.description) : '';
                const lbEn = document.getElementById('category-listing-banner-enabled');
                if (lbEn) lbEn.checked = data.listingBannerEnabled !== false;
                const lbUrl = document.getElementById('category-listing-banner-url');
                if (lbUrl) lbUrl.value = (data.listingBannerUrl != null && String(data.listingBannerUrl).trim()) ? String(data.listingBannerUrl).trim() : '';
                const subWrap = document.getElementById('subcategory-list');
                if (subWrap) {
                    const entries = Object.values(normalizeSubcategories(data.subcategories));
                    subWrap.innerHTML = entries.length
                        ? entries.map((s) => subcategoryRowMarkup(s.name, s.bgColor || '#ffffff', s.textColor || '#000000')).join('')
                        : '<p class="text-xs text-gray-500">No subcategory added yet.</p>';
                    subWrap.querySelectorAll('.remove-subcategory-btn').forEach((btn) => {
                        btn.addEventListener('click', () => {
                            btn.closest('.subcategory-row')?.remove();
                            if (!subWrap.querySelector('.subcategory-row')) {
                                subWrap.innerHTML = '<p class="text-xs text-gray-500">No subcategory added yet.</p>';
                            }
                        });
                    });
                }
                updateImagePreview('#category-image-url', '#category-image-preview');
                updateImagePreview('#category-listing-banner-url', '#category-listing-banner-preview');
                document.getElementById('category-form-title').textContent = 'Edit Category';
                document.querySelector('#save-category-btn .button-text').textContent = 'Update Category';
                document.getElementById('category-cancel-btn').classList.remove('hidden');
            }
        }
        if (action === 'deleteCategory') {
            if (confirm(`Are you sure you want to delete this category? This cannot be undone.`)) {
                remove(ref(db, `clients/${CURRENT_CLIENT_ID}/categories/${id}`))
                    .then(() => showToast('Category deleted.'))
                    .catch((err) => showToast('Failed to delete category.', false));
            }
        }

        // Product Actions
        if (action === 'editProduct') {
            const data = allProducts[id];
            if (data) {
                resetProductForm();
                document.getElementById('product-id').value = id;
                document.getElementById('product-name').value = data.name;
                const cats = data.categories || (data.category ? [data.category] : []);
                const catContainer = document.getElementById('product-categories-container');
                if (catContainer) {
                    catContainer.querySelectorAll('input[name="product-categories"]').forEach(cb => { cb.checked = cats.includes(cb.value); });
                    const subSelect = document.getElementById('product-subcategory');
                    if (subSelect) {
                        const entries = [];
                        Object.values(allCategories || {}).forEach((cat) => {
                            if (!cats.includes(cat.name)) return;
                            Object.values(cat.subcategories || {}).forEach((sub) => {
                                const subName = sub?.name ? String(sub.name).trim() : '';
                                if (!subName) return;
                                entries.push({ key: `${cat.name}|||${subName}`, parent: cat.name, name: subName });
                            });
                        });
                        const uniq = new Map();
                        entries.forEach((entry) => { if (!uniq.has(entry.key)) uniq.set(entry.key, entry); });
                        subSelect.innerHTML = '<option value="">Select a sub category...</option>' + Array.from(uniq.values()).map((entry) => `<option value="${entry.key}" data-parent-name="${entry.parent}" data-sub-name="${entry.name}">${entry.parent} > ${entry.name}</option>`).join('');
                        const currentSubValue = data.subcategoryKey || ((data.subcategoryParent && data.subcategory) ? `${data.subcategoryParent}|||${data.subcategory}` : '');
                        if (currentSubValue) subSelect.value = currentSubValue;
                    }
                } else {
                    const sel = document.getElementById('product-category');
                    if (sel) sel.value = data.category || (data.categories && data.categories[0]) || '';
                }
                document.getElementById('product-image-url').value = data.imageUrl;
                document.getElementById('product-description').value = data.description || '';
                updateImagePreview('#product-image-url', '#product-image-preview');
                
                const hasVariantsCheckbox = document.getElementById('product-has-variants');
                hasVariantsCheckbox.checked = data.hasVariants;
                hasVariantsCheckbox.dispatchEvent(new Event('change'));

                if (data.hasVariants && data.variants) {
                    Object.values(data.variants).forEach(v => addVariantRow(v));
                } else {
                    document.getElementById('product-regular-price').value = data.regularPrice || '';
                    document.getElementById('product-sale-price').value = data.salePrice || '';
                    document.getElementById('product-stock').value = data.stock ?? '';
                }

                document.getElementById('product-form-title').textContent = `Editing: ${data.name}`;
                document.querySelector('#save-product-btn .button-text').textContent = 'Update Product';
                document.getElementById('product-cancel-btn').classList.remove('hidden');
                const ups = Array.isArray(data.upsellProductIds) ? data.upsellProductIds : [];
                populateUpsellCheckboxes(id, ups);
                const bdp = document.getElementById('product-bundle-discount');
                if (bdp) bdp.value = (data.bundleDiscountPercent != null) ? String(Math.min(50, Math.max(0, Number(data.bundleDiscountPercent) || 0))) : '0';
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        }
        if (action === 'deleteProduct') {
             if (confirm(`Are you sure you want to delete "${allProducts[id]?.name}"? This is permanent.`)) {
                remove(ref(db, `clients/${CURRENT_CLIENT_ID}/products/${id}`))
                    .then(() => showToast('Product deleted.'))
                    .catch((err) => showToast('Failed to delete product.', false));
            }
        }
    });
}


// === INITIALIZATION FUNCTION ===
// This function is called by dashboard.js to pass its dependencies.
function initializeProductManager(dbRef, clientId, showToastFunc, updateImagePreviewFunc) {
    db = dbRef;
    CURRENT_CLIENT_ID = clientId;
    showToast = showToastFunc;
    updateImagePreview = updateImagePreviewFunc;
    
    // Now that dependencies are set, setup the event listeners.
    setupProductEventListeners();
}

export { initializeProductManager, renderProducts, renderCategories, populateCategoryDropdown };