<div class="modal modal-sheet fade" id="itemModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body p-0">

                <!-- Image -->
                <div class="modal-img-wrap" id="modalImgWrap">
                    <div class="modal-img-placeholder" id="modalImgPh">🍽</div>
                    <img id="modalImg" src="" alt="" style="display:none;width:100%;height:220px;object-fit:cover;">
                    <button class="modal-close-btn" data-bs-dismiss="modal" aria-label="Close">
                        <i class="bi bi-x-lg"></i>
                    </button>
                </div>

                <!-- Info -->
                <div class="modal-info">
                    <div class="item-veg-badge" style="margin-bottom:8px;"><span></span></div>
                    <div class="modal-item-name" id="modalName"></div>
                    <div class="modal-item-desc" id="modalDesc"></div>
                    <div class="modal-item-price" id="modalPrice"></div>
                </div>

                <!-- Choice groups -->
                <div id="modalChoices"></div>

                <!-- Footer: qty + add button -->
                <div class="modal-footer-bar">
                    <div class="qty-row">
                        <span class="qty-label">Quantity</span>
                        <div class="qty-stepper">
                            <button type="button" onclick="changeQty(-1)">−</button>
                            <span id="modalQty">1</span>
                            <button type="button" onclick="changeQty(1)">+</button>
                        </div>
                    </div>
                    <button class="add-cart-btn" onclick="confirmAddToCart()">
                        <div class="add-cart-btn-left">
                            <i class="bi bi-bag-plus"></i>
                            Add to Cart
                        </div>
                        <span id="modalTotal">Rs. 0.00</span>
                    </button>
                </div>

            </div>
        </div>
    </div>
</div>

<script>
let _mItemId    = null;
let _mBasePrice = 0;
let _mQty       = 1;

async function openItemModal(itemId) {
    _mItemId = itemId;
    _mQty    = 1;
    document.getElementById('modalQty').textContent = 1;

    const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('itemModal'));

    try {
        const res  = await fetch(SHOP_URL + '/item/' + itemId + '/json');
        const data = await res.json();
        if (data.error) { showToast('Item not found.', 'danger'); return; }

        _mBasePrice = parseFloat(data.base_price);

        // Image
        const img = document.getElementById('modalImg');
        const ph  = document.getElementById('modalImgPh');
        if (data.item_image) {
            img.src = UPLOAD_URL + '/' + data.item_image;
            img.style.display = ''; ph.style.display = 'none';
        } else {
            img.style.display = 'none'; ph.style.display = '';
        }

        document.getElementById('modalName').textContent = data.name;
        document.getElementById('modalDesc').textContent = data.description || '';
        document.getElementById('modalDesc').style.display = data.description ? '' : 'none';

        // Choice groups
        const choicesEl = document.getElementById('modalChoices');
        choicesEl.innerHTML = '';
        if (data.groups && data.groups.length) {
            data.groups.forEach(g => {
                const div = document.createElement('div');
                div.innerHTML = `<div class="modal-divider"></div><div class="choice-group-name">${g.name}${g.is_required ? ' <span style="color:var(--accent);">*</span>' : ''}</div>`;
                choicesEl.appendChild(div);

                g.choices.forEach((c, i) => {
                    const label = document.createElement('label');
                    label.className = 'choice-option' + (i === 0 ? ' selected' : '');
                    label.innerHTML = `
                        <input type="radio" name="cg_${g.id}" value="${c.id}" data-price="${c.price_modifier}" ${i===0?'checked':''}>
                        <div class="choice-radio"></div>
                        <span class="choice-label">${c.label}</span>
                        ${parseFloat(c.price_modifier) > 0 ? `<span class="choice-price">+ Rs. ${parseFloat(c.price_modifier).toFixed(2)}</span>` : ''}
                    `;
                    label.addEventListener('click', () => {
                        choicesEl.querySelectorAll(`[name="cg_${g.id}"]`).forEach(r => r.closest('.choice-option').classList.remove('selected'));
                        label.classList.add('selected');
                        label.querySelector('input').checked = true;
                        recalcTotal();
                    });
                    choicesEl.appendChild(label);
                });
            });
        } else {
            const div = document.createElement('div');
            div.className = 'modal-divider';
            choicesEl.appendChild(div);
        }

        recalcTotal();
        modal.show();
    } catch(e) {
        showToast('Failed to load item details.', 'danger');
    }
}

function recalcTotal() {
    let extra = 0;
    document.querySelectorAll('#modalChoices input[type=radio]:checked').forEach(i => {
        extra += parseFloat(i.dataset.price || 0);
    });
    const total = (_mBasePrice + extra) * _mQty;
    document.getElementById('modalPrice').textContent = 'Rs. ' + (_mBasePrice + extra).toFixed(2);
    document.getElementById('modalTotal').textContent = 'Rs. ' + total.toFixed(2);
}

function changeQty(d) {
    _mQty = Math.max(1, _mQty + d);
    document.getElementById('modalQty').textContent = _mQty;
    recalcTotal();
}

async function confirmAddToCart() {
    const choices = {};
    document.querySelectorAll('#modalChoices input[type=radio]:checked').forEach(i => {
        choices[i.name.replace('cg_','')] = i.value;
    });
    const data = await addToCart(_mItemId, choices, _mQty);
    if (data.success) {
        bootstrap.Modal.getInstance(document.getElementById('itemModal'))?.hide();
    }
}
</script>
