// Dashboard Logic
document.addEventListener('DOMContentLoaded', () => {
    const user = Auth.checkAuth();
    if (!user) return;

    // Initial Load
    loadDashboard();
    setupDashboardTabs();
    initDashboardForms();
});

function normalizeLead(lead) {
    const id = lead.id || lead.lead_id || lead.leadid || lead.unique_user_id || Date.now().toString();
    const timestamp = lead.created_at || lead.timestamp || new Date().toISOString();
    const service = lead.service || lead.service_interested || 'General Service';
    
    let customerName = 'Customer';
    let customerMobile = '';
    let customerEmail = '';
    
    if (lead.customer && typeof lead.customer === 'object') {
        customerName = lead.customer.name || customerName;
        customerMobile = lead.customer.mobile || customerMobile;
        customerEmail = lead.customer.email || customerEmail;
    } else {
        customerName = lead.full_name || lead.fullName || customerName;
        customerMobile = lead.mobile || lead.mobileNumber || customerMobile;
        customerEmail = lead.email || customerEmail;
    }
    
    const status = lead.status || 'New';
    const pending_status = lead.pending_status || 'None';
    const pending_remarks = lead.pending_remarks || '';
    const lead_type = lead.lead_type || 'service_request';
    
    return {
        id,
        timestamp,
        service,
        customer: {
            name: customerName,
            mobile: customerMobile,
            email: customerEmail
        },
        status,
        pending_status,
        pending_remarks,
        lead_type
    };
}

let allLoadedLeads = [];

async function loadDashboard() {
    const user = Auth.checkAuth();
    if (!user) return;

    // Show Admin Link for Admin/SuperAdmin
    if (user.role === 'admin' || user.role === 'super_admin' || user.role === 'sub_admin') {
        const adminLink = document.getElementById('adminLink');
        if (adminLink) adminLink.classList.remove('hidden');
    }

    let rawLeads = [];
    try {
        const res = await API.Leads.getAll();
        rawLeads = res.leads || [];
    } catch (e) {
        console.warn('API fetch failed in dashboard, falling back to LocalStorage', e);
    }
    
    if (!rawLeads || rawLeads.length === 0) {
        rawLeads = JSON.parse(localStorage.getItem('freelancerLeads') || '[]');
    }

    const leads = rawLeads.map(normalizeLead);
    allLoadedLeads = leads; // Save to global array for searching/filtering
    
    // Update Welcome Message
    const welcomeName = document.getElementById('welcomeName');
    if (welcomeName) welcomeName.textContent = user.name || 'User';

    // Calculate Stats
    const total = leads.length;
    const active = leads.filter(l => l.status !== 'Approved' && l.status !== 'Rejected' && l.status !== 'Completed').length;
    const actionRequired = leads.filter(l => l.pending_status === 'Pending Raised');

    // Update UI Stats
    const sOrders = document.getElementById('statOrders');
    const sActive = document.getElementById('statActive');
    if (sOrders) sOrders.textContent = total;
    if (sActive) sActive.textContent = active;

    // Render Action Required Section for Business Partners
    const actionSection = document.getElementById('actionRequiredSection');
    if (actionSection) {
        if (actionRequired.length > 0 && user.role === 'business_partner') {
            actionSection.classList.remove('hidden');
            actionSection.innerHTML = `
                <div class="bg-amber-50 border-l-4 border-amber-500 rounded-3xl p-6 shadow-sm mb-6">
                    <div class="flex gap-4">
                        <div class="w-10 h-10 bg-amber-100 text-amber-600 rounded-xl flex items-center justify-center text-lg shrink-0">
                            <i class="fas fa-exclamation-triangle animate-bounce"></i>
                        </div>
                        <div class="flex-1">
                            <h4 class="font-black text-amber-900 text-base">Action Required: Pending Issues Raised</h4>
                            <p class="text-sm text-amber-700 mt-1">Please provide the requested details or update the status to resolve these issues:</p>
                            
                            <div class="mt-4 space-y-3">
                                ${actionRequired.map(lead => `
                                    <div class="bg-white rounded-2xl p-4 border border-amber-200/50 flex flex-col md:flex-row md:items-center justify-between gap-4 animate-pulse">
                                        <div>
                                            <div class="font-bold text-slate-800 text-sm">${lead.customer.name} - <span class="text-primary">${lead.service}</span></div>
                                            <div class="text-xs text-amber-800 font-medium mt-1">Pending Reason: ${lead.pending_remarks}</div>
                                        </div>
                                        <button onclick="resolvePendingPartner('${lead.id}')" class="px-5 py-2.5 bg-amber-500 hover:bg-amber-600 text-white rounded-xl text-xs font-black uppercase tracking-wider transition-all self-start md:self-auto shrink-0 shadow-md shadow-amber-500/20">
                                            Resolve / Respond
                                        </button>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        } else {
            actionSection.classList.add('hidden');
            actionSection.innerHTML = '';
        }
    }

    // Populate Profile Info
    try {
        const dName = document.getElementById('profileNameDisplay');
        const dRole = document.getElementById('profileRoleBadge');
        const iUniqueId = document.getElementById('profileUniqueId');
        const iName = document.getElementById('profileName');
        const iEmail = document.getElementById('profileEmail');
        const iMobile = document.getElementById('profileMobile');
        const iAddress = document.getElementById('profileAddress');

        if (dName) dName.textContent = user.name || 'User Name';
        if (dRole) dRole.textContent = user.role.replace('_', ' ').toUpperCase() || 'Customer';
        if (iUniqueId) iUniqueId.value = user.unique_user_id || 'N/A';
        if (iName) iName.value = user.name || '';
        if (iEmail) iEmail.value = user.email || '';
        if (iMobile) iMobile.value = user.mobile || '';
        if (iAddress) {
            let addrVal = user.address || '';
            if (!addrVal && user.present_address) {
                try {
                    const addr = typeof user.present_address === 'string' ? JSON.parse(user.present_address) : user.present_address;
                    const parts = [];
                    if (addr.area) parts.push(addr.area);
                    if (addr.city) parts.push(addr.city);
                    if (addr.state) parts.push(addr.state);
                    if (addr.pincode) parts.push(addr.pincode);
                    addrVal = parts.join(', ');
                } catch(err) {
                    console.error('Error parsing present_address', err);
                }
            }
            iAddress.value = addrVal;
        }
    } catch (e) { console.error('Error loading profile', e); }

    // Render Service Requests Table
    filterServiceRequests();

    // Render SVG Analytics Chart
    const counts = { New: 0, Progress: 0, Docs: 0, Done: 0, Err: 0 };
    leads.forEach(l => {
        if (l.status === 'New' || l.status === 'Pending') counts.New++;
        else if (l.status === 'In Progress') counts.Progress++;
        else if (l.status === 'Docs Collected') counts.Docs++;
        else if (l.status === 'Completed' || l.status === 'Approved') counts.Done++;
        else if (l.status === 'Rejected') counts.Err++;
    });
    
    renderUserBarChart('leadsChart', [
        { label: 'New/Pending', value: counts.New, color: '#6366F1' },
        { label: 'In Progress', value: counts.Progress, color: '#8B5CF6' },
        { label: 'Docs Collected', value: counts.Docs, color: '#06B6D4' },
        { label: 'Completed', value: counts.Done, color: '#22C55E' },
        { label: 'Rejected', value: counts.Err, color: '#EF4444' }
    ]);

    // Load dynamic recent orders
    loadRecentOrders();
}

function setupDashboardTabs() {
    window.switchTab = function(tabId) {
        // Update Sidebar links
        document.querySelectorAll('.nav-link').forEach(link => {
            if (link.dataset.tab === tabId) link.classList.add('active');
            else link.classList.remove('active');
        });

        // Toggle sections
        document.querySelectorAll('.dash-section').forEach(sec => {
            sec.classList.add('hidden');
        });
        const target = document.getElementById(`section-${tabId}`);
        if (target) target.classList.remove('hidden');

        // Close sidebar on mobile
        if (window.innerWidth < 1024 && typeof toggleSidebar === 'function') {
            toggleSidebar();
        }
    };
}

function initDashboardForms() {
    // Referral Form
    const refForm = document.querySelector('#section-referral form');
    if (refForm) {
        refForm.addEventListener('submit', (e) => {
            e.preventDefault();
            alert('Referral submitted! You will earn rewards when they join.');
            refForm.reset();
        });
    }

    // Profile Form
    const profileForm = document.querySelector('#section-profile form');
    if (profileForm) {
        profileForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const updatedUser = {
                ...JSON.parse(localStorage.getItem('anj_current_user') || '{}'),
                name: document.getElementById('profileName').value,
                email: document.getElementById('profileEmail').value,
                address: document.getElementById('profileAddress').value
            };
            localStorage.setItem('anj_current_user', JSON.stringify(updatedUser));
            alert('Profile updated successfully!');
            loadDashboard(); // Refresh UI
        });
    }


}

function animateValue(id, start, end, duration) {
    const obj = document.getElementById(id);
    if (!obj) return;
    if (start === end) {
        obj.innerHTML = end;
        return;
    }
    const range = end - start;
    let current = start;
    const increment = end > start ? 1 : -1;
    const stepTime = Math.abs(Math.floor(duration / Math.max(range, 1)));
    const timer = setInterval(function () {
        current += increment;
        obj.innerHTML = current;
        if (current == end) {
            clearInterval(timer);
        }
    }, stepTime);
}

window.toggleSidebar = function() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar) sidebar.classList.toggle('open');
    if (overlay) overlay.classList.toggle('hidden');
};

window.markAsSold = function(btn) {
    const card = btn.closest('.stat-card-luxury');
    if (!card) return;
    const badge = card.querySelector('.bg-emerald-100');
    if (badge) {
        badge.className = 'px-3 py-1 bg-slate-100 text-slate-500 rounded-full text-[10px] font-black uppercase tracking-widest';
        badge.textContent = 'Sold';
    }
    btn.disabled = true;
    btn.className = 'w-full py-3 bg-slate-50 text-slate-400 rounded-xl font-bold cursor-not-allowed text-sm';
    btn.textContent = 'Sold Out';
};

window.openServiceRequestModal = function() {
    const modal = document.getElementById('serviceRequestModal');
    if (modal) {
        modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }
};

window.closeServiceRequestModal = function() {
    const modal = document.getElementById('serviceRequestModal');
    if (modal) {
        modal.classList.add('hidden');
        document.body.style.overflow = '';
    }
};

window.updateLeadStatusPartner = async function(leadId, newStatus) {
    try {
        // Try API first
        try {
            await API.Leads.updateStatus(leadId, newStatus);
        } catch (e) {
            console.warn('API update status failed, updating LocalStorage only', e);
        }

        // Sync to LocalStorage (both paths)
        const storageKey = 'freelancerLeads';
        const leads = JSON.parse(localStorage.getItem(storageKey) || '[]');
        const idx = leads.findIndex(l => String(l.id || l.leadId) === String(leadId));
        if (idx !== -1) {
            leads[idx].status = newStatus;
            localStorage.setItem(storageKey, JSON.stringify(leads));
        }

        alert("Lead status updated to " + newStatus);
        loadDashboard();
    } catch (err) {
        console.error(err);
        alert("Failed to update status");
    }
};

window.resolvePendingPartner = async function(leadId) {
    const resolution = prompt("Please enter details or comments explaining how you resolved the pending issue:");
    if (resolution === null) return;
    
    try {
        const comment = resolution || "User submitted update";
        
        try {
            // This updates status and automatically clears pending_status in the DB
            await API.Leads.updateStatus(leadId, 'In Progress', 'Pending Resolved: ' + comment);
        } catch (e) {
            console.warn('API update failed in resolvePendingPartner', e);
        }
        
        // Sync to LocalStorage
        const storageKey = 'freelancerLeads';
        const leads = JSON.parse(localStorage.getItem(storageKey) || '[]');
        const idx = leads.findIndex(l => String(l.id || l.leadId) === String(leadId));
        if (idx !== -1) {
            leads[idx].status = 'In Progress';
            leads[idx].sub_stage = 'Pending Resolved: ' + comment;
            leads[idx].pending_status = 'None';
            leads[idx].pending_remarks = '';
            localStorage.setItem(storageKey, JSON.stringify(leads));
        }
        
        alert("Response submitted successfully! Pending status resolved.");
        loadDashboard();
    } catch(err) {
        console.error(err);
        alert("Failed to submit response.");
    }
};

window.fetchSRPincodeDetails = async function() {
    const pincode = document.getElementById('srPincode').value;
    if (pincode.length === 6) {
        try {
            const response = await fetch(`https://api.postalpincode.in/pincode/${pincode}`);
            const data = await response.json();
            if (data[0].Status === 'Success') {
                const details = data[0].PostOffice[0];
                document.getElementById('srCity').value = details.Block || details.Name;
                document.getElementById('srState').value = details.State;
                document.getElementById('srPincodeError').classList.add('hidden');
            } else {
                document.getElementById('srPincodeError').classList.remove('hidden');
                document.getElementById('srCity').value = '';
                document.getElementById('srState').value = '';
            }
        } catch (e) {
            console.error(e);
        }
    }
};

window.submitServiceRequestForm = async function(event) {
    event.preventDefault();
    
    const payload = {
        lead_type: 'freelancer',
        full_name: document.getElementById('srCustomerName').value,
        mobile: document.getElementById('srCustomerMobile').value,
        email: document.getElementById('srCustomerEmail').value,
        service_interested: document.getElementById('srServiceType').value,
        loan_amount: parseFloat(document.getElementById('srLoanAmount').value || 0),
        employment_type: document.getElementById('srEmploymentType').value || 'Other',
        city: document.getElementById('srCity').value,
        state: document.getElementById('srState').value,
        pincode: document.getElementById('srPincode').value,
        metadata: {
            remarks: document.getElementById('srRemarks').value
        },
        status: 'New'
    };
    
    try {
        let apiSuccess = false;
        try {
            await API.Leads.create(payload);
            apiSuccess = true;
        } catch(e) {
            console.warn('API lead creation failed, falling back to LocalStorage', e);
        }
        
        // LocalStorage fallback
        const leads = JSON.parse(localStorage.getItem('freelancerLeads') || '[]');
        leads.push({
            id: Date.now().toString(),
            freelancer: {
                name: Auth.getCurrentUser().name,
                mobile: Auth.getCurrentUser().mobile
            },
            service: payload.service_interested,
            customer: {
                name: payload.full_name,
                mobile: payload.mobile,
                email: payload.email,
                address: {
                    pincode: payload.pincode,
                    city: payload.city,
                    state: payload.state
                }
            },
            status: 'New',
            pending_status: 'None',
            pending_remarks: '',
            timestamp: new Date().toISOString()
        });
        localStorage.setItem('freelancerLeads', JSON.stringify(leads));
        
        alert("Lead submitted successfully!");
        closeServiceRequestModal();
        loadDashboard();
        
        // Reset form
        document.getElementById('newServiceRequestForm').reset();
    } catch(err) {
        console.error(err);
        alert("Failed to submit lead");
    }
};

function renderUserBarChart(containerId, items) {
    const container = document.getElementById(containerId);
    if (!container) return;
    const maxVal = Math.max(...items.map(i => i.value), 1);
    const height = items.length * 28 + 20;
    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.setAttribute('width', '100%');
    svg.setAttribute('height', String(height));
    let y = 10;
    items.forEach(i => {
        const wPercent = Math.round((i.value / maxVal) * 70); // Max 70% width
        const group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
        
        const label = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        label.setAttribute('x', '8');
        label.setAttribute('y', String(y + 11));
        label.setAttribute('fill', '#64748b');
        label.setAttribute('font-size', '10');
        label.setAttribute('font-weight', '700');
        label.textContent = i.label;
        
        const barBg = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
        barBg.setAttribute('x', '90');
        barBg.setAttribute('y', String(y));
        barBg.setAttribute('rx', '4');
        barBg.setAttribute('ry', '4');
        barBg.setAttribute('width', '55%');
        barBg.setAttribute('height', '12');
        barBg.setAttribute('fill', '#F1F5F9');
        
        const bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
        bar.setAttribute('x', '90');
        bar.setAttribute('y', String(y));
        bar.setAttribute('rx', '4');
        bar.setAttribute('ry', '4');
        bar.setAttribute('width', `${Math.max(wPercent * 0.55, i.value > 0 ? 5 : 0)}%`);
        bar.setAttribute('height', '12');
        bar.setAttribute('fill', i.color || '#001f4d');
        
        const val = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        val.setAttribute('x', '100%');
        val.setAttribute('dx', '-8');
        val.setAttribute('y', String(y + 11));
        val.setAttribute('fill', '#1F2937');
        val.setAttribute('font-size', '10');
        val.setAttribute('font-weight', '700');
        val.setAttribute('text-anchor', 'end');
        val.textContent = String(i.value);
        
        group.appendChild(label);
        group.appendChild(barBg);
        group.appendChild(bar);
        group.appendChild(val);
        svg.appendChild(group);
        y += 28;
    });
    container.innerHTML = '';
    container.appendChild(svg);
}

async function loadRecentOrders() {
    const recentOrders = document.getElementById('recentOrders');
    if (!recentOrders) return;
    try {
        const res = await API.Orders.getMyOrders();
        const orders = res.orders || [];
        if (orders.length === 0) {
            recentOrders.innerHTML = '<p class="text-xs text-slate-400">No recent orders placed.</p>';
        } else {
            recentOrders.innerHTML = orders.slice(0, 3).map(o => `
                <div class="flex justify-between items-center py-3 border-b last:border-0 border-slate-100">
                    <div>
                        <div class="font-bold text-slate-800 text-sm">Order #${o.id}</div>
                        <div class="text-[10px] text-slate-400">${new Date(o.created_at).toLocaleDateString()}</div>
                    </div>
                    <div class="text-right">
                        <div class="font-black text-slate-800 text-sm">₹${parseFloat(o.total_amount).toLocaleString('en-IN')}</div>
                        <span class="px-2 py-0.5 bg-blue-50 text-blue-700 text-[9px] font-black uppercase rounded-lg tracking-wider">${o.status}</span>
                    </div>
                </div>
            `).join('');
        }
    } catch(err) {
        console.warn('Failed to load recent orders', err);
        recentOrders.innerHTML = '<p class="text-xs text-slate-400">Unable to load orders.</p>';
    }
}

let currentBPStatusFilter = '';

window.setStatusFilterBP = function(status, btn) {
    currentBPStatusFilter = status;
    const chips = document.querySelectorAll('#leadStatusFilterChips .chip-btn');
    chips.forEach(c => {
        c.classList.remove('bg-primary', 'text-white', 'border-primary', 'active');
        c.classList.add('bg-white', 'text-slate-600', 'border-slate-200');
    });
    if (btn) {
        btn.classList.remove('bg-white', 'text-slate-600', 'border-slate-200');
        btn.classList.add('bg-primary', 'text-white', 'border-primary', 'active');
    }
    filterServiceRequests();
};

window.filterServiceRequests = function() {
    const searchVal = (document.getElementById('leadSearchInput')?.value || '').toLowerCase();
    const user = Auth.getCurrentUser();
    const isBP = user && user.role === 'business_partner';
    
    const filtered = allLoadedLeads.filter(lead => {
        const matchesSearch = (
            lead.customer.name.toLowerCase().includes(searchVal) ||
            lead.service.toLowerCase().includes(searchVal) ||
            lead.customer.mobile.includes(searchVal)
        );
        
        const matchesStatus = currentBPStatusFilter ? (
            currentBPStatusFilter === 'New' ? (lead.status === 'New' || lead.status === 'Pending') : lead.status === currentBPStatusFilter
        ) : true;
        
        return matchesSearch && matchesStatus;
    });
    
    renderLeadsTable(filtered, isBP);
};

function renderLeadsTable(leadsToRender, isBP) {
    const tableBody = document.getElementById('serviceRequestsTableBody');
    if (!tableBody) return;
    
    if (leadsToRender.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="4" class="px-8 py-20 text-center text-slate-400 font-medium">
                    <i class="fas fa-inbox text-4xl mb-4 opacity-10"></i><br>
                    No matching service requests found.
                </td>
            </tr>
        `;
    } else {
        tableBody.innerHTML = leadsToRender.map(lead => {
            let statusCell = '';
            
            if (isBP) {
                statusCell = `
                    <div class="flex flex-col gap-1.5" onclick="event.stopPropagation()">
                        <select onchange="updateLeadStatusPartner('${lead.id}', this.value)" class="p-2 border border-slate-200 rounded-xl text-xs bg-white outline-none focus:ring-1 focus:ring-primary font-bold max-w-[150px] cursor-pointer">
                            <option value="New" ${lead.status === 'New' || lead.status === 'Pending' ? 'selected' : ''}>New / Pending</option>
                            <option value="In Progress" ${lead.status === 'In Progress' ? 'selected' : ''}>In Progress</option>
                            <option value="Docs Collected" ${lead.status === 'Docs Collected' ? 'selected' : ''}>Docs Collected</option>
                            <option value="Completed" ${lead.status === 'Completed' ? 'selected' : ''}>Completed</option>
                            <option value="Rejected" ${lead.status === 'Rejected' ? 'selected' : ''}>Rejected</option>
                        </select>
                        ${lead.pending_status === 'Pending Raised' ? `<div class="text-[10px] text-amber-600 font-bold"><i class="fas fa-exclamation-triangle mr-1"></i>Pending Raised</div>` : ''}
                    </div>
                `;
            } else {
                statusCell = `
                    <span class="px-4 py-2 ${lead.status === 'Approved' || lead.status === 'Completed' ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'} rounded-xl text-xs font-black uppercase tracking-widest">${lead.status}</span>
                `;
            }

            return `
                <tr onclick="openLeadDetailModal('${lead.id}')" class="hover:bg-slate-50/50 transition-colors cursor-pointer">
                    <td class="px-8 py-6 font-bold text-slate-900">${new Date(lead.timestamp).toLocaleDateString()}</td>
                    <td class="px-8 py-6">
                        <div class="font-black text-slate-900">${lead.customer?.name || 'Customer'}</div>
                        <div class="text-[10px] text-slate-400 uppercase tracking-widest">${lead.customer?.mobile || ''}</div>
                    </td>
                    <td class="px-8 py-6">
                        <span class="px-4 py-2 bg-slate-100 text-slate-600 rounded-xl text-xs font-black uppercase tracking-widest">${lead.service}</span>
                    </td>
                    <td class="px-8 py-6">
                        ${statusCell}
                    </td>
                </tr>
            `;
        }).join('');
    }
}

window.openLeadDetailModal = function(leadId) {
    const lead = allLoadedLeads.find(l => String(l.id) === String(leadId));
    if (!lead) return;
    
    document.getElementById('detailLeadIdHeader').textContent = 'Lead ID: #' + lead.id;
    document.getElementById('detailCustomerName').textContent = lead.customer.name;
    document.getElementById('detailCustomerMobile').textContent = lead.customer.mobile;
    document.getElementById('detailCustomerEmail').textContent = lead.customer.email || 'Not provided';
    document.getElementById('detailServiceType').textContent = lead.service;
    document.getElementById('detailPincode').textContent = lead.customer.address?.pincode || 'N/A';
    document.getElementById('detailCity').textContent = lead.customer.address?.city || 'N/A';
    document.getElementById('detailState').textContent = lead.customer.address?.state || 'N/A';
    
    const amount = parseFloat(lead.loan_amount || 0);
    document.getElementById('detailLoanAmount').textContent = amount ? '₹' + amount.toLocaleString('en-IN') : 'N/A';
    document.getElementById('detailEmployment').textContent = lead.employment_type || 'N/A';
    document.getElementById('detailRemarks').textContent = lead.metadata?.remarks || '-';
    
    // Handle Pending alerts inside detail
    const pendingBox = document.getElementById('detailPendingAlertBox');
    if (lead.pending_status === 'Pending Raised') {
        pendingBox.classList.remove('hidden');
        document.getElementById('detailPendingAlertRemarks').textContent = lead.pending_remarks;
        document.getElementById('detailResolvePendingBtn').onclick = () => {
            closeLeadDetailModal();
            resolvePendingPartner(lead.id);
        };
    } else {
        pendingBox.classList.add('hidden');
    }
    
    // Generate Timeline Tracker
    const container = document.getElementById('detailTimelineContainer');
    
    const stages = [
        { key: 'submitted', label: 'Lead Submitted', desc: 'The service request has been registered.' },
        { key: 'review', label: 'Under Review', desc: 'Processing team is verifying details.' },
        { key: 'docs', label: 'Documents Collected', desc: 'Required documentation has been verified.' },
        { key: 'processing', label: 'Bank Processing', desc: 'Request submitted to partner bank/executive.' },
        { key: 'final', label: 'Outcome Completed', desc: 'Lead has been successfully processed.' }
    ];
    
    // Determine completed stages
    let activeStageIdx = 0; // 0=submitted
    if (lead.status === 'In Progress') activeStageIdx = 1;
    if (lead.status === 'Docs Collected') activeStageIdx = 2;
    if (lead.status === 'Bank Processing' || lead.status === 'Processing') activeStageIdx = 3;
    if (lead.status === 'Completed' || lead.status === 'Approved' || lead.status === 'Rejected') activeStageIdx = 4;
    
    container.innerHTML = stages.map((st, idx) => {
        const isCompleted = idx <= activeStageIdx;
        const isActive = idx === activeStageIdx;
        const isRejected = lead.status === 'Rejected' && idx === 4;
        
        let iconClass = 'fa-check';
        let bgClass = 'bg-slate-200 text-slate-400';
        if (isCompleted) bgClass = 'bg-primary text-white';
        if (isActive) bgClass = 'bg-emerald-500 text-white';
        if (isRejected) {
            bgClass = 'bg-red-500 text-white';
            st.label = 'Lead Rejected';
            st.desc = 'The request was rejected or closed by processing team.';
            iconClass = 'fa-times';
        }
        
        return `
            <div class="relative">
                <div class="absolute -left-[31px] top-0.5 w-4 h-4 rounded-full flex items-center justify-center text-[8px] ${bgClass} z-10">
                    <i class="fas ${iconClass}"></i>
                </div>
                <div>
                    <h5 class="text-xs font-black ${isActive || isCompleted ? 'text-slate-800' : 'text-slate-400'}">${st.label}</h5>
                    <p class="text-[10px] text-slate-400 mt-0.5">${st.desc}</p>
                </div>
            </div>
        `;
    }).join('');
    
    document.getElementById('leadDetailModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
};

window.closeLeadDetailModal = function() {
    document.getElementById('leadDetailModal').classList.add('hidden');
    document.body.style.overflow = '';
};
