<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GST Returns Processor</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js"></script>
    <style>
        :root {
            --primary: #4361ee;
            --primary-dark: #3a0ca3;
            --secondary: #4cc9f0;
            --light: #f8f9fa;
            --dark: #212529;
            --success: #4cc9f0;
            --danger: #f72585;
            --warning: #f8961e;
            --info: #90e0ef;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7ff;
            color: var(--dark);
        }

        .navbar {
            background-color: var(--primary);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .navbar-brand {
            font-weight: 700;
            color: white !important;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .card {
            border-radius: 10px;
            border: none;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            margin-bottom: 30px;
        }

        .card-header {
            background-color: var(--primary);
            color: white;
            font-weight: 600;
            padding: 15px 20px;
            border-bottom: none;
        }

        .card-body {
            padding: 25px;
        }

        .upload-container {
            border: 2px dashed #d1d1d1;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            background-color: #f8f9fa;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .upload-container:hover, .upload-container.dragover {
            border-color: var(--primary);
            background-color: rgba(67, 97, 238, 0.05);
        }

        .upload-icon {
            font-size: 48px;
            color: var(--primary);
            margin-bottom: 15px;
        }

        .btn-primary {
            background-color: var(--primary);
            border-color: var(--primary);
        }

        .btn-primary:hover {
            background-color: var(--primary-dark);
            border-color: var(--primary-dark);
        }

        .btn-outline-primary {
            color: var(--primary);
            border-color: var(--primary);
        }

        .btn-outline-primary:hover {
            background-color: var(--primary);
            border-color: var(--primary);
        }

        .file-list {
            max-height: 300px;
            overflow-y: auto;
            margin-top: 20px;
        }

        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            background-color: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 10px;
            transition: transform 0.2s ease;
        }

        .file-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
        }

        .file-name {
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .file-badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-gstr1 {
            background-color: rgba(67, 97, 238, 0.1);
            color: var(--primary);
        }

        .badge-gstr2a {
            background-color: rgba(76, 201, 240, 0.1);
            color: var(--secondary);
        }

        .badge-gstr3b {
            background-color: rgba(255, 183, 3, 0.1);
            color: var(--warning);
        }

        .progress {
            height: 8px;
            margin-top: 25px;
            border-radius: 4px;
        }

        .progress-bar {
            background-color: var(--primary);
        }

        .processing-status {
            display: none;
            margin-top: 20px;
            text-align: center;
        }

        .result-message {
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            display: none;
        }

        .result-success {
            background-color: rgba(76, 201, 240, 0.1);
            color: var(--success);
            border-left: 4px solid var(--success);
        }

        .result-error {
            background-color: rgba(247, 37, 133, 0.1);
            color: var(--danger);
            border-left: 4px solid var(--danger);
        }

        .nav-tabs {
            border-bottom: 1px solid #dee2e6;
            margin-bottom: 20px;
        }

        .nav-tabs .nav-link {
            border: none;
            color: #6c757d;
            font-weight: 500;
            padding: 10px 15px;
            margin-right: 5px;
            transition: all 0.3s ease;
        }

        .nav-tabs .nav-link:hover {
            border: none;
            color: var(--primary);
        }

        .nav-tabs .nav-link.active {
            color: var(--primary);
            border: none;
            border-bottom: 3px solid var(--primary);
            background-color: transparent;
            font-weight: 600;
        }

        .report-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .report-card {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
            padding: 20px;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            cursor: pointer;
        }

        .report-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
        }

        .report-icon {
            font-size: 32px;
            color: var(--primary);
            margin-bottom: 15px;
        }

        .report-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 10px;
            color: var(--dark);
        }

        .report-desc {
            font-size: 14px;
            color: #6c757d;
        }

        footer {
            background-color: white;
            text-align: center;
            padding: 20px;
            margin-top: 50px;
            border-top: 1px solid #eaeaea;
        }

        @keyframes pulse {
            0% { opacity: 0.6; }
            50% { opacity: 1; }
            100% { opacity: 0.6; }
        }

        .loading-pulse {
            animation: pulse 1.5s infinite ease-in-out;
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand" href="#">GST Returns Processor</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#reports">Reports</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#help">Help</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-lg-8 mx-auto">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>Upload GST Return Files</span>
                        <span class="badge bg-light text-dark">Supports GSTR1, GSTR2A, GSTR3B</span>
                    </div>
                    <div class="card-body">
                        <div class="upload-container" id="upload-area">
                            <div class="upload-icon">📂</div>
                            <h4>Drag & Drop your GST JSON files here</h4>
                            <p class="text-muted mb-3">or</p>
                            <input type="file" id="file-input" multiple accept=".json" class="d-none">
                            <button class="btn btn-primary" onclick="document.getElementById('file-input').click()">Browse Files</button>
                            <p class="text-muted mt-3 small">Upload your GSTR1, GSTR2A, and GSTR3B JSON files to process and analyze</p>
                        </div>

                        <div class="file-list" id="file-list">
                            <!-- Files will be listed here -->
                        </div>

                        <div class="progress">
                            <div class="progress-bar" role="progressbar" style="width: 0%" id="progress-bar"></div>
                        </div>

                        <div class="processing-status" id="processing-status">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Processing...</span>
                            </div>
                            <p class="mt-2">Processing your GST returns data, please wait...</p>
                        </div>

                        <div class="result-message" id="result-message">
                            <!-- Result message will appear here -->
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <button class="btn btn-outline-danger" id="clear-btn">Clear All</button>
                            <div>
                                <button class="btn btn-outline-primary me-2" id="preview-btn" disabled>Preview Data</button>
                                <button class="btn btn-primary" id="process-btn" disabled>Process to Excel</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mt-4" id="data-preview" style="display: none;">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <span>Data Preview</span>
                    </div>
                    <div class="card-body">
                        <ul class="nav nav-tabs" id="previewTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="gstr1-tab" data-bs-toggle="tab" data-bs-target="#gstr1-preview">GSTR1</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="gstr2a-tab" data-bs-toggle="tab" data-bs-target="#gstr2a-preview">GSTR2A</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="gstr3b-tab" data-bs-toggle="tab" data-bs-target="#gstr3b-preview">GSTR3B</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="summary-tab" data-bs-toggle="tab" data-bs-target="#summary-preview">Summary</button>
                            </li>
                        </ul>
                        <div class="tab-content" id="previewTabContent">
                            <div class="tab-pane fade show active" id="gstr1-preview" role="tabpanel">
                                <div class="table-responsive mt-3">
                                    <table class="table table-striped table-hover" id="gstr1-table">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Customer GSTIN</th>
                                                <th>Invoice Number</th>
                                                <th>Invoice Date</th>
                                                <th>Invoice Value</th>
                                                <th>Taxable Value</th>
                                                <th>CGST</th>
                                                <th>SGST</th>
                                                <th>IGST</th>
                                                <th>Total Tax</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- GSTR1 data will be populated here -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="gstr2a-preview" role="tabpanel">
                                <div class="table-responsive mt-3">
                                    <table class="table table-striped table-hover" id="gstr2a-table">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Supplier GSTIN</th>
                                                <th>Invoice Number</th>
                                                <th>Invoice Date</th>
                                                <th>Invoice Value</th>
                                                <th>Taxable Value</th>
                                                <th>CGST</th>
                                                <th>SGST</th>
                                                <th>IGST</th>
                                                <th>Total Tax</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- GSTR2A data will be populated here -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="gstr3b-preview" role="tabpanel">
                                <div class="table-responsive mt-3">
                                    <table class="table table-striped table-hover" id="gstr3b-table">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Description</th>
                                                <th>Taxable Value</th>
                                                <th>IGST</th>
                                                <th>CGST</th>
                                                <th>SGST</th>
                                                <th>Cess</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- GSTR3B data will be populated here -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="summary-preview" role="tabpanel">
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <div class="card bg-light">
                                            <div class="card-body">
                                                <h5 class="card-title">GSTR1 Summary</h5>
                                                <div class="row">
                                                    <div class="col-6">
                                                        <p class="mb-1">Total Invoices:</p>
                                                        <h4 id="gstr1-invoice-count">0</h4>
                                                    </div>
                                                    <div class="col-6">
                                                        <p class="mb-1">Total Value:</p>
                                                        <h4 id="gstr1-total-value">₹0.00</h4>
                                                    </div>
                                                </div>
                                                <div class="row mt-3">
                                                    <div class="col-6">
                                                        <p class="mb-1">Total Tax:</p>
                                                        <h4 id="gstr1-total-tax">₹0.00</h4>
                                                    </div>
                                                    <div class="col-6">
                                                        <p class="mb-1">Taxable Value:</p>
                                                        <h4 id="gstr1-taxable-value">₹0.00</h4>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="card bg-light">
                                            <div class="card-body">
                                                <h5 class="card-title">GSTR2A Summary</h5>
                                                <div class="row">
                                                    <div class="col-6">
                                                        <p class="mb-1">Total Invoices:</p>
                                                        <h4 id="gstr2a-invoice-count">0</h4>
                                                    </div>
                                                    <div class="col-6">
                                                        <p class="mb-1">Total Value:</p>
                                                        <h4 id="gstr2a-total-value">₹0.00</h4>
                                                    </div>
                                                </div>
                                                <div class="row mt-3">
                                                    <div class="col-6">
                                                        <p class="mb-1">Total Tax:</p>
                                                        <h4 id="gstr2a-total-tax">₹0.00</h4>
                                                    </div>
                                                    <div class="col-6">
                                                        <p class="mb-1">Taxable Value:</p>
                                                        <h4 id="gstr2a-taxable-value">₹0.00</h4>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <div class="card bg-light">
                                            <div class="card-body">
                                                <h5 class="card-title">GSTR3B Summary</h5>
                                                <div class="row">
                                                    <div class="col-6">
                                                        <p class="mb-1">Total Output Tax:</p>
                                                        <h4 id="gstr3b-output-tax">₹0.00</h4>
                                                    </div>
                                                    <div class="col-6">
                                                        <p class="mb-1">Total ITC:</p>
                                                        <h4 id="gstr3b-total-itc">₹0.00</h4>
                                                    </div>
                                                </div>
                                                <div class="row mt-3">
                                                    <div class="col-6">
                                                        <p class="mb-1">Tax Paid:</p>
                                                        <h4 id="gstr3b-tax-paid">₹0.00</h4>
                                                    </div>
                                                    <div class="col-6">
                                                        <p class="mb-1">ITC Utilized:</p>
                                                        <h4 id="gstr3b-itc-utilized">₹0.00</h4>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="card bg-light">
                                            <div class="card-body">
                                                <h5 class="card-title">Reconciliation Summary</h5>
                                                <div class="row">
                                                    <div class="col-6">
                                                        <p class="mb-1">GSTR1 vs GSTR3B:</p>
                                                        <h4 id="reconciliation-1-3b">-</h4>
                                                    </div>
                                                    <div class="col-6">
                                                        <p class="mb-1">GSTR2A vs ITC:</p>
                                                        <h4 id="reconciliation-2a-itc">-</h4>
                                                    </div>
                                                </div>
                                                <div class="row mt-3">
                                                    <div class="col-12">
                                                        <p class="mb-1">Status:</p>
                                                        <h4 id="reconciliation-status">-</h4>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mt-4" id="reports">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <span>Available MIS Reports</span>
                    </div>
                    <div class="card-body">
                        <p>Generate detailed MIS reports from your GST data for better insights and compliance:</p>
                        
                        <div class="report-grid">
                            <div class="report-card" onclick="generateReport('b2b-invoice-matching')">
                                <div class="report-icon">📋</div>
                                <div class="report-title">B2B Invoice Matching</div>
                                <div class="report-desc">Match invoices between GSTR1 and GSTR2A for reconciliation</div>
                            </div>
                            
                            <div class="report-card" onclick="generateReport('hsn-summary')">
                                <div class="report-icon">📊</div>
                                <div class="report-title">HSN Summary Report</div>
                                <div class="report-desc">Summary of supplies based on HSN codes with tax details</div>
                            </div>
                            
                            <div class="report-card" onclick="generateReport('itc-eligibility')">
                                <div class="report-icon">💰</div>
                                <div class="report-title">ITC Eligibility Report</div>
                                <div class="report-desc">Analyze eligible and ineligible input tax credits</div>
                            </div>
                            
                            <div class="report-card" onclick="generateReport('tax-liability')">
                                <div class="report-icon">📝</div>
                                <div class="report-title">Tax Liability Analysis</div>
                                <div class="report-desc">Detailed breakdown of tax liabilities by tax type</div>
                            </div>
                            
                            <div class="report-card" onclick="generateReport('e-invoice-status')">
                                <div class="report-icon">🧾</div>
                                <div class="report-title">E-Invoice Status Report</div>
                                <div class="report-desc">Track e-invoice implementation and compliance status</div>
                            </div>
                            
                            <div class="report-card" onclick="generateReport('vendor-compliance')">
                                <div class="report-icon">🔍</div>
                                <div class="report-title">Vendor Compliance Report</div>
                                <div class="report-desc">Monitor filing status and compliance of your vendors</div>
                            </div>
                            
                            <div class="report-card" onclick="generateReport('gstr1-gstr3b-reconciliation')">
                                <div class="report-icon">🔄</div>
                                <div class="report-title">GSTR1 vs GSTR3B Reconciliation</div>
                                <div class="report-desc">Identify mismatches between GSTR1 and GSTR3B filings</div>
                            </div>
                            
                            <div class="report-card" onclick="generateReport('reverse-charge')">
                                <div class="report-icon">↩️</div>
                                <div class="report-title">Reverse Charge Report</div>
                                <div class="report-desc">Analysis of purchases under reverse charge mechanism</div>
                            </div>
                            
                            <div class="report-card" onclick="generateReport('custom-report')">
                                <div class="report-icon">⚙️</div>
                                <div class="report-title">Custom Report</div>
                                <div class="report-desc">Create your own customized report with specific parameters</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer>
        <div class="container">
            <p>© 2024 GST Returns Processor | All Rights Reserved</p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // DOM Elements
        const uploadArea = document.getElementById('upload-area');
        const fileInput = document.getElementById('file-input');
        const fileList = document.getElementById('file-list');
        const progressBar = document.getElementById('progress-bar');
        const processingStatus = document.getElementById('processing-status');
        const resultMessage = document.getElementById('result-message');
        const clearBtn = document.getElementById('clear-btn');
        const processBtn = document.getElementById('process-btn');
        const previewBtn = document.getElementById('preview-btn');
        const dataPreview = document.getElementById('data-preview');
        
        // Store uploaded files
        let uploadedFiles = [];
        
        // Event Listeners for drag and drop
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            uploadArea.classList.add('dragover');
        }
        
        function unhighlight() {
            uploadArea.classList.remove('dragover');
        }
        
        // Handle file drop
        uploadArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const files = e.dataTransfer.files;
            handleFiles(files);
        }
        
        // Handle file input change
        fileInput.addEventListener('change', function() {
            handleFiles(this.files);
        });
        
        // Process the files
        function handleFiles(files) {
            if (files.length === 0) return;
            
            [...files].forEach(file => {
                if (file.type === "application/json" || file.name.endsWith('.json')) {
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                        try {
                            const jsonData = JSON.parse(e.target.result);
                            let fileType = determineGstFileType(jsonData);
                            
                            if (fileType) {
                                // Check if we already have a file of this type
                                const existingFile = uploadedFiles.find(f => f.type === fileType);
                                if (existingFile) {
                                    // If this file is for a different period, allow it
                                    const existingPeriod = getPeriodFromFile(existingFile.data);
                                    const newPeriod = getPeriodFromFile(jsonData);
                                    
                                    if (existingPeriod === newPeriod) {
                                        showResult(`Warning: A ${fileType} file for the same period is already uploaded. The new file will replace it.`, 'warning');
                                        // Remove the existing file
                                        uploadedFiles = uploadedFiles.filter(f => !(f.type === fileType && getPeriodFromFile(f.data) === newPeriod));
                                        // Remove from DOM
                                        removeFileFromList(existingFile.name);
                                                                                // Add the new file
                                        addFileToList(file.name, fileType);
                                        uploadedFiles.push({ name: file.name, type: fileType, data: jsonData });
                                    } else {
                                        // Different periods, just add the new file
                                        addFileToList(file.name, fileType);
                                        uploadedFiles.push({ name: file.name, type: fileType, data: jsonData });
                                    }
                                } else {
                                    // No existing file of this type, just add it
                                    addFileToList(file.name, fileType);
                                    uploadedFiles.push({ name: file.name, type: fileType, data: jsonData });
                                }
                            } else {
                                showResult(`Error: File "${file.name}" does not seem to be a valid GST return file.`, 'danger');
                            }
                        } catch (error) {
                            showResult(`Error reading file "${file.name}": ${error.message}`, 'danger');
                        }
                    };
                    
                    reader.readAsText(file);
                } else {
                    showResult(`Error: File "${file.name}" is not a valid JSON file. Please upload a JSON file.`, 'danger');
                }
            });
            
            updateButtonStates();
        }
        
        // Determine the type of GST file
        function determineGstFileType(data) {
            if (data.gstin && data.b2b) return 'gstr1';
            if (data.gstin && data.b2bur) return 'gstr2a';
            if (data.gstin && data.cdnr) return 'gstr3b';
            return null;
        }
        
        // Get the period from the file data
        function getPeriodFromFile(data) {
            if (data.gstin && data.b2b) return data.b2b[0]?.inv?.[0]?.idt.split('-')[1] + '-' + data.b2b[0]?.inv?.[0]?.idt.split('-')[2];
            if (data.gstin && data.b2bur) return data.b2bur[0]?.inum?.split('-')[1] + '-' + data.b2bur[0]?.inum?.split('-')[2];
            if (data.gstin && data.cdnr) return data.cdnr[0]?.nt?.[0]?.ntdt.split('-')[1] + '-' + data.cdnr[0]?.nt?.[0]?.ntdt.split('-')[2];
            return null;
        }
        
        // Add file to the list in the UI
        function addFileToList(fileName, fileType) {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            fileItem.innerHTML = `
                <div class="file-name">
                    <span>${fileName}</span>
                    <span class="file-badge badge-${fileType}">${fileType.toUpperCase()}</span>
                </div>
                <button class="btn btn-sm btn-outline-danger" onclick="removeFile('${fileName}')">Remove</button>
            `;
            fileList.appendChild(fileItem);
        }
        
        // Remove file from the list in the UI
        function removeFileFromList(fileName) {
            const fileItems = fileList.querySelectorAll('.file-item');
            fileItems.forEach(item => {
                if (item.querySelector('.file-name span:first-child').innerText === fileName) {
                    fileList.removeChild(item);
                }
            });
        }
        
        // Remove a file from the uploaded files array
        function removeFile(fileName) {
            uploadedFiles = uploadedFiles.filter(file => file.name !== fileName);
            removeFileFromList(fileName);
            updateButtonStates();
        }
        
        // Clear all uploaded files
        clearBtn.addEventListener('click', function() {
            uploadedFiles = [];
            fileList.innerHTML = '';
            updateButtonStates();
        });
        
        // Update button states based on the number of uploaded files
        function updateButtonStates() {
            if (uploadedFiles.length > 0) {
                previewBtn.disabled = false;
                processBtn.disabled = false;
            } else {
                previewBtn.disabled = true;
                processBtn.disabled = true;
            }
        }
        
        // Show result message
        function showResult(message, type) {
            resultMessage.innerHTML = `<p class="alert alert-${type}">${message}</p>`;
            resultMessage.style.display = 'block';
            setTimeout(() => {
                resultMessage.style.display = 'none';
            }, 5000);
        }
        
        // Preview data
        previewBtn.addEventListener('click', function() {
            dataPreview.style.display = 'block';
            populatePreviewData();
        });
        
        // Populate preview data
        function populatePreviewData() {
            const gstr1Data = uploadedFiles.find(file => file.type === 'gstr1')?.data?.b2b || [];
            const gstr2aData = uploadedFiles.find(file => file.type === 'gstr2a')?.data?.b2bur || [];
            const gstr3bData = uploadedFiles.find(file => file.type === 'gstr3b')?.data?.cdnr || [];
            
            populateTable('gstr1-table', gstr1Data, 'b2b');
            populateTable('gstr2a-table', gstr2aData, 'b2bur');
            populateTable('gstr3b-table', gstr3bData, 'cdnr');
            
            populateSummary(gstr1Data, gstr2aData, gstr3bData);
        }
        
        // Populate table with data
        function populateTable(tableId, data, key) {
            const tableBody = document.getElementById(tableId).querySelector('tbody');
            tableBody.innerHTML = '';
            
            data.forEach(item => {
                item.inv.forEach(inv => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${inv.ctin}</td>
                        <td>${inv.inum}</td>
                        <td>${inv.idt}</td>
                        <td>₹${parseFloat(inv.val).toFixed(2)}</td>
                        <td>₹${parseFloat(inv.txval).toFixed(2)}</td>
                        <td>₹${parseFloat(inv.camt).toFixed(2)}</td>
                        <td>₹${parseFloat(inv.samt).toFixed(2)}</td>
                        <td>₹${parseFloat(inv.iamt).toFixed(2)}</td>
                        <td>₹${parseFloat(inv.txval + inv.camt + inv.samt + inv.iamt).toFixed(2)}</td>
                    `;
                    tableBody.appendChild(row);
                });
            });
        }
        
        // Populate summary with data
        function populateSummary(gstr1Data, gstr2aData, gstr3bData) {
            let gstr1InvoiceCount = 0, gstr1TotalValue = 0, gstr1TotalTax = 0, gstr1TaxableValue = 0;
            let gstr2aInvoiceCount = 0, gstr2aTotalValue = 0, gstr2aTotalTax = 0, gstr2aTaxableValue = 0;
            let gstr3bOutputTax = 0, gstr3bTotalItc = 0, gstr3bTaxPaid = 0, gstr3bItcUtilized = 0;
            
            gstr1Data.forEach(item => {
                item.inv.forEach(inv => {
                    gstr1InvoiceCount++;
                    gstr1TotalValue += parseFloat(inv.val);
                    gstr1TotalTax += parseFloat(inv.camt) + parseFloat(inv.samt) + parseFloat(inv.iamt);
                    gstr1TaxableValue += parseFloat(inv.txval);
                });
            });
            
            gstr2aData.forEach(item => {
                item.inum.forEach(inv => {
                    gstr2aInvoiceCount++;
                    gstr2aTotalValue += parseFloat(inv.val);
                    gstr2aTotalTax += parseFloat(inv.camt) + parseFloat(inv.samt) + parseFloat(inv.iamt);
                    gstr2aTaxableValue += parseFloat(inv.txval);
                });
            });
            
            gstr3bData.forEach(item => {
                item.nt.forEach(nt => {
                    gstr3bOutputTax += parseFloat(nt.itc?.txval) || 0;
                    gstr3bTotalItc += parseFloat(nt.itc?.camt) + parseFloat(nt.itc?.samt) + parseFloat(nt.itc?.iamt) || 0;
                    gstr3bTaxPaid += parseFloat(nt.itc?.camt) + parseFloat(nt.itc?.samt) + parseFloat(nt.itc?.iamt) || 0;
                    gstr3bItcUtilized += parseFloat(nt.itc?.camt) + parseFloat(nt.itc?.samt) + parseFloat(nt.iamt) || 0;
                });
            });
            
            document.getElementById('gstr1-invoice-count').innerText = gstr1InvoiceCount;
            document.getElementById('gstr1-total-value').innerText = `₹${gstr1TotalValue.toFixed(2)}`;
            document.getElementById('gstr1-total-tax').innerText = `₹${gstr1TotalTax.toFixed(2)}`;
            document.getElementById('gstr1-taxable-value').innerText = `₹${gstr1TaxableValue.toFixed(2)}`;
            
            document.getElementById('gstr2a-invoice-count').innerText = gstr2aInvoiceCount;
            document.getElementById('gstr2a-total-value').innerText = `₹${gstr2aTotalValue.toFixed(2)}`;
            document.getElementById('gstr2a-total-tax').innerText = `₹${gstr2aTotalTax.toFixed(2)}`;
            document.getElementById('gstr2a-taxable-value').innerText = `₹${gstr2aTaxableValue.toFixed(2)}`;
            
            document.getElementById('gstr3b-output-tax').innerText = `₹${gstr3bOutputTax.toFixed(2)}`;
            document.getElementById('gstr3b-total-itc').innerText = `₹${gstr3bTotalItc.toFixed(2)}`;
            document.getElementById('gstr3b-tax-paid').innerText = `₹${gstr3bTaxPaid.toFixed(2)}`;
            document.getElementById('gstr3b-itc-utilized').innerText = `₹${gstr3bItcUtilized.toFixed(2)}`;
            
            // Reconciliation logic
            const gstr1VsGstr3b = gstr1TotalTax === gstr3bOutputTax ? 'Balanced' : 'Unbalanced';
            const gstr2aVsItc = gstr2aTotalTax === gstr3bTotalItc ? 'Balanced' : 'Unbalanced';
            const reconciliationStatus = gstr1VsGstr3b === 'Balanced' && gstr2aVsItc === 'Balanced' ? 'All Balanced' : 'Some Unbalanced';
            
            document.getElementById('reconciliation-1-3b').innerText = gstr1VsGstr3b;
            document.getElementById('reconciliation-2a-itc').innerText = gstr2aVsItc;
            document.getElementById('reconciliation-status').innerText = reconciliationStatus;
        }
        
        // Process to Excel
        processBtn.addEventListener('click', function() {
            processingStatus.style.display = 'block';
            processBtn.disabled = true;
            clearBtn.disabled = true;
            
            setTimeout(() => {
                try {
                    const workbook = XLSX.utils.book_new();
                    
                    const gstr1Data = uploadedFiles.find(file => file.type === 'gstr1')?.data?.b2b || [];
                    const gstr2aData = uploadedFiles.find(file => file.type === 'gstr2a')?.data?.b2bur || [];
                    const gstr3bData = uploadedFiles.find(file => file.type === 'gstr3b')?.data?.cdnr || [];
                    
                    const gstr1Sheet = XLSX.utils.json_to_sheet(flattenData(gstr1Data, 'b2b'));
                    const gstr2aSheet = XLSX.utils.json_to_sheet(flattenData(gstr2aData, 'b2bur'));
                    const gstr3bSheet = XLSX.utils.json_to_sheet(flattenData(gstr3bData, 'cdnr'));
                    
                    XLSX.utils.book_append_sheet(workbook, gstr1Sheet, 'GSTR1');
                    XLSX.utils.book_append_sheet(workbook, gstr2aSheet, 'GSTR2A');
                    XLSX.utils.book_append_sheet(workbook, gstr3bSheet, 'GSTR3B');
                    
                    XLSX.writeFile(workbook, 'GST_Returns_Processed.xlsx');
                    
                    showResult('Your GST returns data has been successfully processed and exported to an Excel file.', 'success');
                } catch (error) {
                    showResult(`Error processing files: ${error.message}`, 'danger');
                } finally {
                    processingStatus.style.display = 'none';
                    processBtn.disabled = false;
                    clearBtn.disabled = false;
                }
            }, 2000); // Simulate processing time
        });
        
        // Flatten data for Excel export
        function flattenData(data, key) {
            const flattenedData = [];
            
            data.forEach(item => {
                item.inv.forEach(inv => {
                    flattenedData.push({
                        'Customer GSTIN': inv.ctin,
                        'Invoice Number': inv.inum,
                        'Invoice Date': inv.idt,
                        'Invoice Value': parseFloat(inv.val),
                        'Taxable Value': parseFloat(inv.txval),
                        'CGST': parseFloat(inv.camt),
                        'SGST': parseFloat(inv.samt),
                        'IGST': parseFloat(inv.iamt),
                        'Total Tax': parseFloat(inv.txval) + parseFloat(inv.camt) + parseFloat(inv.samt) + parseFloat(inv.iamt)
                    });
                });
            });
            
            return flattenedData;
        }
        
        // Generate report
        function generateReport(reportType) {
            switch (reportType) {
                case 'b2b-invoice-matching':
                    showResult('Generating B2B Invoice Matching Report...', 'info');
                    break;
                case 'hsn-summary':
                    showResult('Generating HSN Summary Report...', 'info');
                    break;
                case 'itc-eligibility':
                    showResult('Generating ITC Eligibility Report...', 'info');
                    break;
                case 'tax-liability':
                    showResult('Generating Tax Liability Analysis Report...', 'info');
                    break;
                case 'e-invoice-status':
                    showResult('Generating E-Invoice Status Report...', 'info');
                    break;
                case 'vendor-compliance':
                    showResult('Generating Vendor Compliance Report...', 'info');
                    break;
                case 'gstr1-gstr3b-reconciliation':
                    showResult('Generating GSTR1 vs GSTR3B Reconciliation Report...', 'info');
                    break;
                case 'reverse-charge':
                    showResult('Generating Reverse Charge Report...', 'info');
                    break;
                case 'custom-report':
                    showResult('Generating Custom Report...', 'info');
                    break;
                default:
                    showResult('Unknown report type selected.', 'danger');
            }
            
            // Simulate report generation time
            setTimeout(() => {
                showResult('Report generated successfully!', 'success');
            }, 3000);
        }
    </script>
</body>
</html> Improve fully workable in all way do not left out anything