function showProductForm() { document.getElementById('product-form-area').style.display = 'block'; }
function hideProductForm() { document.getElementById('product-form-area').style.display = 'none'; }
function toggleQualities() { document.getElementById('pf-qualities-area').style.display = document.getElementById('pf-has-qualities').checked ? 'block' : 'none'; }
function toggleTypes() { document.getElementById('pf-types-area').style.display = document.getElementById('pf-has-types').checked ? 'block' : 'none'; }

function addQualityInput() {
    var container = document.getElementById('pf-quality-inputs');
    var row = document.createElement('div'); row.className = 'dynamic-input-row';
    row.innerHTML = '<input type="text" class="admin-input" placeholder="Quality name"><button class="remove-input-btn" onclick="removeInput(this)">-</button>';
    container.appendChild(row);
}
function addTypeInput() {
    var container = document.getElementById('pf-type-inputs');
    var row = document.createElement('div'); row.className = 'dynamic-input-row';
    row.innerHTML = '<input type="text" class="admin-input" placeholder="Type name"><button class="remove-input-btn" onclick="removeInput(this)">-</button>';
    container.appendChild(row);
}
function removeInput(btn) { btn.parentElement.remove(); }

function generateVariants() {
    var qualities = [];
    var types = [];
    var unitLabel = document.getElementById('pf-unit').value || 'g';

    if (document.getElementById('pf-has-qualities').checked) {
        var qInputs = document.querySelectorAll('#pf-quality-inputs input');
        for (var i = 0; i < qInputs.length; i++) { if (qInputs[i].value.trim()) qualities.push(qInputs[i].value.trim()); }
    }
    if (document.getElementById('pf-has-types').checked) {
        var tInputs = document.querySelectorAll('#pf-type-inputs input');
        for (var i = 0; i < tInputs.length; i++) { if (tInputs[i].value.trim()) types.push(tInputs[i].value.trim()); }
    }

    if (qualities.length === 0) qualities = [null];
    if (types.length === 0) types = [null];

    var html = '';
    var idx = 0;
    for (var q = 0; q < qualities.length; q++) {
        for (var t = 0; t < types.length; t++) {
            var label = (qualities[q] || '') + (qualities[q] && types[t] ? ' / ' : '') + (types[t] || '') || 'Standard';
            var sku = 'SUPS_' + Math.random().toString(36).substr(2, 6).toUpperCase();
            html += '<div class="variant-card" data-idx="' + idx + '">';
            html += '<div class="variant-card-header">' + label + '</div>';
            html += '<div class="variant-sku">SKU: ' + sku + '</div>';
            html += '<input type="hidden" class="v-quality" value="' + (qualities[q] || '') + '">';
            html += '<input type="hidden" class="v-type" value="' + (types[t] || '') + '">';
            html += '<input type="hidden" class="v-sku" value="' + sku + '">';
            html += '<div class="admin-form-group"><label>Image URL</label><input type="text" class="admin-input v-image" placeholder="/uploads/products/..."></div>';
            html += '<div class="admin-form-group"><label>Base Price ($)</label><input type="number" class="admin-input v-price" step="0.01" placeholder="0.00"></div>';
            html += '<div class="admin-form-group"><label>Sizes (amount / price)</label>';
            html += '<div class="dynamic-inputs v-sizes">';
            html += '<div class="size-row"><input type="number" class="admin-input" placeholder="Amount" step="0.1"><input type="number" class="admin-input" placeholder="Price $" step="0.01"><button class="remove-input-btn" onclick="removeInput(this.parentElement)">-</button></div>';
            html += '</div>';
            html += '<button class="add-input-btn" style="margin-top:4px" onclick="addSizeRow(this)">+</button>';
            html += '</div>';
            html += '</div>';
            idx++;
        }
    }

    document.getElementById('variant-cards').innerHTML = html;
    document.getElementById('variant-grid').style.display = 'block';
}

function addSizeRow(btn) {
    var container = btn.previousElementSibling;
    var row = document.createElement('div'); row.className = 'size-row';
    row.innerHTML = '<input type="number" class="admin-input" placeholder="Amount" step="0.1"><input type="number" class="admin-input" placeholder="Price $" step="0.01"><button class="remove-input-btn" onclick="removeInput(this.parentElement)">-</button>';
    container.appendChild(row);
}

function saveProduct() {
    var data = {
        action: 'admin_create_product',
        name: document.getElementById('pf-name').value,
        description: document.getElementById('pf-desc').value,
        category_id: document.getElementById('pf-category').value,
        image: document.getElementById('pf-image').value,
        unit_label: document.getElementById('pf-unit').value,
        has_qualities: document.getElementById('pf-has-qualities').checked ? 1 : 0,
        has_types: document.getElementById('pf-has-types').checked ? 1 : 0,
        variants: []
    };

    var cards = document.querySelectorAll('.variant-card[data-idx]');
    for (var i = 0; i < cards.length; i++) {
        var card = cards[i];
        var variant = {
            quality: card.querySelector('.v-quality').value,
            type: card.querySelector('.v-type').value,
            sku: card.querySelector('.v-sku').value,
            image: card.querySelector('.v-image').value,
            price: parseFloat(card.querySelector('.v-price').value) || 0,
            sizes: []
        };
        var sizeRows = card.querySelectorAll('.size-row');
        for (var j = 0; j < sizeRows.length; j++) {
            var inputs = sizeRows[j].querySelectorAll('input');
            if (inputs[0].value && inputs[1].value) {
                variant.sizes.push({ amount: parseFloat(inputs[0].value), price: parseFloat(inputs[1].value) });
            }
        }
        data.variants.push(variant);
    }

    Bridge.post('/api/router.php', data).then(function(r) {
        if (r.success) { alert('Product created.'); location.reload(); }
        else { alert(r.error || 'Failed.'); }
    });
}

function editProduct(id) { alert('Edit product ' + id + ' -- coming in next build.'); }
function deleteProduct(id) {
    if (!confirm('Delete this product?')) return;
    Bridge.post('/api/router.php', { action: 'admin_delete_product', product_id: id }).then(function(r) {
        if (r.success) location.reload();
        else alert(r.error || 'Failed.');
    });
}