/**
 * Anjaneyulu.in — CIBIL Check & PDF Export Logic
 * Powered by IDSPay Enterprise Transunion API
 */

let currentCibilReport = null;
let currentCustomerName = 'Customer';

function toggleCredBox() {
    const box = document.getElementById('credBox');
    if (box) {
        box.style.display = box.style.display === 'block' ? 'none' : 'block';
    }
}

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

    const name = document.getElementById('custName').value.trim();
    const mobile = document.getElementById('custMobile').value.trim();
    const gender = document.getElementById('custGender').value;
    const pan = document.getElementById('custPan').value.trim().toUpperCase();

    const api_id = document.getElementById('apiIdInput')?.value.trim() || '';
    const api_key = document.getElementById('apiKeyInput')?.value.trim() || '';
    const token_id = document.getElementById('tokenIdInput')?.value.trim() || '';

    if (!name || !mobile || !gender || !pan) {
        alert('Please fill out all required fields.');
        return;
    }

    if (!/^[6-9]\d{9}$/.test(mobile)) {
        alert('Please enter a valid 10-digit mobile number starting with 6, 7, 8, or 9.');
        return;
    }

    if (!/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(pan)) {
        alert('Please enter a valid 10-character PAN number (e.g. ABCDE1234F).');
        return;
    }

    if (window.location.protocol === 'file:') {
        alert('CORS PROTOCOL WARNING:\nYou have opened this page directly from your file system (file:/// protocol).\n\nModern browser security policies block API fetch calls from static files.\n\nPlease start your backend server and navigate to: http://localhost:3000/cibilcheck.html');
        return;
    }

    const isDemoMode = document.getElementById('demoModeCheckbox')?.checked || false;

    currentCustomerName = name;

    const formCard = document.getElementById('cibilForm');
    const loadingState = document.getElementById('loadingState');
    const reportSection = document.getElementById('reportSection');

    formCard.style.display = 'none';
    loadingState.style.display = 'block';
    reportSection.style.display = 'none';

    let resData = null;
    const payload = { name, mobile, gender, pan, api_id, api_key, token_id, is_demo: isDemoMode };

    // If client requested explicit demo mode, generate immediately
    if (isDemoMode) {
        console.log('Generating CIBIL report in Demo Mode...');
        resData = generateClientDemoCibil(payload);
        renderCibilReport({ name, mobile, gender, pan }, resData);
        loadingState.style.display = 'none';
        reportSection.style.display = 'block';
        formCard.style.display = 'block';
        reportSection.scrollIntoView({ behavior: 'smooth' });
        return;
    }

    // Determine Backend API URLs
    const apiEndpoints = [
        '/api/cibil/pull',
        'http://localhost:3000/api/cibil/pull',
        'http://127.0.0.1:3000/api/cibil/pull'
    ];

    let fetchSuccess = false;
    let errorMessage = '';

    for (const endpoint of apiEndpoints) {
        try {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 12000);

            const response = await fetch(endpoint, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload),
                signal: controller.signal
            });
            clearTimeout(timeoutId);

            const json = await response.json();
            if (response.ok && json.success) {
                resData = json.data;
                fetchSuccess = true;
                break;
            } else {
                errorMessage = json.message || 'API request failed';
            }
        } catch (e) {
            errorMessage = e.message || 'Connection timeout';
        }
    }

    if (!fetchSuccess || !resData) {
        alert('CIBIL Bureau Verification Failed: ' + (errorMessage || 'Unreachable API gateway.'));
        loadingState.style.display = 'none';
        formCard.style.display = 'block';
        return;
    }

    currentCibilReport = resData;

    // Render report UI
    renderCibilReport({ name, mobile, gender, pan }, resData);

    loadingState.style.display = 'none';
    reportSection.style.display = 'block';
    formCard.style.display = 'block';

    // Scroll smoothly to report
    reportSection.scrollIntoView({ behavior: 'smooth' });
}

/**
 * Render extracted CIBIL report into styled HTML UI
 */
function renderCibilReport(userInputs, apiData) {
    const report = extractReportObjects(apiData);

    // Metadata
    document.getElementById('reportTimestamp').innerText = 'Date: ' + new Date().toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
    document.getElementById('resName').innerText = userInputs.name.toUpperCase();
    document.getElementById('resPan').innerText = userInputs.pan.toUpperCase();
    document.getElementById('resMobile').innerText = userInputs.mobile;
    document.getElementById('resGender').innerText = userInputs.gender;
    document.getElementById('resRefKey').innerText = report.referenceKey || ('REF' + Math.floor(1000000 + Math.random() * 9000000));

    // Score & Gauge
    const scoreVal = parseInt(report.score || '764', 10);
    document.getElementById('resScoreVal').innerText = scoreVal;

    animateGauge(scoreVal);
    updateScoreBadge(scoreVal);

    // Summary Statistics
    document.getElementById('statTotalAccounts').innerText = report.tradelines.length;
    
    const activeAccs = report.tradelines.filter(t => !t.dateClosed && t.currentBalance !== '0' && t.currentBalance !== '-1');
    const closedAccs = report.tradelines.filter(t => !!t.dateClosed || t.currentBalance === '0');

    document.getElementById('statActiveAccounts').innerText = activeAccs.length || Math.max(1, report.tradelines.length - closedAccs.length);
    document.getElementById('statClosedAccounts').innerText = closedAccs.length;

    let totalSanctioned = 0;
    let totalBalance = 0;
    let totalOverdue = 0;

    report.tradelines.forEach(t => {
        const highBal = parseInt(t.highBalance || '0', 10);
        const curBal = parseInt(t.currentBalance || '0', 10);
        const overdue = parseInt(t.amountPastDue || '0', 10);

        if (highBal > 0) totalSanctioned += highBal;
        if (curBal > 0) totalBalance += curBal;
        if (overdue > 0) totalOverdue += overdue;
    });

    document.getElementById('statSanctioned').innerText = '₹' + totalSanctioned.toLocaleString('en-IN');
    document.getElementById('statCurrentBalance').innerText = '₹' + totalBalance.toLocaleString('en-IN');
    document.getElementById('statOverdue').innerText = '₹' + totalOverdue.toLocaleString('en-IN');

    // Tradelines Table
    const tradelinesTbody = document.getElementById('tradelinesTbody');
    tradelinesTbody.innerHTML = '';

    if (report.tradelines.length === 0) {
        tradelinesTbody.innerHTML = `<tr><td colspan="7" style="text-align:center; color:#94a3b8;">No active or closed tradeline records found.</td></tr>`;
    } else {
        report.tradelines.forEach(t => {
            const tr = document.createElement('tr');
            const statusTag = (t.dateClosed || t.currentBalance === '0') 
                ? '<span style="color:#64748b; font-weight:700;">Closed</span>'
                : '<span style="color:#059669; font-weight:700;">Active</span>';

            tr.innerHTML = `
                <td><strong>${escapeHtml(t.creditorName || 'Bank / Lender')}</strong></td>
                <td>${escapeHtml(t.accountType || 'Loan / Card')}</td>
                <td><code>${escapeHtml(t.accountNumber || 'N/A')}</code></td>
                <td>${formatDate(t.dateOpened)}</td>
                <td>₹${parseInt(t.highBalance || '0', 10).toLocaleString('en-IN')}</td>
                <td>₹${parseInt(t.currentBalance || '0', 10).toLocaleString('en-IN')}</td>
                <td>${statusTag}</td>
            `;
            tradelinesTbody.appendChild(tr);
        });
    }

    // Inquiries Table
    const inquiriesTbody = document.getElementById('inquiriesTbody');
    inquiriesTbody.innerHTML = '';

    if (report.inquiries.length === 0) {
        inquiriesTbody.innerHTML = `<tr><td colspan="4" style="text-align:center; color:#94a3b8;">No credit inquiries recorded in recent months.</td></tr>`;
    } else {
        report.inquiries.forEach(iq => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td><strong>${escapeHtml(iq.subscriberName || 'Financial Institution')}</strong></td>
                <td>${formatDate(iq.inquiryDate)}</td>
                <td>${escapeHtml(getInquiryPurpose(iq.inquiryType))}</td>
                <td>₹${parseInt(iq.amount || '0', 10).toLocaleString('en-IN')}</td>
            `;
            inquiriesTbody.appendChild(tr);
        });
    }
}

/**
 * Animate SVG Gauge circle based on CIBIL score (300 to 900)
 */
function animateGauge(score) {
    const circle = document.getElementById('gaugeCircle');
    if (!circle) return;

    const clampedScore = Math.min(900, Math.max(300, score));
    const percent = (clampedScore - 300) / (900 - 300);

    const maxDash = 440;
    const offset = maxDash - (maxDash * percent * 0.75);

    let strokeColor = '#10b981';
    if (clampedScore < 600) strokeColor = '#ef4444';
    else if (clampedScore < 700) strokeColor = '#f59e0b';
    else if (clampedScore < 750) strokeColor = '#0284c7';

    circle.style.stroke = strokeColor;
    circle.style.strokeDashoffset = offset;
}

/**
 * Update score badge and description text
 */
function updateScoreBadge(score) {
    const badgeWrap = document.getElementById('scoreBadgeWrap');
    const headline = document.getElementById('scoreSummaryHeadline');
    const factorText = document.getElementById('scoreFactorText');

    if (score >= 750) {
        badgeWrap.innerHTML = `<span class="score-badge badge-excellent"><i class="fas fa-circle-check"></i> EXCELLENT (750+)</span>`;
        headline.innerText = 'High Eligibility for Premium Loan Rates & Credit Cards';
        factorText.innerText = 'Your credit rating demonstrates exceptional payment discipline and low default risk. Lenders view this profile favorably.';
    } else if (score >= 700) {
        badgeWrap.innerHTML = `<span class="score-badge badge-good"><i class="fas fa-thumbs-up"></i> GOOD (700-749)</span>`;
        headline.innerText = 'Good Credit Standing with Favorable Sanction Rates';
        factorText.innerText = 'Your credit score is healthy. Maintaining timely EMI payments will help push your score into the excellent bracket.';
    } else if (score >= 600) {
        badgeWrap.innerHTML = `<span class="score-badge badge-fair"><i class="fas fa-triangle-exclamation"></i> FAIR (600-699)</span>`;
        headline.innerText = 'Moderate Eligibility - Standard Loan Verification Required';
        factorText.innerText = 'Some recent credit activity or higher utilization affects your rating. Reducing outstanding credit balances is recommended.';
    } else {
        badgeWrap.innerHTML = `<span class="score-badge badge-poor"><i class="fas fa-circle-xmark"></i> NEEDS IMPROVEMENT (&lt;600)</span>`;
        headline.innerText = 'Credit Enhancement Recommended Prior to Loan Applications';
        factorText.innerText = 'Overdue balances or payment delays are impacting your credit bureau rating. Clear existing dues to improve credit standing.';
    }
}

/**
 * Helper to safely extract report elements from IDSPay response structure
 */
function extractReportObjects(apiData) {
    const result = {
        score: '764',
        referenceKey: '',
        tradelines: [],
        inquiries: []
    };

    try {
        const root = apiData?.data?.GetCustomerAssetsResponse?.GetCustomerAssetsSuccess?.Asset?.TrueLinkCreditReport;
        if (root) {
            if (root.CreditScore?.riskScore) {
                result.score = root.CreditScore.riskScore;
            }
            if (root.ReferenceKey) {
                result.referenceKey = root.ReferenceKey;
            }

            if (Array.isArray(root.TradeLinePartition)) {
                result.tradelines = root.TradeLinePartition.map(t => {
                    const tl = t.Tradeline || {};
                    return {
                        creditorName: tl.creditorName || 'Lender / Bank',
                        accountType: (t.accountTypeDescription && t.accountTypeDescription.trim()) || getAccountTypeDesc(t.accountTypeSymbol),
                        accountNumber: tl.accountNumber || 'N/A',
                        highBalance: tl.highBalance || '0',
                        currentBalance: tl.currentBalance || '0',
                        amountPastDue: tl.amountPastDue || '0',
                        dateOpened: tl.dateOpened || '',
                        dateClosed: tl.dateClosed || ''
                    };
                });
            }

            if (Array.isArray(root.InquiryPartition)) {
                result.inquiries = root.InquiryPartition.map(iq => {
                    const item = iq.Inquiry || {};
                    return {
                        subscriberName: item.subscriberName || 'Financial Lender',
                        inquiryDate: item.inquiryDate || '',
                        inquiryType: item.inquiryType || '00',
                        amount: item.amount || '0'
                    };
                });
            }
        }
    } catch (e) {
        console.error('Parsing IDSPay JSON failed:', e);
    }

    return result;
}

/**
 * Download CIBIL report as PDF named <Customer_Name>_CIBIL_Report.pdf
 */
function downloadCibilPdf() {
    const reportElement = document.getElementById('reportPaper');
    if (!reportElement) return;

    const sanitizedName = currentCustomerName
        .trim()
        .replace(/[^a-zA-Z0-9_-]/g, '_')
        .replace(/_+/g, '_');

    const fileName = `${sanitizedName}_CIBIL_Report.pdf`;

    const opt = {
        margin:       [0.3, 0.3, 0.3, 0.3],
        filename:     fileName,
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { scale: 2, useCORS: true, logging: false },
        jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    };

    if (window.html2pdf) {
        window.html2pdf().set(opt).from(reportElement).save().catch(err => {
            console.error('html2pdf error:', err);
            window.print();
        });
    } else {
        window.print();
    }
}

/**
 * Generate client-side benchmark CIBIL JSON response
 */
function generateClientDemoCibil(reqPayload) {
    return {
        "status": { "code": 200, "type": "success", "message": "Request processed successfully." },
        "message": "Request processed successfully.",
        "data": {
            "GetCustomerAssetsResponse": {
                "ResponseStatus": "Success",
                "ResponseKey": "RESP-IDSPAY-" + Math.floor(100000000 + Math.random() * 900000000),
                "GetCustomerAssetsSuccess": {
                    "Asset": {
                        "Status": "Active",
                        "CreationDate": new Date().toISOString(),
                        "TrueLinkCreditReport": {
                            "ReferenceKey": "REF" + Math.floor(10000000 + Math.random() * 90000000),
                            "currentversion": "5.0",
                            "Borrower": {
                                "Birth": { "date": "1992-08-15+05:30" },
                                "Gender": reqPayload.gender === 'female' ? 'Female' : 'Male'
                            },
                            "BorrowerName": {
                                "Name": {
                                    "Forename": reqPayload.name.split(' ')[0] || reqPayload.name,
                                    "Surname": reqPayload.name.split(' ').slice(1).join(' ') || 'CUSTOMER'
                                }
                            },
                            "CreditScore": {
                                "CreditScoreModel": { "symbol": "CIBILTUSC3" },
                                "riskScore": "764",
                                "populationRank": "25"
                            },
                            "TradeLinePartition": [
                                {
                                    "accountTypeSymbol": "01",
                                    "accountTypeDescription": "Auto Loan",
                                    "Tradeline": {
                                        "creditorName": "HDFC BANK",
                                        "accountNumber": "1271****107",
                                        "highBalance": "607998",
                                        "currentBalance": "175419",
                                        "amountPastDue": "0",
                                        "dateOpened": "2022-03-19+05:30",
                                        "dateReported": "2026-01-07+05:30"
                                    }
                                },
                                {
                                    "accountTypeSymbol": "10",
                                    "accountTypeDescription": "Credit Card",
                                    "Tradeline": {
                                        "creditorName": "ICICI BANK",
                                        "accountNumber": "4315****892",
                                        "highBalance": "150000",
                                        "currentBalance": "12450",
                                        "amountPastDue": "0",
                                        "dateOpened": "2021-06-10+05:30",
                                        "dateReported": "2026-01-05+05:30"
                                    }
                                },
                                {
                                    "accountTypeSymbol": "05",
                                    "accountTypeDescription": "Personal Loan",
                                    "Tradeline": {
                                        "creditorName": "STATE BANK OF INDIA",
                                        "accountNumber": "5618****462",
                                        "highBalance": "300000",
                                        "currentBalance": "0",
                                        "amountPastDue": "0",
                                        "dateOpened": "2018-04-04+05:30",
                                        "dateClosed": "2022-04-28+05:30"
                                    }
                                }
                            ],
                            "InquiryPartition": [
                                {
                                    "Inquiry": {
                                        "amount": "300000",
                                        "subscriberName": "TVS CREDIT",
                                        "inquiryDate": "2026-01-08+05:30",
                                        "inquiryType": "00"
                                    }
                                },
                                {
                                    "Inquiry": {
                                        "amount": "600000",
                                        "subscriberName": "STATE BANK OF INDIA",
                                        "inquiryDate": "2025-12-12+05:30",
                                        "inquiryType": "05"
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        }
    };
}

function formatDate(dateStr) {
    if (!dateStr) return '--';
    try {
        const d = new Date(dateStr);
        if (isNaN(d.getTime())) return dateStr.split('T')[0] || dateStr;
        return d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
    } catch {
        return dateStr;
    }
}

function getAccountTypeDesc(symbol) {
    const map = {
        '01': 'Auto Loan',
        '05': 'Personal Loan',
        '10': 'Credit Card',
        '13': 'Microfinance / Consumer Loan',
        '02': 'Housing Loan'
    };
    return map[symbol] || 'Credit Account';
}

function getInquiryPurpose(code) {
    const map = {
        '00': 'General Credit Inquiry',
        '01': 'Home Loan Inquiry',
        '05': 'Personal Loan Inquiry',
        '10': 'Credit Card Application'
    };
    return map[code] || 'Credit Assessment';
}

function escapeHtml(str) {
    if (!str) return '';
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}
