/* ===== GLOBAL STYLES ===== */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    padding: 20px;
}

.container {
    max-width: 1600px;
    margin: 0 auto;
    background: white;
    border-radius: 10px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.2);
    overflow: hidden;
}

/* ===== HEADER STYLES ===== */
.header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 30px;
    text-align: center;
    position: relative;
}

.header h1 {
    font-size: 2.5em;
    margin-bottom: 10px;
}

.header p {
    font-size: 1.1em;
    opacity: 0.9;
}

.sync-status {
    position: absolute;
    top: 20px;
    right: 20px;
    padding: 8px 15px;
    background: rgba(255,255,255,0.2);
    border-radius: 20px;
    font-size: 0.9em;
    display: flex;
    align-items: center;
    gap: 8px;
}

.sync-indicator {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #4CAF50;
    animation: pulse 2s infinite;
}

.sync-indicator.syncing {
    background: #FFC107;
}

.sync-indicator.offline {
    background: #F44336;
}

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

/* ===== NAVIGATION TABS ===== */
.nav-tabs {
    display: flex;
    background: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
    overflow-x: auto;
}

.nav-tab {
    flex: 1;
    min-width: 150px;
    padding: 20px;
    text-align: center;
    cursor: pointer;
    background: #e9ecef;
    border: none;
    font-size: 1em;
    font-weight: 600;
    transition: all 0.3s ease;
    color: #495057;
}

.nav-tab:hover {
    background: #dee2e6;
}

.nav-tab.active {
    background: white;
    color: #667eea;
    border-bottom: 3px solid #667eea;
}

/* ===== SECTION STYLES ===== */
.section {
    display: none;
    padding: 30px;
}

.section.active {
    display: block;
}

/* ===== FORM STYLES ===== */
.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #333;
    font-size: 0.95em;
}

.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 12px;
    border: 2px solid #e0e0e0;
    border-radius: 6px;
    font-size: 1em;
    transition: border-color 0.3s ease;
    font-family: inherit;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
    outline: none;
    border-color: #667eea;
}

.form-group textarea {
    resize: vertical;
    min-height: 80px;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

/* ===== DRAG AND DROP ZONE ===== */
.drop-zone {
    border: 3px dashed #667eea;
    border-radius: 10px;
    padding: 40px;
    text-align: center;
    background: #f8f9fa;
    transition: all 0.3s ease;
    cursor: pointer;
    margin: 20px 0;
}

.drop-zone:hover,
.drop-zone.drag-over {
    background: #e7f3ff;
    border-color: #764ba2;
}

.drop-zone-icon {
    font-size: 3em;
    margin-bottom: 15px;
}

.drop-zone-text {
    font-size: 1.1em;
    color: #666;
    margin-bottom: 10px;
}

.drop-zone-subtext {
    font-size: 0.9em;
    color: #999;
}

.file-input-hidden {
    display: none;
}

.uploaded-files-list {
    margin-top: 20px;
}

.uploaded-file-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 6px;
    margin-bottom: 10px;
    border: 1px solid #e0e0e0;
}

.uploaded-file-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.file-icon {
    font-size: 1.5em;
}

.file-remove-btn {
    background: #dc3545;
    color: white;
    border: none;
    padding: 5px 15px;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.file-remove-btn:hover {
    background: #c82333;
}

/* ===== BUTTON STYLES ===== */
.btn {
    padding: 12px 30px;
    border: none;
    border-radius: 6px;
    font-size: 1em;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-right: 10px;
    margin-bottom: 10px;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.btn-success {
    background: #28a745;
    color: white;
}

.btn-success:hover {
    background: #218838;
}

.btn-danger {
    background: #dc3545;
    color: white;
}

.btn-danger:hover {
    background: #c82333;
}

.btn-warning {
    background: #ffc107;
    color: #212529;
}

.btn-warning:hover {
    background: #e0a800;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #5a6268;
}

.btn-info {
    background: #17a2b8;
    color: white;
}

.btn-info:hover {
    background: #138496;
}

/* ===== PROJECT LIST STYLES ===== */
.project-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.project-card {
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    background: #f8f9fa;
    transition: all 0.3s ease;
}

.project-card:hover {
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    transform: translateY(-3px);
}

.project-card h3 {
    color: #667eea;
    margin-bottom: 10px;
}

.project-card p {
    margin: 5px 0;
    color: #666;
}

.project-card .project-id {
    font-weight: bold;
    color: #764ba2;
}

/* ===== LINE ITEM STYLES ===== */
.line-item {
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    background: #f8f9fa;
}

.line-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 2px solid #dee2e6;
}

.line-item-category {
    display: inline-block;
    padding: 5px 15px;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.9em;
}

.category-supplies {
    background: #d4edda;
    color: #155724;
}

.category-labor {
    background: #d1ecf1;
    color: #0c5460;
}

.category-administrative {
    background: #fff3cd;
    color: #856404;
}

.line-item-content {
    margin-bottom: 15px;
}

.line-item-content p {
    margin: 8px 0;
    color: #333;
}

.line-item-content strong {
    color: #667eea;
}

.resource-links {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #dee2e6;
}

.resource-link {
    display: inline-block;
    margin: 5px 10px 5px 0;
    padding: 8px 15px;
    background: #667eea;
    color: white;
    text-decoration: none;
    border-radius: 5px;
    font-size: 0.9em;
    transition: all 0.3s ease;
}

.resource-link:hover {
    background: #764ba2;
    transform: translateY(-2px);
}

/* ===== DYNAMIC CATEGORY INPUTS ===== */
.category-inputs {
    background: #e9ecef;
    padding: 20px;
    border-radius: 6px;
    margin-top: 15px;
}

/* ===== ALERT STYLES ===== */
.alert {
    padding: 15px 20px;
    border-radius: 6px;
    margin-bottom: 20px;
    font-weight: 500;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.alert-info {
    background: #d1ecf1;
    color: #0c5460;
    border: 1px solid #bee5eb;
}

.alert-warning {
    background: #fff3cd;
    color: #856404;
    border: 1px solid #ffeaa7;
}

/* ===== MODAL STYLES ===== */
.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    overflow-y: auto;
}

.modal.active {
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal-content {
    background: white;
    padding: 30px;
    border-radius: 10px;
    max-width: 900px;
    width: 90%;
    max-height: 90vh;
    overflow-y: auto;
    box-shadow: 0 10px 40px rgba(0,0,0,0.3);
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #e0e0e0;
}

.modal-close {
    font-size: 2em;
    cursor: pointer;
    color: #999;
    transition: color 0.3s ease;
}

.modal-close:hover {
    color: #333;
}

/* ===== REPORTING STYLES ===== */
.report-summary {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin: 20px 0;
}

.report-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 25px;
    border-radius: 10px;
    text-align: center;
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.report-card h3 {
    font-size: 2em;
    margin-bottom: 10px;
}

.report-card p {
    font-size: 1em;
    opacity: 0.9;
}

.chart-container {
    background: white;
    padding: 20px;
    border-radius: 10px;
    margin: 20px 0;
    border: 2px solid #e0e0e0;
}

.chart-bar {
    display: flex;
    align-items: center;
    margin: 15px 0;
}

.chart-label {
    width: 150px;
    font-weight: 600;
    color: #333;
}

.chart-bar-fill {
    flex: 1;
    height: 30px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 5px;
    position: relative;
    transition: width 0.5s ease;
}

.chart-value {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: white;
    font-weight: 600;
}

/* ===== EXPORT/IMPORT SECTION ===== */
.action-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin: 20px 0;
}

/* ===== SETTINGS PANEL ===== */
.settings-panel {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 10px;
    margin: 20px 0;
}

.settings-group {
    margin-bottom: 20px;
}

.settings-group h3 {
    color: #667eea;
    margin-bottom: 15px;
}

.toggle-switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
}

.toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: .4s;
    border-radius: 34px;
}

.toggle-slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    transition: .4s;
    border-radius: 50%;
}

input:checked + .toggle-slider {
    background-color: #667eea;
}

input:checked + .toggle-slider:before {
    transform: translateX(26px);
}

/* ===== UTILITY CLASSES ===== */
.text-center {
    text-align: center;
}

.mt-20 {
    margin-top: 20px;
}

.mb-20 {
    margin-bottom: 20px;
}

.hidden {
    display: none;
}

.total-cost {
    font-size: 1.5em;
    font-weight: bold;
    color: #28a745;
}

/* ===== FILTER AND SEARCH STYLES ===== */
.filter-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.search-box {
    width: 100%;
    padding: 12px;
    border: 2px solid #e0e0e0;
    border-radius: 6px;
    font-size: 1em;
    margin-bottom: 15px;
}

.no-data {
    text-align: center;
    padding: 40px;
    color: #999;
    font-size: 1.2em;
}

/* ===== PRINT STYLES ===== */
@media print {
    body {
        background: white;
        padding: 0;
    }

    .container {
        box-shadow: none;
    }

    .header {
        background: white;
        color: black;
        border-bottom: 2px solid #333;
    }

    .nav-tabs,
    .btn,
    .sync-status,
    .action-buttons {
        display: none !important;
    }

    .section {
        display: block !important;
        page-break-after: always;
    }

    .project-card,
    .line-item {
        border: 1px solid #333;
        page-break-inside: avoid;
    }
}

/* ===== RESPONSIVE DESIGN ===== */
@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
    }

    .project-list {
        grid-template-columns: 1fr;
    }

    .header h1 {
        font-size: 1.8em;
    }

    .nav-tab {
        font-size: 0.9em;
        padding: 15px 10px;
    }

    .report-summary {
        grid-template-columns: 1fr;
    }

    .sync-status {
        position: static;
        margin-top: 15px;
        justify-content: center;
    }

    .line-item-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .chart-label {
        width: 100px;
        font-size: 0.9em;
    }
}

/* ===== LOADING SPINNER ===== */
.spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #667eea;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 20px auto;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* ===== NOTIFICATION TOAST ===== */
.toast {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: #333;
    color: white;
    padding: 15px 25px;
    border-radius: 8px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.3);
    z-index: 2000;
    animation: slideIn 0.3s ease;
}

.toast.success {
    background: #28a745;
}

.toast.error {
    background: #dc3545;
}

.toast.info {
    background: #17a2b8;
}

@keyframes slideIn {
    from {
        transform: translateX(400px);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

Now I'll create the complete JavaScript file with all functionality:

js

Copy
/**
 * ========================================
 * ENHANCED PROJECT TRACKING APPLICATION
 * ========================================
 * 
 * Version: 2.0
 * Author: Project Tracking System
 * Description: Comprehensive project and line item management system
 * 
 * FEATURES:
 * - Project and line item management
 * - Export/Import (JSON, CSV)
 * - Advanced reporting and analytics
 * - Drag & drop file uploads
 * - Backend API integration
 * - Cloud storage support
 * - Email notifications
 * - Real-time synchronization
 * - Print-friendly views
 * 
 * ARCHITECTURE:
 * - localStorage for offline data persistence
 * - Optional backend API for multi-user support
 * - Cloud storage integration for file uploads
 * - Real-time synchronization with conflict resolution
 */

// ========================================
// GLOBAL CONFIGURATION
// ========================================

let uploadedFiles = []; // Store uploaded files temporarily
let syncInterval = null; // Auto-sync interval
let apiConfig = {
    enabled: false,
    endpoint: '',
    apiKey: ''
};
let cloudConfig = {
    enabled: false,
    provider: '',
    bucket: '',
    accessKey: '',
    secretKey: ''
};
let notificationConfig = {
    email: '',
    projectCreated: false,
    lineItemAdded: false,
    costThreshold: false,
    threshold: 10000
};

// ========================================
// DATA MANAGEMENT FUNCTIONS
// ========================================

/**
 * Retrieves all projects from localStorage
 * @returns {Array} Array of project objects
 */
function getProjects() {
    try {
        const projects = localStorage.getItem('projects');
        return projects ? JSON.parse(projects) : [];
    } catch (error) {
        console.error('Error retrieving projects:', error);
        showToast('Error loading projects. Data may be corrupted.', 'error');
        return [];
    }
}

/**
 * Saves projects array to localStorage
 * @param {Array} projects - Array of project objects to save
 */
function saveProjects(projects) {
    try {
        localStorage.setItem('projects', JSON.stringify(projects));
        if (apiConfig.enabled) {
            syncToBackend('projects', projects);
        }
    } catch (error) {
        console.error('Error saving projects:', error);
        if (error.name === 'QuotaExceededError') {
            showToast('Storage quota exceeded. Please delete some data.', 'error');
        } else {
            showToast('Error saving project data.', 'error');
        }
    }
}

/**
 * Retrieves all line items from localStorage
 * @returns {Array} Array of line item objects
 */
function getLineItems() {
    try {
        const lineItems = localStorage.getItem('lineItems');
        return lineItems ? JSON.parse(lineItems) : [];
    } catch (error) {
        console.error('Error retrieving line items:', error);
        showToast('Error loading line items. Data may be corrupted.', 'error');
        return [];
    }
}

/**
 * Saves line items array to localStorage
 * @param {Array} lineItems - Array of line item objects to save
 */
function saveLineItems(lineItems) {
    try {
        localStorage.setItem('lineItems', JSON.stringify(lineItems));
        if (apiConfig.enabled) {
            syncToBackend('lineItems', lineItems);
        }
    } catch (error) {
        console.error('Error saving line items:', error);
        if (error.name === 'QuotaExceededError') {
            showToast('Storage quota exceeded. Please delete some data.', 'error');
        } else {
            showToast('Error saving line item data.', 'error');
        }
    }
}

/**
 * Generates a unique project ID
 * @returns {number} Unique unsigned integer ID
 */
function generateProjectId() {
    const projects = getProjects();
    if (projects.length === 0) {
        return 1;
    }
    const maxId = Math.max(...projects.map(p => p.projectId));
    return maxId + 1;
}

// ========================================
// UI NAVIGATION FUNCTIONS
// ========================================

/**
 * Switches between application tabs/sections
 * @param {string} tabName - ID of the section to display
 */
function switchTab(tabName) {
    // Hide all sections
    const sections = document.querySelectorAll('.section');
    sections.forEach(section => section.classList.remove('active'));

    // Remove active class from all tabs
    const tabs = document.querySelectorAll('.nav-tab');
    tabs.forEach(tab => tab.classList.remove('active'));

    // Show selected section
    const selectedSection = document.getElementById(tabName);
    if (selectedSection) {
        selectedSection.classList.add('active');
    }

    // Add active class to clicked tab
    event.target.classList.add('active');

    // Refresh data when switching to view tabs
    if (tabName === 'view-projects') {
        displayProjects();
    } else if (tabName === 'view-line-items') {
        displayLineItems();
    } else if (tabName === 'add-line-item') {
        populateProjectDropdowns();
    } else if (tabName === 'reports') {
        populateReportFilters();
        generateReports();
    }
}

// ========================================
// TOAST NOTIFICATION SYSTEM
// ========================================

/**
 * Displays a toast notification
 * @param {string} message - Message to display
 * @param {string} type - Toast type ('success', 'error', 'info')
 */
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.remove();
    }, 3000);
}

/**
 * Displays an alert message in a specific container
 * @param {string} containerId - ID of the alert container element
 * @param {string} message - Message to display
 * @param {string} type - Alert type ('success', 'error', 'info')
 */
function showAlert(containerId, message, type = 'success') {
    const container = document.getElementById(containerId);
    if (!container) return;

    const alertClass = type === 'error' ? 'alert-error' : 
                      type === 'info' ? 'alert-info' : 'alert-success';
    
    container.innerHTML = `<div class="alert ${alertClass}">${escapeHtml(message)}</div>`;
    
    if (type === 'success') {
        setTimeout(() => {
            container.innerHTML = '';
        }, 5000);
    }
}

/**
 * Escapes HTML special characters to prevent XSS attacks
 * @param {string} text - Text to escape
 * @returns {string} Escaped text safe for HTML insertion
 */
function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return String(text).replace(/[&<>"']/g, m => map[m]);
}

// ========================================
// PROJECT MANAGEMENT FUNCTIONS
// ========================================

/**
 * Creates a new project from form data
 * @param {Event} event - Form submit event
 */
function createProject(event) {
    event.preventDefault();

    const projectData = {
        projectId: generateProjectId(),
        projectTitle: document.getElementById('project-title').value.trim(),
        responsibleContact: document.getElementById('responsible-contact').value.trim(),
        contactNumber: document.getElementById('contact-number').value.trim(),
        contactTextNumber: document.getElementById('contact-text-number').value.trim(),
        contactEmail: document.getElementById('contact-email').value.trim(),
        dateCreated: new Date().toISOString(),
        projectSynopsis: document.getElementById('project-synopsis').value.trim(),
        projectDescription: document.getElementById('project-description').value.trim()
    };

    if (!validateEmail(projectData.contactEmail)) {
        showAlert('project-alert', 'Please enter a valid email address.', 'error');
        return;
    }

    const projects = getProjects();
    projects.push(projectData);
    saveProjects(projects);

    showAlert('project-alert', `Project "${projectData.projectTitle}" created successfully! Project ID: ${projectData.projectId}`, 'success');
    showToast(`Project created: ${projectData.projectTitle}`, 'success');

    // Send email notification if enabled
    if (notificationConfig.projectCreated && notificationConfig.email) {
        sendEmailNotification('project_created', projectData);
    }

    resetProjectForm();
    populateProjectDropdowns();
}

/**
 * Validates email format
 * @param {string} email - Email address to validate
 * @returns {boolean} True if valid email format
 */
function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

/**
 * Resets the project creation form
 */
function resetProjectForm() {
    document.getElementById('project-form').reset();
    document.getElementById('project-alert').innerHTML = '';
}

/**
 * Populates project dropdown menus throughout the application
 */
function populateProjectDropdowns() {
    const projects = getProjects();
    
    const dropdowns = [
        'line-item-project-id',
        'filter-project',
        'report-project-filter'
    ];

    dropdowns.forEach(dropdownId => {
        const dropdown = document.getElementById(dropdownId);
        if (dropdown) {
            const currentValue = dropdown.value;
            const firstOption = dropdown.options[0].text;
            dropdown.innerHTML = `<option value="">${firstOption}</option>`;
            
            projects.forEach(project => {
                const option = document.createElement('option');
                option.value = project.projectId;
                option.textContent = `${project.projectTitle} (ID: ${project.projectId})`;
                dropdown.appendChild(option);
            });
            
            if (currentValue) {
                dropdown.value = currentValue;
            }
        }
    });
}

/**
 * Updates the project info display when a project is selected
 */
function updateProjectInfo() {
    const projectId = parseInt(document.getElementById('line-item-project-id').value);
    const infoDiv = document.getElementById('selected-project-info');
    const titleSpan = document.getElementById('selected-project-title');

    if (projectId) {
        const projects = getProjects();
        const project = projects.find(p => p.projectId === projectId);
        
        if (project) {
            titleSpan.textContent = `${project.projectTitle} (ID: ${project.projectId})`;
            infoDiv.classList.remove('hidden');
        }
    } else {
        infoDiv.classList.add('hidden');
    }
}

/**
 * Displays all projects in the view projects section
 */
function displayProjects() {
    const projects = getProjects();
    const container = document.getElementById('projects-container');

    if (projects.length === 0) {
        container.innerHTML = '<div class="no-data">No projects found. Create your first project!</div>';
        return;
    }

    let html = '';
    projects.forEach(project => {
        const lineItems = getLineItems().filter(item => item.projectId === project.projectId);
        const totalCost = lineItems.reduce((sum, item) => sum + (item.totalCost || 0), 0);

        html += `
            <div class="project-card">
                <h3>${escapeHtml(project.projectTitle)}</h3>
                <p class="project-id">Project ID: ${project.projectId}</p>
                <p><strong>Contact:</strong> ${escapeHtml(project.responsibleContact)}</p>
                <p><strong>Phone:</strong> ${escapeHtml(project.contactNumber)}</p>
                <p><strong>Email:</strong> ${escapeHtml(project.contactEmail)}</p>
                <p><strong>Created:</strong> ${formatDate(project.dateCreated)}</p>
                <p><strong>Synopsis:</strong> ${escapeHtml(project.projectSynopsis)}</p>
                <p><strong>Line Items:</strong> ${lineItems.length}</p>
                <p class="total-cost">Total Cost: 
$$
{totalCost.toFixed(2)}</p>
                <div class="mt-20">
                    <button class="btn btn-warning" onclick="editProject(${project.projectId})">Edit</button>
                    <button class="btn btn-danger" onclick="deleteProject(${project.projectId})">Delete</button>
                </div>
            </div>
        `;
    });

    container.innerHTML = html;
}

/**
 * Formats ISO date string to readable format
 * @param {string} isoDate - ISO format date string
 * @returns {string} Formatted date string
 */
function formatDate(isoDate) {
    const date = new Date(isoDate);
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
}

/**
 * Opens edit modal for a specific project
 * @param {number} projectId - ID of project to edit
 */
function editProject(projectId) {
    const projects = getProjects();
    const project = projects.find(p => p.projectId === projectId);

    if (!project) {
        showToast('Project not found!', 'error');
        return;
    }

    document.getElementById('edit-project-id').value = project.projectId;
    document.getElementById('edit-project-title').value = project.projectTitle;
    document.getElementById('edit-responsible-contact').value = project.responsibleContact;
    document.getElementById('edit-contact-number').value = project.contactNumber;
    document.getElementById('edit-contact-text-number').value = project.contactTextNumber || '';
    document.getElementById('edit-contact-email').value = project.contactEmail;
    document.getElementById('edit-project-synopsis').value = project.projectSynopsis;
    document.getElementById('edit-project-description').value = project.projectDescription;

    document.getElementById('edit-project-modal').classList.add('active');
}

/**
 * Updates an existing project with new data
 * @param {Event} event - Form submit event
 */
function updateProject(event) {
    event.preventDefault();

    const projectId = parseInt(document.getElementById('edit-project-id').value);
    const projects = getProjects();
    const projectIndex = projects.findIndex(p => p.projectId === projectId);

    if (projectIndex === -1) {
        showToast('Project not found!', 'error');
        return;
    }

    projects[projectIndex] = {
        ...projects[projectIndex],
        projectTitle: document.getElementById('edit-project-title').value.trim(),
        responsibleContact: document.getElementById('edit-responsible-contact').value.trim(),
        contactNumber: document.getElementById('edit-contact-number').value.trim(),
        contactTextNumber: document.getElementById('edit-contact-text-number').value.trim(),
        contactEmail: document.getElementById('edit-contact-email').value.trim(),
        projectSynopsis: document.getElementById('edit-project-synopsis').value.trim(),
        projectDescription: document.getElementById('edit-project-description').value.trim()
    };

    saveProjects(projects);
    closeEditProjectModal();
    displayProjects();
    populateProjectDropdowns();
    
    showToast('Project updated successfully!', 'success');
}

/**
 * Closes the edit project modal
 */
function closeEditProjectModal() {
    document.getElementById('edit-project-modal').classList.remove('active');
}

/**
 * Deletes a project and all associated line items
 * @param {number} projectId - ID of project to delete
 */
function deleteProject(projectId) {
    const projects = getProjects();
    const project = projects.find(p => p.projectId === projectId);

    if (!project) {
        showToast('Project not found!', 'error');
        return;
    }

    const lineItems = getLineItems();
    const associatedItems = lineItems.filter(item => item.projectId === projectId);

    const confirmMessage = `Are you sure you want to delete project "${project.projectTitle}"?\n\n` +
                          `This will also delete ${associatedItems.length} associated line item(s).\n\n` +
                          `This action cannot be undone!`;

    if (!confirm(confirmMessage)) {
        return;
    }

    const updatedProjects = projects.filter(p => p.projectId !== projectId);
    saveProjects(updatedProjects);

    const updatedLineItems = lineItems.filter(item => item.projectId !== projectId);
    saveLineItems(updatedLineItems);

    displayProjects();
    populateProjectDropdowns();

    showToast('Project and associated line items deleted successfully!', 'success');
}

/**
 * Filters displayed projects based on search input
 */
function filterProjects() {
    const searchTerm = document.getElementById('project-search').value.toLowerCase();
    const projects = getProjects();

    const filtered = projects.filter(project => {
        return project.projectTitle.toLowerCase().includes(searchTerm) ||
               project.responsibleContact.toLowerCase().includes(searchTerm) ||
               project.projectId.toString().includes(searchTerm) ||
               project.contactEmail.toLowerCase().includes(searchTerm);
    });

    const container = document.getElementById('projects-container');
    
    if (filtered.length === 0) {
        container.innerHTML = '<div class="no-data">No projects match your search.</div>';
        return;
    }

    let html = '';
    filtered.forEach(project => {
        const lineItems = getLineItems().filter(item => item.projectId === project.projectId);
        const totalCost = lineItems.reduce((sum, item) => sum + (item.totalCost || 0), 0);

        html += `
            <div class="project-card">
                <h3>${escapeHtml(project.projectTitle)}</h3>
                <p class="project-id">Project ID: ${project.projectId}</p>
                <p><strong>Contact:</strong> ${escapeHtml(project.responsibleContact)}</p>
                <p><strong>Phone:</strong> ${escapeHtml(project.contactNumber)}</p>
                <p><strong>Email:</strong> ${escapeHtml(project.contactEmail)}</p>
                <p><strong>Created:</strong> ${formatDate(project.dateCreated)}</p>
                <p><strong>Synopsis:</strong> ${escapeHtml(project.projectSynopsis)}</p>
                <p><strong>Line Items:</strong> ${lineItems.length}</p>
                <p class="total-cost">Total Cost:
$$
{totalCost.toFixed(2)}</p>
                <div class="mt-20">
                    <button class="btn btn-warning" onclick="editProject(${project.projectId})">Edit</button>
                    <button class="btn btn-danger" onclick="deleteProject(${project.projectId})">Delete</button>
                </div>
            </div>
        `;
    });

    container.innerHTML = html;
}

// ========================================
// LINE ITEM MANAGEMENT FUNCTIONS
// ========================================

/**
 * Updates category-specific input fields based on selected category
 */
function updateCategoryInputs() {
    const category = document.getElementById('line-item-category').value;
    const container = document.getElementById('category-inputs-container');

    if (!category) {
        container.innerHTML = '';
        return;
    }

    let html = '<div class="category-inputs">';

    if (category === 'Labor') {
        html += `
            <h3>Labor Details</h3>
            <div class="form-row">
                <div class="form-group">
                    <label for="labor-rate">Hourly Rate ($) *</label>
                    <input type="number" id="labor-rate" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label for="labor-hours">Number of Hours *</label>
                    <input type="number" id="labor-hours" step="0.01" min="0" required>
                </div>
            </div>
            <div class="form-group">
                <label for="labor-date">Date Worked *</label>
                <input type="date" id="labor-date" required>
            </div>
        `;
    } else if (category === 'Supplies') {
        html += `
            <h3>Supplies Details</h3>
            <div class="form-row">
                <div class="form-group">
                    <label for="supplies-cost">Cost per Item ($) *</label>
                    <input type="number" id="supplies-cost" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label for="supplies-quantity">Quantity *</label>
                    <input type="number" id="supplies-quantity" step="0.01" min="0" required>
                </div>
            </div>
            <div class="form-group">
                <label for="supplies-date">Date Purchased *</label>
                <input type="date" id="supplies-date" required>
            </div>
        `;
    } else if (category === 'Administrative') {
        html += `
            <h3>Administrative Details</h3>
            <div class="form-row">
                <div class="form-group">
                    <label for="admin-cost">Cost ($) *</label>
                    <input type="number" id="admin-cost" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label for="admin-date">Date *</label>
                    <input type="date" id="admin-date" required>
                </div>
            </div>
        `;
    }

    html += '</div>';
    container.innerHTML = html;
}

/**
 * Creates a new line item from form data
 * @param {Event} event - Form submit event
 */
function createLineItem(event) {
    event.preventDefault();

    const projectId = parseInt(document.getElementById('line-item-project-id').value);
    const category = document.getElementById('line-item-category').value;

    const projects = getProjects();
    if (!projects.find(p => p.projectId === projectId)) {
        showAlert('line-item-alert', 'Selected project not found!', 'error');
        return;
    }

    let categoryInputs = {};
    let totalCost = 0;

    if (category === 'Labor') {
        const rate = parseFloat(document.getElementById('labor-rate').value);
        const hours = parseFloat(document.getElementById('labor-hours').value);
        const date = document.getElementById('labor-date').value;

        categoryInputs = { rate, hours, date };
        totalCost = rate * hours;
    } else if (category === 'Supplies') {
        const cost = parseFloat(document.getElementById('supplies-cost').value);
        const quantity = parseFloat(document.getElementById('supplies-quantity').value);
        const date = document.getElementById('supplies-date').value;

        categoryInputs = { cost, quantity, date };
        totalCost = cost * quantity;
    } else if (category === 'Administrative') {
        const cost = parseFloat(document.getElementById('admin-cost').value);
        const date = document.getElementById('admin-date').value;

        categoryInputs = { cost, date };
        totalCost = cost;
    }

    const resources = {
        imguri: [],
        viduri: [],
        pdfuri: []
    };

    // Add uploaded files
    uploadedFiles.forEach(file => {
        if (file.type.startsWith('image/')) {
            resources.imguri.push(file.path);
        } else if (file.type.startsWith('video/')) {
            resources.viduri.push(file.path);
        } else if (file.type === 'application/pdf') {
            resources.pdfuri.push(file.path);
        }
    });

    // Add manual URIs
    const imguri = document.getElementById('line-item-imguri').value.trim();
    const viduri = document.getElementById('line-item-viduri').value.trim();
    const pdfuri = document.getElementById('line-item-pdfuri').value.trim();

    if (imguri) resources.imguri.push(imguri);
    if (viduri) resources.viduri.push(viduri);
    if (pdfuri) resources.pdfuri.push(pdfuri);

    const lineItem = {
        projectId,
        category,
        categoryInputs,
        synopsis: document.getElementById('line-item-synopsis').value.trim(),
        notes: document.getElementById('line-item-notes').value.trim(),
        totalCost,
        resources,
        dateCreated: new Date().toISOString()
    };

    const lineItems = getLineItems();
    lineItems.push(lineItem);
    saveLineItems(lineItems);

    showAlert('line-item-alert', `Line item added successfully! Total Cost: 
$$
{totalCost.toFixed(2)}`, 'success');
    showToast(`Line item added:
$$
{totalCost.toFixed(2)}`, 'success');

    // Send email notification if enabled
    if (notificationConfig.lineItemAdded && notificationConfig.email) {
        sendEmailNotification('line_item_added', lineItem);
    }

    // Check cost threshold
    if (notificationConfig.costThreshold && totalCost > notificationConfig.threshold) {
        sendEmailNotification('cost_threshold', lineItem);
    }

    resetLineItemForm();
}

/**
 * Resets the line item creation form
 */
function resetLineItemForm() {
    document.getElementById('line-item-form').reset();
    document.getElementById('category-inputs-container').innerHTML = '';
    document.getElementById('selected-project-info').classList.add('hidden');
    document.getElementById('line-item-alert').innerHTML = '';
    uploadedFiles = [];
    document.getElementById('uploaded-files-list').innerHTML = '';
}

/**
 * Displays all line items with filtering options
 */
function displayLineItems() {
    const lineItems = getLineItems();
    const container = document.getElementById('line-items-container');

    if (lineItems.length === 0) {
        container.innerHTML = '<div class="no-data">No line items found. Add your first line item!</div>';
        return;
    }

    let html = '';
    lineItems.forEach((item, index) => {
        const project = getProjects().find(p => p.projectId === item.projectId);
        const projectTitle = project ? project.projectTitle : 'Unknown Project';

        html += generateLineItemHTML(item, index, projectTitle);
    });

    container.innerHTML = html;
}

/**
 * Generates HTML for a single line item
 * @param {Object} item - Line item object
 * @param {number} index - Index in lineItems array
 * @param {string} projectTitle - Title of associated project
 * @returns {string} HTML string for line item
 */
function generateLineItemHTML(item, index, projectTitle) {
    let categoryDetails = '';
    
    if (item.category === 'Labor') {
        categoryDetails = `
            <p><strong>Rate:</strong> 
$$
{item.categoryInputs.rate.toFixed(2)}/hr</p>
            <p><strong>Hours:</strong> ${item.categoryInputs.hours.toFixed(2)}</p>
            <p><strong>Date Worked:</strong> ${item.categoryInputs.date}</p>
        `;
    } else if (item.category === 'Supplies') {
        categoryDetails = `
            <p><strong>Cost per Item:</strong>
$$
{item.categoryInputs.cost.toFixed(2)}</p>
            <p><strong>Quantity:</strong> ${item.categoryInputs.quantity.toFixed(2)}</p>
            <p><strong>Date Purchased:</strong> ${item.categoryInputs.date}</p>
        `;
    } else if (item.category === 'Administrative') {
        categoryDetails = `
            <p><strong>Cost:</strong> 
$$
{item.categoryInputs.cost.toFixed(2)}</p>
            <p><strong>Date:</strong> ${item.categoryInputs.date}</p>
        `;
    }

    let resourceHTML = '';
    if (item.resources) {
        const allResources = [
            ...(item.resources.imguri || []).map(uri => ({ uri, type: 'Image' })),
            ...(item.resources.viduri || []).map(uri => ({ uri, type: 'Video' })),
            ...(item.resources.pdfuri || []).map(uri => ({ uri, type: 'PDF' }))
        ];

        if (allResources.length > 0) {
            resourceHTML = '<div class="resource-links"><strong>Resources:</strong><br>';
            allResources.forEach(resource => {
                resourceHTML += `
                    <a href="${escapeHtml(resource.uri)}" target="_blank" class="resource-link">
                        📎 ${resource.type}: ${escapeHtml(resource.uri)}
                    </a>
                `;
            });
            resourceHTML += '</div>';
        }
    }

    return `
        <div class="line-item">
            <div class="line-item-header">
                <div>
                    <span class="line-item-category category-${item.category.toLowerCase()}">
                        ${item.category}
                    </span>
                    <h3 style="display: inline; margin-left: 15px;">${escapeHtml(item.synopsis)}</h3>
                </div>
                <div>
                    <button class="btn btn-warning" onclick="editLineItem(${index})">Edit</button>
                    <button class="btn btn-danger" onclick="deleteLineItem(${index})">Delete</button>
                </div>
            </div>
            <div class="line-item-content">
                <p><strong>Project:</strong> ${escapeHtml(projectTitle)} (ID: ${item.projectId})</p>
                ${categoryDetails}
                <p><strong>Total Cost:</strong> <span class="total-cost">
$$
{item.totalCost.toFixed(2)}</span></p>
                ${item.notes ? `<p><strong>Notes:</strong> ${escapeHtml(item.notes)}</p>` : ''}
                <p><strong>Created:</strong> ${formatDate(item.dateCreated)}</p>
            </div>
            ${resourceHTML}
        </div>
    `;
}

/**
 * Filters line items based on project, category, and search term
 */
function filterLineItems() {
    const projectFilter = document.getElementById('filter-project').value;
    const categoryFilter = document.getElementById('filter-category').value;
    const searchTerm = document.getElementById('line-item-search').value.toLowerCase();
    
    let lineItems = getLineItems();

    if (projectFilter) {
        lineItems = lineItems.filter(item => item.projectId === parseInt(projectFilter));
    }

    if (categoryFilter) {
        lineItems = lineItems.filter(item => item.category === categoryFilter);
    }

    if (searchTerm) {
        lineItems = lineItems.filter(item => {
            return item.synopsis.toLowerCase().includes(searchTerm) ||
                   (item.notes && item.notes.toLowerCase().includes(searchTerm));
        });
    }

    const container = document.getElementById('line-items-container');
    
    if (lineItems.length === 0) {
        container.innerHTML = '<div class="no-data">No line items match your filters.</div>';
        return;
    }

    let html = '';
    lineItems.forEach((item, originalIndex) => {
        const allItems = getLineItems();
        const realIndex = allItems.findIndex(i => 
            i.projectId === item.projectId && 
            i.dateCreated === item.dateCreated &&
            i.synopsis === item.synopsis
        );
        
        const project = getProjects().find(p => p.projectId === item.projectId);
        const projectTitle = project ? project.projectTitle : 'Unknown Project';
        
        html += generateLineItemHTML(item, realIndex, projectTitle);
    });

    container.innerHTML = html;
}

/**
 * Opens edit modal for a specific line item
 * @param {number} index - Index of line item in array
 */
function editLineItem(index) {
    const lineItems = getLineItems();
    const item = lineItems[index];

    if (!item) {
        showToast('Line item not found!', 'error');
        return;
    }

    document.getElementById('edit-line-item-index').value = index;
    document.getElementById('edit-line-item-category').value = item.category;
    document.getElementById('edit-line-item-synopsis').value = item.synopsis;
    document.getElementById('edit-line-item-notes').value = item.notes || '';

    document.getElementById('edit-line-item-imguri').value = 
        item.resources.imguri && item.resources.imguri.length > 0 ? item.resources.imguri[0] : '';
    document.getElementById('edit-line-item-viduri').value = 
        item.resources.viduri && item.resources.viduri.length > 0 ? item.resources.viduri[0] : '';
    document.getElementById('edit-line-item-pdfuri').value = 
        item.resources.pdfuri && item.resources.pdfuri.length > 0 ? item.resources.pdfuri[0] : '';

    updateEditCategoryInputs();

    if (item.category === 'Labor') {
        document.getElementById('edit-labor-rate').value = item.categoryInputs.rate;
        document.getElementById('edit-labor-hours').value = item.categoryInputs.hours;
        document.getElementById('edit-labor-date').value = item.categoryInputs.date;
    } else if (item.category === 'Supplies') {
        document.getElementById('edit-supplies-cost').value = item.categoryInputs.cost;
        document.getElementById('edit-supplies-quantity').value = item.categoryInputs.quantity;
        document.getElementById('edit-supplies-date').value = item.categoryInputs.date;
    } else if (item.category === 'Administrative') {
        document.getElementById('edit-admin-cost').value = item.categoryInputs.cost;
        document.getElementById('edit-admin-date').value = item.categoryInputs.date;
    }

    document.getElementById('edit-line-item-modal').classList.add('active');
}

/**
 * Updates category inputs in edit modal
 */
function updateEditCategoryInputs() {
    const category = document.getElementById('edit-line-item-category').value;
    const container = document.getElementById('edit-category-inputs-container');

    if (!category) {
        container.innerHTML = '';
        return;
    }

    let html = '<div class="category-inputs">';

    if (category === 'Labor') {
        html += `
            <h3>Labor Details</h3>
            <div class="form-row">
                <div class="form-group">
                    <label for="edit-labor-rate">Hourly Rate ($) *</label>
                    <input type="number" id="edit-labor-rate" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label for="edit-labor-hours">Number of Hours *</label>
                    <input type="number" id="edit-labor-hours" step="0.01" min="0" required>
                </div>
            </div>
            <div class="form-group">
                <label for="edit-labor-date">Date Worked *</label>
                <input type="date" id="edit-labor-date" required>
            </div>
        `;
    } else if (category === 'Supplies') {
        html += `
            <h3>Supplies Details</h3>
            <div class="form-row">
                <div class="form-group">
                    <label for="edit-supplies-cost">Cost per Item ($) *</label>
                    <input type="number" id="edit-supplies-cost" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label for="edit-supplies-quantity">Quantity *</label>
                    <input type="number" id="edit-supplies-quantity" step="0.01" min="0" required>
                </div>
            </div>
            <div class="form-group">
                <label for="edit-supplies-date">Date Purchased *</label>
                <input type="date" id="edit-supplies-date" required>
            </div>
        `;
    } else if (category === 'Administrative') {
        html += `
            <h3>Administrative Details</h3>
            <div class="form-row">
                <div class="form-group">
                    <label for="edit-admin-cost">Cost ($) *</label>
                    <input type="number" id="edit-admin-cost" step="0.01" min="0" required>
                </div>
                <div class="form-group">
                    <label for="edit-admin-date">Date *</label>
                    <input type="date" id="edit-admin-date" required>
                </div>
            </div>
        `;
    }

    html += '</div>';
    container.innerHTML = html;
}

/**
 * Updates an existing line item
 * @param {Event} event - Form submit event
 */
function updateLineItem(event) {
    event.preventDefault();

    const index = parseInt(document.getElementById('edit-line-item-index').value);
    const lineItems = getLineItems();

    if (index < 0 || index >= lineItems.length) {
        showToast('Line item not found!', 'error');
        return;
    }

    const category = document.getElementById('edit-line-item-category').value;

    let categoryInputs = {};
    let totalCost = 0;

    if (category === 'Labor') {
        const rate = parseFloat(document.getElementById('edit-labor-rate').value);
        const hours = parseFloat(document.getElementById('edit-labor-hours').value);
        const date = document.getElementById('edit-labor-date').value;

        categoryInputs = { rate, hours, date };
        totalCost = rate * hours;
    } else if (category === 'Supplies') {
        const cost = parseFloat(document.getElementById('edit-supplies-cost').value);
        const quantity = parseFloat(document.getElementById('edit-supplies-quantity').value);
        const date = document.getElementById('edit-supplies-date').value;

        categoryInputs = { cost, quantity, date };
        totalCost = cost * quantity;
    } else if (category === 'Administrative') {
        const cost = parseFloat(document.getElementById('edit-admin-cost').value);
        const date = document.getElementById('edit-admin-date').value;

        categoryInputs = { cost, date };
        totalCost = cost;
    }

    const resources = {
        imguri: [],
        viduri: [],
        pdfuri: []
    };

    const imguri = document.getElementById('edit-line-item-imguri').value.trim();
    const viduri = document.getElementById('edit-line-item-viduri').value.trim();
    const pdfuri = document.getElementById('edit-line-item-pdfuri').value.trim();

    if (imguri) resources.imguri.push(imguri);
    if (viduri) resources.viduri.push(viduri);
    if (pdfuri) resources.pdfuri.push(pdfuri);

    lineItems[index] = {
        ...lineItems[index],
        category,
        categoryInputs,
        synopsis: document.getElementById('edit-line-item-synopsis').value.trim(),
        notes: document.getElementById('edit-line-item-notes').value.trim(),
        totalCost,
        resources
    };

    saveLineItems(lineItems);
    closeEditLineItemModal();
    displayLineItems();
    
    showToast('Line item updated successfully!', 'success');
}

/**
 * Closes the edit line item modal
 */
function closeEditLineItemModal() {
    document.getElementById('edit-line-item-modal').classList.remove('active');
}

/**
 * Deletes a line item
 * @param {number} index - Index of line item to delete
 */
function deleteLineItem(index) {
    const lineItems = getLineItems();
    const item = lineItems[index];

    if (!item) {
        showToast('Line item not found!', 'error');
        return;
    }

    if (!confirm(`Are you sure you want to delete this line item?\n\nSynopsis: ${item.synopsis}\nTotal Cost: 
$$
{item.totalCost.toFixed(2)}\n\nThis action cannot be undone!`)) {
        return;
    }

    lineItems.splice(index, 1);
    saveLineItems(lineItems);
    displayLineItems();
    
    showToast('Line item deleted successfully!', 'success');
}

// ========================================
// FILE UPLOAD FUNCTIONS (DRAG & DROP)
// ========================================

/**
 * Initializes drag and drop functionality
 */
function initializeDragAndDrop() {
    const dropZone = document.getElementById('drop-zone');
    const fileInput = document.getElementById('file-input');

    // Prevent default drag behaviors
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
        document.body.addEventListener(eventName, preventDefaults, false);
    });

    // Highlight drop zone when item is dragged over it
    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, () => {
            dropZone.classList.add('drag-over');
        }, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, () => {
            dropZone.classList.remove('drag-over');
        }, false);
    });

    // Handle dropped files
    dropZone.addEventListener('drop', handleDrop, false);
    fileInput.addEventListener('change', handleFileSelect, false);

    // Import drop zone
    const importDropZone = document.getElementById('import-drop-zone');
    const importFileInput = document.getElementById('import-file-input');

    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        importDropZone.addEventListener(eventName, preventDefaults, false);
    });

    ['dragenter', 'dragover'].forEach(eventName => {
        importDropZone.addEventListener(eventName, () => {
            importDropZone.classList.add('drag-over');
        }, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        importDropZone.addEventListener(eventName, () => {
            importDropZone.classList.remove('drag-over');
        }, false);
    });

    importDropZone.addEventListener('drop', handleImportDrop, false);
    importFileInput.addEventListener('change', handleImportFileSelect, false);

    // Restore file input
    const restoreFileInput = document.getElementById('restore-file-input');
    restoreFileInput.addEventListener('change', handleRestoreFileSelect, false);
}

/**
 * Prevents default drag and drop behavior
 * @param {Event} e - Event object
 */
function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

/**
 * Handles file drop event
 * @param {Event} e - Drop event
 */
function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    handleFiles(files);
}

/**
 * Handles file selection from input
 * @param {Event} e - Change event
 */
function handleFileSelect(e) {
    const files = e.target.files;
    handleFiles(files);
}

/**
 * Processes uploaded files
 * @param {FileList} files - List of files to process
 */
function handleFiles(files) {
    [...files].forEach(file => {
        // Validate file type
        const validTypes = ['image/', 'video/', 'application/pdf'];
        const isValid = validTypes.some(type => file.type.startsWith(type));

        if (!isValid) {
            showToast(`Invalid file type: ${file.name}`, 'error');
            return;
        }

        // Simulate file upload (in production, upload to server or cloud storage)
        const fileData = {
            name: file.name,
            type: file.type,
            size: file.size,
            path: generateFilePath(file)
        };

        uploadedFiles.push(fileData);
        displayUploadedFiles();

        // If cloud storage is enabled, upload to cloud
        if (cloudConfig.enabled) {
            uploadToCloud(file, fileData.path);
        }
    });
}

/**
 * Generates a file path for uploaded file
 * @param {File} file - File object
 * @returns {string} Generated file path
 */
function generateFilePath(file) {
    const timestamp = Date.now();
    const safeName = file.name.replace(/[^a-zA-Z0-9.-]/g, '_');
    
    if (file.type.startsWith('image/')) {
        return `imgs/${timestamp}_${safeName}`;
    } else if (file.type.startsWith('video/')) {
        return `vids/${timestamp}_${safeName}`;
    } else if (file.type === 'application/pdf') {
        return `pdfs/${timestamp}_${safeName}`;
    }
    
    return `files/${timestamp}_${safeName}`;
}

/**
 * Displays list of uploaded files
 */
function displayUploadedFiles() {
    const container = document.getElementById('uploaded-files-list');
    
    if (uploadedFiles.length === 0) {
        container.innerHTML = '';
        return;
    }

    let html = '<h4>Uploaded Files:</h4>';
    uploadedFiles.forEach((file, index) => {
        const icon = file.type.startsWith('image/') ? '🖼️' :
                    file.type.startsWith('video/') ? '🎥' : '📄';
        
        html += `
            <div class="uploaded-file-item">
                <div class="uploaded-file-info">
                    <span class="file-icon">${icon}</span>
                    <div>
                        <strong>${escapeHtml(file.name)}</strong><br>
                        <small>${(file.size / 1024).toFixed(2)} KB - ${escapeHtml(file.path)}</small>
                    </div>
                </div>
                <button type="button" class="file-remove-btn" onclick="removeUploadedFile(${index})">Remove</button>
            </div>
        `;
    });

    container.innerHTML = html;
}

/**
 * Removes an uploaded file from the list
 * @param {number} index - Index of file to remove
 */
function removeUploadedFile(index) {
    uploadedFiles.splice(index, 1);
    displayUploadedFiles();
}

// ========================================
// EXPORT FUNCTIONS
// ========================================

/**
 * Exports all data as JSON
 */
function exportAllDataJSON() {
    const data = {
        projects: getProjects(),
        lineItems: getLineItems(),
        exportDate: new Date().toISOString(),
        version: '1.0'
    };

    downloadJSON(data, `project-tracker-backup-${Date.now()}.json`);
    showToast('All data exported successfully!', 'success');
}

/**
 * Exports projects only as JSON
 */
function exportProjectsJSON() {
    const data = {
        projects: getProjects(),
        exportDate: new Date().toISOString()
    };

    downloadJSON(data, `projects-${Date.now()}.json`);
    showToast('Projects exported successfully!', 'success');
}

/**
 * Exports line items only as JSON
 */
function exportLineItemsJSON() {
    const data = {
        lineItems: getLineItems(),
        exportDate: new Date().toISOString()
    };

    downloadJSON(data, `line-items-${Date.now()}.json`);
    showToast('Line items exported successfully!', 'success');
}

/**
 * Downloads data as JSON file
 * @param {Object} data - Data to export
 * @param {string} filename - Name of file to download
 */
function downloadJSON(data, filename) {
    const json = JSON.stringify(data, null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

/**
 * Exports projects as CSV
 */
function exportProjectsCSV() {
    const projects = getProjects();
    
    if (projects.length === 0) {
        showToast('No projects to export!', 'error');
        return;
    }

    let csv = 'Project ID,Project Title,Responsible Contact,Contact Number,Contact Email,Date Created,Synopsis,Description,Line Items Count,Total Cost\n';

    projects.forEach(project => {
        const lineItems = getLineItems().filter(item => item.projectId === project.projectId);
        const totalCost = lineItems.reduce((sum, item) => sum + (item.totalCost || 0), 0);

        csv += `${project.projectId},"${escapeCSV(project.projectTitle)}","${escapeCSV(project.responsibleContact)}","${escapeCSV(project.contactNumber)}","${escapeCSV(project.contactEmail)}","${project.dateCreated}","${escapeCSV(project.projectSynopsis)}","${escapeCSV(project.projectDescription)}",${lineItems.length},${totalCost.toFixed(2)}\n`;
    });

    downloadCSV(csv, `projects-${Date.now()}.csv`);
    showToast('Projects exported as CSV!', 'success');
}

/**
 * Exports line items as CSV
 */
function exportLineItemsCSV() {
    const lineItems = getLineItems();
    
    if (lineItems.length === 0) {
        showToast('No line items to export!', 'error');
        return;
    }

    let csv = 'Project ID,Category,Synopsis,Notes,Total Cost,Date Created\n';

    lineItems.forEach(item => {
        csv += `${item.projectId},"${item.category}","${escapeCSV(item.synopsis)}","${escapeCSV(item.notes || '')}",${item.totalCost.toFixed(2)},"${item.dateCreated}"\n`;
    });

    downloadCSV(csv, `line-items-${Date.now()}.csv`);
    showToast('Line items exported as CSV!', 'success');
}

/**
 * Exports report data as CSV
 */
function exportReportCSV() {
    const projects = getProjects();
    const lineItems = getLineItems();

    if (projects.length === 0) {
        showToast('No data to export!', 'error');
        return;
    }

    let csv = 'Project ID,Project Title,Category,Line Item Synopsis,Cost,Date\n';

    projects.forEach(project => {
        const projectItems = lineItems.filter(item => item.projectId === project.projectId);
        
        if (projectItems.length === 0) {
            csv += `${project.projectId},"${escapeCSV(project.projectTitle)}","N/A","No line items",0.00,"${project.dateCreated}"\n`;
        } else {
            projectItems.forEach(item => {
                const date = item.categoryInputs.date || item.dateCreated;
                csv += `${project.projectId},"${escapeCSV(project.projectTitle)}","${item.category}","${escapeCSV(item.synopsis)}",${item.totalCost.toFixed(2)},"${date}"\n`;
            });
        }
    });

    downloadCSV(csv, `report-${Date.now()}.csv`);
    showToast('Report exported as CSV!', 'success');
}

/**
 * Escapes special characters for CSV
 * @param {string} text - Text to escape
 * @returns {string} Escaped text
 */
function escapeCSV(text) {
    if (typeof text !== 'string') return '';
    return text.replace(/"/g, '""');
}

/**
 * Downloads data as CSV file
 * @param {string} csv - CSV data
 * @param {string} filename - Name of file to download
 */
function downloadCSV(csv, filename) {
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// ========================================
// IMPORT FUNCTIONS
// ========================================

/**
 * Handles import file drop
 * @param {Event} e - Drop event
 */
function handleImportDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    if (files.length > 0) {
        handleImportFile(files[0]);
    }
}

/**
 * Handles import file selection
 * @param {Event} e - Change event
 */
function handleImportFileSelect(e) {
    const files = e.target.files;
    if (files.length > 0) {
        handleImportFile(files[0]);
    }
}

/**
 * Processes import file
 * @param {File} file - File to import
 */
function handleImportFile(file) {
    if (file.type !== 'application/json') {
        showAlert('import-status', 'Please select a valid JSON file!', 'error');
        return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
        try {
            const data = JSON.parse(e.target.result);
            importData(data);
        } catch (error) {
            console.error('Import error:', error);
            showAlert('import-status', 'Error parsing JSON file. Please check the file format.', 'error');
        }
    };
    reader.readAsText(file);
}

/**
 * Imports data from JSON object
 * @param {Object} data - Data to import
 */
function importData(data) {
    let importedProjects = 0;
    let importedLineItems = 0;
    let skippedProjects = 0;

    const existingProjects = getProjects();
    const existingLineItems = getLineItems();
    const existingProjectIds = new Set(existingProjects.map(p => p.projectId));

    // Import projects
    if (data.projects && Array.isArray(data.projects)) {
        data.projects.forEach(project => {
            if (!existingProjectIds.has(project.projectId)) {
                existingProjects.push(project);
                importedProjects++;
            } else {
                skippedProjects++;
            }
        });
        saveProjects(existingProjects);
    }

    // Import line items
    if (data.lineItems && Array.isArray(data.lineItems)) {
        data.lineItems.forEach(item => {
            existingLineItems.push(item);
            importedLineItems++;
        });
        saveLineItems(existingLineItems);
    }

    const message = `Import completed!\n\nProjects imported: ${importedProjects}\nProjects skipped (duplicate IDs): ${skippedProjects}\nLine items imported: ${importedLineItems}`;
    showAlert('import-status', message, 'success');
    showToast('Data imported successfully!', 'success');

    // Refresh displays
    populateProjectDropdowns();
    displayProjects();
    displayLineItems();
}

// ========================================
// BACKUP AND RESTORE FUNCTIONS
// ========================================

/**
 * Creates a complete backup of all data
 */
function createBackup() {
    const backup = {
        projects: getProjects(),
        lineItems: getLineItems(),
        settings: {
            apiConfig: apiConfig,
            cloudConfig: cloudConfig,
            notificationConfig: notificationConfig
        },
        backupDate: new Date().toISOString(),
        version: '1.0'
    };

    downloadJSON(backup, `complete-backup-${Date.now()}.json`);
    showToast('Backup created successfully!', 'success');
}

/**
 * Handles restore file selection
 * @param {Event} e - Change event
 */
function handleRestoreFileSelect(e) {
    const files = e.target.files;
    if (files.length === 0) return;

    const file = files[0];
    
    if (!confirm('⚠️ WARNING: Restoring from backup will REPLACE all current data!\n\nAre you sure you want to continue?')) {
        e.target.value = '';
        return;
    }

    const reader = new FileReader();
    reader.onload = function(event) {
        try {
            const backup = JSON.parse(event.target.result);
            restoreFromBackup(backup);
        } catch (error) {
            console.error('Restore error:', error);
            showToast('Error restoring backup. Invalid file format.', 'error');
        }
    };
    reader.readAsText(file);
    e.target.value = '';
}

/**
 * Restores data from backup
 * @param {Object} backup - Backup data
 */
function restoreFromBackup(backup) {
    try {
        if (backup.projects) {
            localStorage.setItem('projects', JSON.stringify(backup.projects));
        }
        if (backup.lineItems) {
            localStorage.setItem('lineItems', JSON.stringify(backup.lineItems));
        }
        if (backup.settings) {
            if (backup.settings.apiConfig) {
                apiConfig = backup.settings.apiConfig;
                localStorage.setItem('apiConfig', JSON.stringify(apiConfig));
            }
            if (backup.settings.cloudConfig) {
                cloudConfig = backup.settings.cloudConfig;
                localStorage.setItem('cloudConfig', JSON.stringify(cloudConfig));
            }
            if (backup.settings.notificationConfig) {
                notificationConfig = backup.settings.notificationConfig;
                localStorage.setItem('notificationConfig', JSON.stringify(notificationConfig));
            }
        }

        showToast('Backup restored successfully! Reloading...', 'success');
        
        setTimeout(() => {
            location.reload();
        }, 2000);
    } catch (error) {
        console.error('Restore error:', error);
        showToast('Error restoring backup.', 'error');
    }
}

/**
 * Clears all application data
 */
function clearAllData() {
    if (!confirm('⚠️ DANGER: This will DELETE ALL DATA permanently!\n\nAre you absolutely sure?')) {
        return;
    }

    if (!confirm('This is your FINAL WARNING!\n\nAll projects, line items, and settings will be permanently deleted.\n\nContinue?')) {
        return;
    }

    localStorage.removeItem('projects');
    localStorage.removeItem('lineItems');
    
    showToast('All data cleared! Reloading...', 'success');
    
    setTimeout(() => {
        location.reload();
    }, 2000);
}

// ========================================
// REPORTING FUNCTIONS
// ========================================

/**
 * Populates report filter dropdowns
 */
function populateReportFilters() {
    populateProjectDropdowns();
}

/**
 * Generates comprehensive reports
 */
function generateReports() {
    const startDate = document.getElementById('report-start-date').value;
    const endDate = document.getElementById('report-end-date').value;
    const projectFilter = document.getElementById('report-project-filter').value;

    let projects = getProjects();
    let lineItems = getLineItems();

    // Apply project filter
    if (projectFilter) {
        projects = projects.filter(p => p.projectId === parseInt(projectFilter));
        lineItems = lineItems.filter(item => item.projectId === parseInt(projectFilter));
    }

    // Apply date range filter
    if (startDate || endDate) {
        lineItems = lineItems.filter(item => {
            const itemDate = new Date(item.categoryInputs.date || item.dateCreated);
            
            if (startDate && endDate) {
                return itemDate >= new Date(startDate) && itemDate <= new Date(endDate);
            } else if (startDate) {
                return itemDate >= new Date(startDate);
            } else if (endDate) {
                return itemDate <= new Date(endDate);
            }
            
            return true;
        });
    }

    // Calculate summary statistics
    const totalProjects = projects.length;
    const totalLineItems = lineItems.length;
    const totalCost = lineItems.reduce((sum, item) => sum + (item.totalCost || 0), 0);
    const avgCost = totalLineItems > 0 ? totalCost / totalLineItems : 0;

    // Update summary cards
    document.getElementById('total-projects').textContent = totalProjects;
    document.getElementById('total-line-items').textContent = totalLineItems;
    document.getElementById('total-cost').textContent = `
$$
{totalCost.toFixed(2)}`;
    document.getElementById('avg-cost').textContent = `
$$
{avgCost.toFixed(2)}`;

    // Generate category breakdown
    generateCategoryChart(lineItems);

    // Generate project breakdown
    generateProjectChart(projects, lineItems);

    // Generate detailed report
    generateDetailedReport(projects, lineItems);
}

/**
 * Generates category breakdown chart
 * @param {Array} lineItems - Filtered line items
 */
function generateCategoryChart(lineItems) {
    const categories = {
        'Supplies': 0,
        'Labor': 0,
        'Administrative': 0
    };

    lineItems.forEach(item => {
        categories[item.category] += item.totalCost;
    });

    const maxCost = Math.max(...Object.values(categories));
    const container = document.getElementById('category-chart');

    if (maxCost === 0) {
        container.innerHTML = '<p style="text-align: center; color: #999;">No data available</p>';
        return;
    }

    let html = '';
    Object.entries(categories).forEach(([category, cost]) => {
        const percentage = maxCost > 0 ? (cost / maxCost) * 100 : 0;
        html += `
            <div class="chart-bar">
                <div class="chart-label">${category}</div>
                <div class="chart-bar-fill" style="width: ${percentage}%">
                    <span class="chart-value">
$$
{cost.toFixed(2)}</span>
                </div>
            </div>
        `;
    });

    container.innerHTML = html;
}

/**
 * Generates project breakdown chart
 * @param {Array} projects - Filtered projects
 * @param {Array} lineItems - Filtered line items
 */
function generateProjectChart(projects, lineItems) {
    const projectCosts = {};

    projects.forEach(project => {
        const items = lineItems.filter(item => item.projectId === project.projectId);
        const totalCost = items.reduce((sum, item) => sum + (item.totalCost || 0), 0);
        projectCosts[project.projectTitle] = totalCost;
    });

    const maxCost = Math.max(...Object.values(projectCosts));
    const container = document.getElementById('project-chart');

    if (maxCost === 0) {
        container.innerHTML = '<p style="text-align: center; color: #999;">No data available</p>';
        return;
    }

    let html = '';
    Object.entries(projectCosts).forEach(([title, cost]) => {
        const percentage = maxCost > 0 ? (cost / maxCost) * 100 : 0;
        html += `
            <div class="chart-bar">
                <div class="chart-label">${escapeHtml(title)}</div>
                <div class="chart-bar-fill" style="width: ${percentage}%">
                    <span class="chart-value">
$$
{cost.toFixed(2)}</span>
                </div>
            </div>
        `;
    });

    container.innerHTML = html;
}

/**
 * Generates detailed report table
 * @param {Array} projects - Filtered projects
 * @param {Array} lineItems - Filtered line items
 */
function generateDetailedReport(projects, lineItems) {
    const container = document.getElementById('detailed-report');

    if (projects.length === 0) {
        container.innerHTML = '<p style="text-align: center; color: #999;">No data available</p>';
        return;
    }

    let html = '<table style="width: 100%; border-collapse: collapse;">';
    html += '<thead><tr style="background: #667eea; color: white;">';
    html += '<th style="padding: 12px; text-align: left;">Project</th>';
    html += '<th style="padding: 12px; text-align: center;">Line Items</th>';
    html += '<th style="padding: 12px; text-align: center;">Supplies</th>';
    html += '<th style="padding: 12px; text-align: center;">Labor</th>';
    html += '<th style="padding: 12px; text-align: center;">Admin</th>';
    html += '<th style="padding: 12px; text-align: right;">Total Cost</th>';
    html += '</tr></thead><tbody>';

    projects.forEach((project, index) => {
        const items = lineItems.filter(item => item.projectId === project.projectId);
        const totalCost = items.reduce((sum, item) => sum + (item.totalCost || 0), 0);
        
        const suppliesCost = items.filter(i => i.category === 'Supplies')
            .reduce((sum, item) => sum + item.totalCost, 0);
        const laborCost = items.filter(i => i.category === 'Labor')
            .reduce((sum, item) => sum + item.totalCost, 0);
        const adminCost = items.filter(i => i.category === 'Administrative')
            .reduce((sum, item) => sum + item.totalCost, 0);

        const bgColor = index % 2 === 0 ? '#f8f9fa' : 'white';
        
        html += `<tr style="background: ${bgColor};">`;
        html += `<td style="padding: 12px;">${escapeHtml(project.projectTitle)}</td>`;
        html += `<td style="padding: 12px; text-align: center;">${items.length}</td>`;
        html += `<td style="padding: 12px; text-align: center;">
$$
{suppliesCost.toFixed(2)}</td>`;
        html += `<td style="padding: 12px; text-align: center;">
$$
{laborCost.toFixed(2)}</td>`;
        html += `<td style="padding: 12px; text-align: center;">
$$
{adminCost.toFixed(2)}</td>`;
        html += `<td style="padding: 12px; text-align: right; font-weight: bold;">
$$
{totalCost.toFixed(2)}</td>`;
        html += '</tr>';
    });

    html += '</tbody></table>';
    container.innerHTML = html;
}
