<main class="main-content" id="mainContent">
    <header class="main-header">
        <h1>PORTFOLIO UPLOAD</h1>
        <p class="welcome-text">Upload PDF portfolios and extract model data automatically</p>
    </header>

    <div class="content-area">
        <div class="upload-container">
            <!-- Project Name Input -->
            <div class="form-group">
                <label for="projectName" style="font-weight: 700; margin-bottom: 10px; display: block;">Project Name</label>
                <input type="text" id="projectName" class="form-input" placeholder="Enter project name..." style="padding: 12px; border: 2px dashed #007bff; border-radius: 8px; width: 100%;">
            </div>

            <!-- Drag & Drop Area -->
            <div id="dropZone" class="drop-zone">
                <div class="drop-content">
                    <i class="fas fa-cloud-upload-alt" style="font-size: 48px; color: #007bff; margin-bottom: 20px;"></i>
                    <h3>Drag & Drop PDF Files Here</h3>
                    <p>Upload up to 100 PDF files at once</p>
                    <p class="file-info">Supported: PDF files only</p>
                    <button class="browse-btn" onclick="document.getElementById('pdfFiles').click()">
                        <i class="fas fa-folder-open"></i> Browse Files
                    </button>
                </div>
                <input type="file" id="pdfFiles" multiple accept=".pdf" style="display: none;">
            </div>

            <!-- File List -->
            <div id="fileList" class="file-list" style="display: none;">
                <h4>Selected Files:</h4>
                <div id="fileItems"></div>
                <div class="file-stats">
                    <div>Total Files: <span id="fileCount">0</span></div>
                    <div>Total Size: <span id="totalSize">0 MB</span></div>
                </div>
            </div>

            <!-- Upload Button -->
            <button id="uploadBtn" class="upload-btn" disabled>
                <i class="fas fa-upload"></i> Process PDFs
            </button>

            <!-- Processing Progress -->
            <div id="processingProgress" class="progress-container" style="display: none;">
                <h4>Processing PDFs...</h4>
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
                <div class="progress-text">Extracting images and data...</div>
            </div>

            <!-- Results Section -->
            <div id="resultsSection" class="results-section" style="display: none;">
                <h4>Processing Complete!</h4>
                <div id="resultsContent"></div>
                <button id="viewDetailsBtn" class="view-details-btn">
                    <i class="fas fa-chart-bar"></i> View Detailed Results
                </button>
            </div>
        </div>
    </div>
</main>

<style>
.upload-container {
    max-width: 800px;
    margin: 0 auto;
}

.drop-zone {
    border: 3px dashed #007bff;
    border-radius: 12px;
    padding: 40px 20px;
    text-align: center;
    background: #f8f9fa;
    transition: all 0.3s ease;
    margin: 20px 0;
}

.drop-zone.dragover {
    background: #e3f2fd;
    border-color: #0056b3;
}

.drop-content h3 {
    color: #333;
    margin-bottom: 10px;
    font-weight: 700;
}

.drop-content p {
    color: #666;
    margin: 5px 0;
}

.file-info {
    font-size: 12px;
    color: #999;
}

.browse-btn {
    background: #007bff;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    cursor: pointer;
    font-weight: 600;
    margin-top: 15px;
    transition: background 0.3s ease;
}

.browse-btn:hover {
    background: #0056b3;
}

.file-list {
    background: white;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
}

.file-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #f0f0f0;
}

.file-item:last-child {
    border-bottom: none;
}

.file-name {
    font-weight: 600;
}

.file-size {
    color: #666;
    font-size: 12px;
}

.file-stats {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 2px solid #007bff;
    font-weight: 600;
}

.upload-btn {
    background: #28a745;
    color: white;
    border: none;
    padding: 15px 30px;
    border-radius: 8px;
    cursor: pointer;
    font-weight: 700;
    font-size: 16px;
    width: 100%;
    transition: background 0.3s ease;
}

.upload-btn:disabled {
    background: #6c757d;
    cursor: not-allowed;
}

.upload-btn:not(:disabled):hover {
    background: #218838;
}

.progress-container {
    background: white;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
}

.progress-bar {
    width: 100%;
    height: 20px;
    background: #f0f0f0;
    border-radius: 10px;
    overflow: hidden;
    margin: 10px 0;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #007bff, #0056b3);
    width: 0%;
    transition: width 0.3s ease;
}

.progress-text {
    text-align: center;
    font-weight: 600;
    color: #333;
}

.results-section {
    background: white;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
}

.view-details-btn {
    background: #007bff;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    cursor: pointer;
    font-weight: 600;
    margin-top: 15px;
}

.view-details-btn:hover {
    background: #0056b3;
}
</style>

<script>
let selectedFiles = [];

document.addEventListener('DOMContentLoaded', function() {
    const dropZone = document.getElementById('dropZone');
    const fileInput = document.getElementById('pdfFiles');
    const fileList = document.getElementById('fileList');
    const fileItems = document.getElementById('fileItems');
    const fileCount = document.getElementById('fileCount');
    const totalSize = document.getElementById('totalSize');
    const uploadBtn = document.getElementById('uploadBtn');
    const projectNameInput = document.getElementById('projectName');

    // Drag and drop functionality
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, unhighlight, false);
    });

    function highlight() {
        dropZone.classList.add('dragover');
    }

    function unhighlight() {
        dropZone.classList.remove('dragover');
    }

    dropZone.addEventListener('drop', handleDrop, false);
    fileInput.addEventListener('change', handleFileSelect, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles(files);
    }

    function handleFileSelect(e) {
        const files = e.target.files;
        handleFiles(files);
    }

    function handleFiles(files) {
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            if (file.type === 'application/pdf') {
                selectedFiles.push(file);
            }
        }
        updateFileList();
    }

    function updateFileList() {
        fileItems.innerHTML = '';
        let totalSizeBytes = 0;

        selectedFiles.forEach((file, index) => {
            totalSizeBytes += file.size;
            
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            fileItem.innerHTML = `
                <div>
                    <span class="file-name">${file.name}</span>
                    <div class="file-size">${formatBytes(file.size)}</div>
                </div>
                <button onclick="removeFile(${index})" style="background: #dc3545; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer;">
                    <i class="fas fa-times"></i>
                </button>
            `;
            fileItems.appendChild(fileItem);
        });

        fileCount.textContent = selectedFiles.length;
        totalSize.textContent = formatBytes(totalSizeBytes);
        
        fileList.style.display = selectedFiles.length > 0 ? 'block' : 'none';
        uploadBtn.disabled = selectedFiles.length === 0 || !projectNameInput.value.trim();
    }

    window.removeFile = function(index) {
        selectedFiles.splice(index, 1);
        updateFileList();
    }

    projectNameInput.addEventListener('input', function() {
        uploadBtn.disabled = selectedFiles.length === 0 || !this.value.trim();
    });

    uploadBtn.addEventListener('click', processFiles);
});

function formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function processFiles() {
    const projectName = document.getElementById('projectName').value.trim();
    if (!projectName) {
        alert('Please enter a project name');
        return;
    }

    const formData = new FormData();
    formData.append('project_name', projectName);
    
    selectedFiles.forEach(file => {
        formData.append('pdf_files[]', file);
    });

    const progressContainer = document.getElementById('processingProgress');
    const progressFill = document.querySelector('.progress-fill');
    const progressText = document.querySelector('.progress-text');
    
    progressContainer.style.display = 'block';
    progressFill.style.width = '0%';

    // Simulate progress
    let progress = 0;
    const progressInterval = setInterval(() => {
        progress += Math.random() * 10;
        if (progress > 90) progress = 90;
        progressFill.style.width = progress + '%';
    }, 500);

    fetch('<?php echo base_url("portfolio/upload_pdf"); ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        clearInterval(progressInterval);
        progressFill.style.width = '100%';
        progressText.textContent = 'Processing Complete!';

        if (data.success) {
            showResults(data);
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        clearInterval(progressInterval);
        alert('Upload failed: ' + error);
    });
}

function showResults(data) {
    const resultsSection = document.getElementById('resultsSection');
    const resultsContent = document.getElementById('resultsContent');
    
    let countdown = 5;
    
    resultsContent.innerHTML = `
        <div style="background: #d4edda; color: #155724; padding: 15px; border-radius: 6px; margin-bottom: 15px;">
            <strong>Success!</strong> Processed ${data.processed_files} PDF files
        </div>
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-top: 15px;">
            <div style="background: #e3f2fd; padding: 15px; border-radius: 6px; text-align: center;">
                <div style="font-size: 24px; font-weight: 700; color: #007bff;">${data.processed_files}</div>
                <div style="font-size: 12px; color: #666;">PDF Files</div>
            </div>
            <div style="background: #e8f5e8; padding: 15px; border-radius: 6px; text-align: center;">
                <div style="font-size: 24px; font-weight: 700; color: #28a745;">${data.total_size}</div>
                <div style="font-size: 12px; color: #666;">Total Size</div>
            </div>
            <div style="background: #fff3cd; padding: 15px; border-radius: 6px; text-align: center;">
                <div style="font-size: 24px; font-weight: 700; color: #856404;">${data.processing_result.models ? data.processing_result.models.length : 0}</div>
                <div style="font-size: 12px; color: #666;">Models Found</div>
            </div>
        </div>
        <div style="margin-top: 20px; text-align: center; padding: 15px; background: #f8f9fa; border-radius: 6px;">
            <p style="margin-bottom: 15px; font-weight: 600;">Redirecting to results in <span id="countdown">${countdown}</span> seconds...</p>
            <button onclick="viewDetailedResults()" style="background: #007bff; color: white; border: none; padding: 12px 24px; border-radius: 6px; cursor: pointer; font-weight: 600; margin-right: 10px;">
                <i class="fas fa-chart-bar"></i> View Results Now
            </button>
            <button onclick="stopRedirect()" style="background: #6c757d; color: white; border: none; padding: 12px 24px; border-radius: 6px; cursor: pointer; font-weight: 600;">
                <i class="fas fa-times"></i> Cancel Auto-Redirect
            </button>
        </div>
    `;
    
    resultsSection.style.display = 'block';
    
    // Auto-redirect countdown
    const countdownInterval = setInterval(() => {
        countdown--;
        document.getElementById('countdown').textContent = countdown;
        
        if (countdown <= 0) {
            clearInterval(countdownInterval);
            viewDetailedResults();
        }
    }, 1000);
    
    // Store interval ID to allow cancellation
    window.redirectInterval = countdownInterval;
}

function stopRedirect() {
    clearInterval(window.redirectInterval);
    document.querySelector('#resultsSection p').textContent = 'Auto-redirect cancelled. Click "View Results Now" to see the results.';
}

function viewDetailedResults() {
    if (window.redirectInterval) {
        clearInterval(window.redirectInterval);
    }
    window.location.href = '<?php echo base_url("portfolio/results"); ?>';
}

function processMoreFiles() {
    if (window.redirectInterval) {
        clearInterval(window.redirectInterval);
    }
    // Reset the form
    selectedFiles = [];
    document.getElementById('projectName').value = '';
    document.getElementById('fileList').style.display = 'none';
    document.getElementById('resultsSection').style.display = 'none';
    document.getElementById('processingProgress').style.display = 'none';
    document.getElementById('pdfFiles').value = '';
    updateFileList();
}
</script>