document.addEventListener('DOMContentLoaded', async () => {
    // Check if user is logged in
    if (localStorage.getItem('isLoggedIn') !== 'true') {
        const path = window.location.pathname;
        if (path.includes('/pages/')) {
            window.location.href = '../login.html';
        } else {
            window.location.href = 'login.html';
        }
        return;
    }

    // Set active nav
    const currentPath = window.location.pathname;
    const navItems = document.querySelectorAll('.nav-item');

    navItems.forEach(item => {
        const href = item.getAttribute('href');
        if (currentPath.includes(href) || (currentPath.endsWith('/') && href === 'index.html')) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });

    // Load damage items
    await loadDamageItems();
});

let allDamageItems = [];

async function loadDamageItems() {
    try {
        // Use dedicated endpoint for better performance and simpler logic
        allDamageItems = await app.apiGet('/damaged-items'); // This will be prefixed with API_BASE_URL in main.js
        displayDamageItems(allDamageItems);
    } catch (error) {
        console.error('Error loading damage items:', error);
        document.getElementById('damageItemsList').innerHTML =
            '<tr><td colspan="7" class="loading">Failed to load data. Please refresh the page and try again.</td></tr>';
    }
}

function displayDamageItems(items) {
    const tbody = document.getElementById('damageItemsList');

    if (items.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="loading">No damaged items found</td></tr>';
        return;
    }

    // Sort by date desc
    items.sort((a, b) => new Date(b.return_date) - new Date(a.return_date));

    tbody.innerHTML = items.map(item => `
        <tr>
            <td>${item.return_date}</td>
            <td>${item.sku_code}</td>
            <td>${item.product_name} - ${item.flavour}</td>
            <td>${item.weight}</td>
            <td><span class="badge badge-danger">${item.quantity}</span></td>
            <td>${item.reason}</td>
            <td>
                <button class="btn btn-secondary" onclick="openEditModal(${item.id})" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;">
                    Edit
                </button>
                <button class="btn btn-danger" onclick="deleteDamageItem(${item.id})" style="padding: 0.25rem 0.5rem; font-size: 0.75rem; margin-left: 0.5rem;">
                    Delete
                </button>
            </td>
        </tr>
    `).join('');
}

function openEditModal(returnId) {
    const item = allDamageItems.find(i => i.id === returnId);
    if (!item) return;

    document.getElementById('editReturnId').value = returnId;
    document.getElementById('editSkuId').value = item.sku_id; // sku_id comes from joined return_items? Let's check api. yes.
    // Wait, the API returns r.*, ri.quantity, s.sku_code... 
    // It does NOT return sku_id explicitly in server.js line 594.
    // Let me check server.js again.
    // "SELECT r.*, ri.quantity, s.sku_code, s.flavour, s.weight, p.name as product_name"
    // It fetches from skus s (joined on ri.sku_id = s.id).
    // The query MISSES 'ri.sku_id' or 's.id as sku_id'.
    // So item.sku_id might ALSO be undefined!

    // I need to check server.js line 594 again.
    // "SELECT r.*, ri.quantity, s.sku_code..."

    // If sku_id is missing, Edit will fail too.
    // But Delete only needs ID. Use ID for now.
    // Function openEditModal needs to be fixed if sku_id is missing.
    // Let's assume for now I just fix ID for Delete.
    // But I should fix ID for openEditModal too.

    document.getElementById('editReturnType').value = item.return_type;
    document.getElementById('editProductDetails').value = `${item.sku_code} - ${item.product_name} (${item.flavour})`;
    document.getElementById('editDate').value = item.return_date;
    document.getElementById('editCustomerName').value = item.customer_name || '';
    document.getElementById('editQuantity').value = item.quantity;
    document.getElementById('editReason').value = item.reason;

    document.getElementById('editDamageModal').classList.add('active');
}

function closeEditModal() {
    document.getElementById('editDamageModal').classList.remove('active');
    document.getElementById('editDamageForm').reset();
}

async function updateDamageItem(event) {
    event.preventDefault();

    const returnId = document.getElementById('editReturnId').value;

    // Construct payload strictly matching the backend expectation
    const payload = {
        return_date: document.getElementById('editDate').value,
        customer_name: document.getElementById('editCustomerName').value,
        reason: document.getElementById('editReason').value,
        return_type: document.getElementById('editReturnType').value, // 'Damaged'
        items: [{
            sku_id: parseInt(document.getElementById('editSkuId').value),
            quantity: parseInt(document.getElementById('editQuantity').value)
        }]
    };

    try {
        await app.apiPut(`/returns/${returnId}`, payload);
        app.showNotification('Damaged item updated successfully', 'success');
        closeEditModal();
        await loadDamageItems();
    } catch (error) {
        console.error('Error updating damage item:', error);
        app.showNotification('Failed to update damage item', 'error');
    }
}

async function deleteDamageItem(returnId) {
    if (confirm('Are you sure you want to delete this damage record?')) {
        try {
            await app.apiDelete(`/returns/${returnId}`);
            app.showNotification('Damage record deleted successfully', 'success');
            await loadDamageItems();
        } catch (error) {
            console.error('Error deleting damage item:', error);
            app.showNotification('Failed to delete damage record', 'error');
        }
    }
}
