async function initItemLedger() {
    const $itemSelect = $('#ilItemSelect');
    const $tableBody = $('#ilTableBody');
    const $tableFoot = $('#ilTableFoot');
    const $btnShow = $('#btnShowItemLedger');
    const $summaryCards = $('#ilSummaryCards');
    const $btnPrint = $('#btnPrintLedger');

    // 1. Set default dates (Current Year)
    const todayStr = Utils.getISODate();
    const currentYear = new Date().getFullYear();
    const firstDayStr = `${currentYear}-01-01`;
    $('#ilDateFrom').val(firstDayStr);
    $('#ilDateTo').val(todayStr);

    // 2. Load Items
    try {
        const res = await API.get('/items');
        $itemSelect.empty().append('<option value=""></option>');
        res.data.forEach(i => {
            $itemSelect.append(new Option(i.name, i.id));
        });
        $itemSelect.select2({
            placeholder: 'جنس منتخب کریں...',
            allowClear: true,
            dir: 'rtl',
            width: '100%'
        });
    } catch (err) {
        Toast.danger("اجناس لوڈ کرنے میں غلطی آئی۔");
    }

    // 3. Show Ledger Action
    $btnShow.on('click', async function() {
        const itemId = $itemSelect.val();
        const from = $('#ilDateFrom').val();
        const to = $('#ilDateTo').val();

        if (!itemId) {
            Toast.warning("براہ کرم پہلے جنس منتخب کریں۔");
            return;
        }

        const itemName = $itemSelect.find('option:selected').text();
        $('#ilLedgerTitle').text(`کھاتہ تفصیل: ${itemName}`);
        $('#printItemName').text(`جنس: ${itemName}`);
        $('#printDateRange').text(`مورخہ ${Utils.formatDate(from)} تا ${Utils.formatDate(to)}`);
        
        $btnShow.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> رپورٹ بن رہی ہے...');

        try {
            const res = await API.get(`/items/${itemId}/advanced-ledger`, { from_date: from, to_date: to });
            renderItemLedger(res.data, from);
            Toast.success("کھاتہ رپورٹ اپڈیٹ کر دی گئی ہے۔");
            $summaryCards.fadeIn();
            $tableFoot.show();
            $btnPrint.show();
        } catch (err) {
            $tableBody.html('<tr><td colspan="6" class="text-center text-danger">ڈیٹا لوڈ کرنے میں غلطی ہوئی۔</td></tr>');
        } finally {
            $btnShow.prop('disabled', false).html('<i class="fas fa-search"></i> کھاتہ دکھائیں');
        }
    });

    /**
     * Format financial balance with نام/جمع label
     */
    function formatBalance(val) {
        const abs = Utils.formatNumber(Math.abs(val));
        if (val >= 0) {
            return `<span style="color: #4ade80;">نام ${abs}</span>`;
        } else {
            return `<span style="color: #f87171;">جمع ${abs}</span>`;
        }
    }

    function renderItemLedger(data, fromDate) {
        let html = '';
        const entries = data.entries;
        const openingWazan = parseFloat(data.opening_wazan);
        const openingFinancial = parseFloat(data.opening_financial);
        const summary = data.summary;

        // 1. Update KPI Cards
        $('#ilKpiOpening').text('KG ' + Utils.formatNumber(openingWazan));
        $('#ilKpiTotalDr').text(Utils.formatNumber(summary.total_dr));
        $('#ilKpiTotalCr').text(Utils.formatNumber(summary.total_cr));
        $('#ilKpiFinancial').html(formatBalance(summary.current_financial));

        // 2. Opening Balance Row
        const openingDr = openingFinancial >= 0 ? Utils.formatNumber(openingFinancial) : '-';
        const openingCr = openingFinancial < 0 ? Utils.formatNumber(Math.abs(openingFinancial)) : '-';

        html += `
            <tr style="background-color: var(--accent-light); border-bottom: 2px solid var(--border);">
                <td>${Utils.formatDate(fromDate)}</td>
                <td class="fw-bold">سابقہ بقایا (Opening Balance) — وزن: ${Utils.formatNumber(openingWazan)} KG</td>
                <td>-</td>
                <td class="text-success fw-bold">${openingDr}</td>
                <td class="text-danger fw-bold">${openingCr}</td>
                <td class="fw-bold">${formatBalance(openingFinancial)}</td>
            </tr>
        `;

        // 3. Transaction Rows
        if (entries.length === 0) {
            html += '<tr><td colspan="6" class="text-center py-4">اس دورانیے میں کوئی انٹری نہیں ملی۔</td></tr>';
        } else {
            entries.forEach(e => {
                const wIn = parseFloat(e.weight_in);
                const wOut = parseFloat(e.weight_out);
                const dr = parseFloat(e.dr);
                const cr = parseFloat(e.cr);
                const runFin = parseFloat(e.running_financial);
                
                let badgeClass = 'bg-secondary';
                if (e.type === 'purchase') badgeClass = 'bg-success';
                else if (e.type === 'sale') badgeClass = 'bg-danger';
                else if (e.type === 'expense') badgeClass = 'bg-warning text-dark';

                // Build weight display
                let weightDisplay = '-';
                if (wIn > 0) weightDisplay = `<span class="text-success">+${Utils.formatNumber(wIn)}</span>`;
                else if (wOut > 0) weightDisplay = `<span class="text-danger">-${Utils.formatNumber(wOut)}</span>`;

                // Build detail cell
                const detail = `<span class="badge ${badgeClass}" style="margin-left:5px;">${e.type_label}</span> ${e.ref_no} — ${e.party_name}`;

                html += `
                    <tr>
                        <td>${Utils.formatDate(e.date)}</td>
                        <td>${detail}</td>
                        <td>${weightDisplay}</td>
                        <td class="text-success">${dr > 0 ? Utils.formatNumber(dr) : '-'}</td>
                        <td class="text-danger">${cr > 0 ? Utils.formatNumber(cr) : '-'}</td>
                        <td class="fw-bold">${formatBalance(runFin)}</td>
                    </tr>
                `;
            });
        }

        $tableBody.html(html);

        // 4. Update Footer Totals
        $('#ilTotalStock').text(Utils.formatNumber(summary.current_stock));
        $('#ilTotalDr').text(Utils.formatNumber(summary.total_dr));
        $('#ilTotalCr').text(Utils.formatNumber(summary.total_cr));
        $('#ilFinalBalance').html(formatBalance(summary.current_financial));
    }
}
