fix this code issues actually this code not working correct please fix this code issue 


i want to extract the data form the uploaded document and highlight the data according his sentiment 
with the download option after showing that the file data sentiment 



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Sentiment Analysis Tool</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <header>
            <h1>Sentiment Analysis Tool</h1>
            <p>Upload any document to analyze its sentiment</p>
        </header>

        <main>
            <section class="upload-section">
                <div class="upload-area" id="uploadArea">
                    <svg class="upload-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path d="M12 15V3m0 0l-4 4m4-4l4 4M2 17l.621 2.485A2 2 0 004.561 21h14.878a2 2 0 001.94-1.515L22 17"></path>
                    </svg>
                    <p>Drop your file here or click to browse</p>
                    <p class="file-types">Supported: .txt, .csv, .json, .xlsx, .pdf, .html, .xml</p>
                    <input type="file" id="fileInput" accept=".txt,.csv,.json,.xlsx,.pdf,.html,.xml" hidden>
                </div>
            </section>

            <section class="analysis-section" id="analysisSection" hidden>
                <div class="stats-container">
                    <div class="stat-card positive">
                        <h3>Positive</h3>
                        <p class="stat-value" id="positiveCount">0</p>
                    </div>
                    <div class="stat-card negative">
                        <h3>Negative</h3>
                        <p class="stat-value" id="negativeCount">0</p>
                    </div>
                    <div class="stat-card neutral">
                        <h3>Neutral</h3>
                        <p class="stat-value" id="neutralCount">0</p>
                    </div>
                </div>

                <div class="controls">
                    <button class="btn btn-primary" id="downloadBtn">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <path d="M12 15V3m0 12l-4-4m4 4l4-4M2 17l.621 2.485A2 2 0 004.561 21h14.878a2 2 0 001.94-1.515L22 17"></path>
                        </svg>
                        Download Highlighted
                    </button>
                    <button class="btn btn-secondary" id="resetBtn">Reset</button>
                </div>

                <div class="result-container" id="resultContainer"></div>
            </section>
        </main>

        <div class="loading" id="loading" hidden>
            <div class="spinner"></div>
            <p>Analyzing sentiment...</p>
        </div>
    </div>

    <!-- External Libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
    <script>pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';</script>
    
    <!-- Sentiment Analysis -->
    <script src="sentiment.js"></script>
    
    <!-- Main Application -->
    <script type="module" src="app.js"></script>
</body>
</html>








// File Processor Module (No changes here)
const FileProcessor = (() => {
    const processors = new Map([
        ['txt', async (file) => file.text()],
        ['csv', async (file) => {
            const text = await file.text();
            const result = Papa.parse(text);
            return result.data.flat().join(' ');
        }],
        ['json', async (file) => {
            const text = await file.text();
            const data = JSON.parse(text);
            return JSON.stringify(data, null, 2);
        }],
        ['xlsx', async (file) => {
            const arrayBuffer = await file.arrayBuffer();
            const workbook = XLSX.read(arrayBuffer);
            const texts = [];

            for (const sheetName of workbook.SheetNames) {
                const worksheet = workbook.Sheets[sheetName];
                const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                texts.push(...data.flat().filter(Boolean));
            }

            return texts.join(' ');
        }],
        ['html', async (file) => {
            const text = await file.text();
            const parser = new DOMParser();
            const doc = parser.parseFromString(text, 'text/html');
            return doc.body.textContent || '';
        }],
        ['xml', async (file) => {
            const text = await file.text();
            const parser = new DOMParser();
            const doc = parser.parseFromString(text, 'text/xml');
            return doc.textContent || '';
        }],
        ['pdf', async (file) => {
            const arrayBuffer = await file.arrayBuffer();
            const pdf = await pdfjsLib.getDocument(arrayBuffer).promise;
            const texts = [];

            for (let i = 1; i <= pdf.numPages; i++) {
                const page = await pdf.getPage(i);
                const content = await page.getTextContent();
                const pageText = content.items.map(item => item.str).join(' ');
                texts.push(pageText);
            }

            return texts.join(' ');
        }]
    ]);

    const process = async (file) => {
        const extension = file.name.split('.').pop().toLowerCase();
        const processor = processors.get(extension);

        if (!processor) {
            throw new Error(`Unsupported file type: ${extension}`);
        }

        return processor(file);
    };

    return { process };
})();

// Sentiment Analyzer Module (No changes here)
const SentimentAnalyzer = (() => {
    const analyzeText = (text) => {
        // This regex tries to split by common sentence terminators, keeping the terminator.
        // It's a simplification and might not be perfect for all cases.
        const sentences = text.match(/[^.!?]+[.!?]|\S+/g) || [text];
        const results = [];

        for (const sentence of sentences) {
            const trimmed = sentence.trim();
            if (!trimmed) continue;

            const analysis = Sentiment.analyze(trimmed);
            results.push({
                text: trimmed,
                score: analysis.score,
                sentiment: analysis.score > 0 ? 'positive' :
                          analysis.score < 0 ? 'negative' : 'neutral'
            });
        }

        return results;
    };

    const getStatistics = (results) => {
        const stats = {
            positive: 0,
            negative: 0,
            neutral: 0
        };

        for (const result of results) {
            stats[result.sentiment]++;
        }

        return stats;
    };

    return { analyzeText, getStatistics };
})();

// UI Controller Module - MODIFIED
const UIController = (() => {
    const elements = {
        uploadArea: document.getElementById('uploadArea'),
        fileInput: document.getElementById('fileInput'),
        analysisSection: document.getElementById('analysisSection'),
        resultContainer: document.getElementById('resultContainer'),
        loading: document.getElementById('loading'),
        downloadBtn: document.getElementById('downloadBtn'),
        resetBtn: document.getElementById('resetBtn'),
        positiveCount: document.getElementById('positiveCount'),
        negativeCount: document.getElementById('negativeCount'),
        neutralCount: document.getElementById('neutralCount')
    };

    const showLoading = () => {
        elements.loading.hidden = false;
        disableUpload(); // Disable upload when loading starts
    };

    const hideLoading = () => {
        elements.loading.hidden = true;
        enableUpload(); // Re-enable upload after loading completes (unless reset is clicked)
    };

    const showAnalysis = () => {
        elements.analysisSection.hidden = false;
    };

    const hideAnalysis = () => {
        elements.analysisSection.hidden = true;
    };

    const updateStatistics = (stats) => {
        elements.positiveCount.textContent = stats.positive;
        elements.negativeCount.textContent = stats.negative;
        elements.neutralCount.textContent = stats.neutral;
    };

    const displayResults = (results) => {
        elements.resultContainer.innerHTML = '';

        for (const result of results) {
            const paragraph = document.createElement('p');
            const span = document.createElement('span');
            span.className = `sentiment-${result.sentiment}`;
            span.textContent = result.text;
            paragraph.appendChild(span);
            elements.resultContainer.appendChild(paragraph);
        }
    };

    const disableUpload = () => {
        elements.uploadArea.classList.add('disabled');
        elements.fileInput.disabled = true;
    };

    const enableUpload = () => {
        elements.uploadArea.classList.remove('disabled');
        elements.fileInput.disabled = false;
    };

    const reset = () => {
        hideAnalysis();
        elements.resultContainer.innerHTML = '';
        elements.fileInput.value = ''; // Clear file input
        enableUpload(); // Re-enable upload on reset
    };

    return {
        elements,
        showLoading,
        hideLoading,
        showAnalysis,
        hideAnalysis,
        updateStatistics,
        displayResults,
        reset,
        disableUpload, // Expose for initial state control if needed
        enableUpload   // Expose for initial state control if needed
    };
})();

// File Handler Module - MODIFIED
const FileHandler = (() => {
    let currentResults = [];

    const handleFile = async (file) => {
        if (!file) return; // Ensure a file exists

        UIController.reset(); // Reset UI before processing new file to clear previous results
        // UIController.showLoading() is called inside handleFile to disable upload area immediately
        // and show spinner.

        try {
            UIController.showLoading();

            const text = await FileProcessor.process(file);
            const results = SentimentAnalyzer.analyzeText(text);
            const stats = SentimentAnalyzer.getStatistics(results);

            currentResults = results;

            UIController.updateStatistics(stats);
            UIController.displayResults(results);
            UIController.showAnalysis();
        } catch (error) {
            console.error('Error processing file:', error);
            alert(`Error: ${error.message}`);
        } finally {
            UIController.hideLoading(); // Hide loading and re-enable upload area
        }
    };

    const downloadResults = () => {
        if (!currentResults.length) return;

        const html = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Sentiment Analysis Results</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; line-height: 1.6; }
        .sentiment-positive { background-color: #d1fae5; color: #065f46; padding: 2px 6px; border-radius: 4px; }
        .sentiment-negative { background-color: #fee2e2; color: #991b1b; padding: 2px 6px; border-radius: 4px; }
        .sentiment-neutral { background-color: #f3f4f6; color: #374151; padding: 2px 6px; border-radius: 4px; }
        p { margin-bottom: 10px; }
    </style>
</head>
<body>
    <h1>Sentiment Analysis Results</h1>
    ${currentResults.map(result =>
        `<p><span class="sentiment-${result.sentiment}">${result.text}</span></p>`
    ).join('')}
</body>
</html>`;

        const blob = new Blob([html], { type: 'text/html' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'sentiment-analysis-results.html';
        a.click();
        URL.revokeObjectURL(url);
    };

    return { handleFile, downloadResults };
})();

// Event Handlers Setup
const setupEventHandlers = () => {
    const { elements } = UIController;

    // File input change
    elements.fileInput.addEventListener('change', (e) => {
        const file = e.target.files?.[0];
        if (file) FileHandler.handleFile(file);
    });

    // Upload area click
    elements.uploadArea.addEventListener('click', () => {
        // Only trigger click if not disabled
        if (!elements.uploadArea.classList.contains('disabled')) {
            elements.fileInput.click();
        }
    });

    // Drag and drop
    elements.uploadArea.addEventListener('dragover', (e) => {
        if (!elements.uploadArea.classList.contains('disabled')) {
            e.preventDefault();
            elements.uploadArea.classList.add('drag-over');
        }
    });

    elements.uploadArea.addEventListener('dragleave', () => {
        elements.uploadArea.classList.remove('drag-over');
    });

    elements.uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        elements.uploadArea.classList.remove('drag-over');

        if (!elements.uploadArea.classList.contains('disabled')) {
            const file = e.dataTransfer.files?.[0];
            if (file) FileHandler.handleFile(file);
        }
    });

    // Download button
    elements.downloadBtn.addEventListener('click', FileHandler.downloadResults);

    // Reset button
    elements.resetBtn.addEventListener('click', UIController.reset);
};

// Initialize application
document.addEventListener('DOMContentLoaded', setupEventHandlers);