<!DOCTYPE html>
<html lang="ru" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D Print Sales Manager</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .dark-mode { background-color: #1a202c; color: #e2e8f0; }
        .light-mode { background-color: #f7fafc; color: #2d3748; }
        .sidebar { transition: all 0.3s ease; }
        .sidebar.collapsed { width: 70px; }
        .sidebar.collapsed .sidebar-text { display: none; }
        .main-content { transition: margin-left 0.3s ease; }
        .file-upload { position: relative; overflow: hidden; display: inline-block; }
        .file-upload input[type="file"] { position: absolute; left: 0; top: 0; opacity: 0; }
        .product-card {
            @apply bg-white dark:bg-gray-700 rounded-lg shadow overflow-hidden transition-transform hover:scale-105;
            min-width: 180px;
        }
        .product-image {
            @apply w-full h-32 object-cover lazy-load;
        }
        .cost-calculator { background-color: #f3f4f6; padding: 1rem; border-radius: 0.5rem; }
        .cost-result { font-weight: bold; color: #2563eb; }
        .cost-formula { font-size: 0.875rem; color: #4b5563; }
        .color-preview { display: inline-block; width: 20px; height: 20px; border-radius: 50%; margin-right: 8px; vertical-align: middle; }
        .order-badge {
            @apply absolute top-2 left-2 bg-blue-500 text-white text-xs px-2 py-1 rounded;
        }
        .customer-badge {
            @apply absolute top-2 right-2 bg-green-500 text-white text-xs px-2 py-1 rounded;
        }
        .status-badge {
            @apply absolute bottom-2 right-2 bg-gray-500 text-white text-xs px-2 py-1 rounded;
        }
        .lazy-load {
            background: #eee;
            background: linear-gradient(110deg, #ececec 8%, #f5f5f5 18%, #ececec 33%);
            background-size: 200% 100%;
            animation: shimmer 1.5s infinite;
        }
        @keyframes shimmer {
            from { background-position: 200% 0; }
            to { background-position: -200% 0; }
        }
    </style>
</head>
<body class="h-full dark-mode">
    <div class="flex h-full">
        <!-- Sidebar -->
        <div class="sidebar bg-gray-800 text-white w-64 h-full fixed overflow-y-auto no-print" id="sidebar">
            <div class="p-4 flex items-center justify-between border-b border-gray-700">
                <h1 class="text-xl font-bold sidebar-text">3D Print Manager</h1>
                <button id="toggleSidebar" class="text-gray-400 hover:text-white">
                    <i class="fas fa-bars sidebar-icon"></i>
                </button>
            </div>
            <nav class="mt-4">
                <div class="px-4 py-2">
                    <button id="toggleTheme" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-moon mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Темная тема</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('dashboard')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-tachometer-alt mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Дашборд</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('materials')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-boxes mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Материалы</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('products')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-cube mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Продукция</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('sales')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-ruble-sign mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Продажи</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('costs')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-calculator mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Калькулятор</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('analytics')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-chart-line mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Аналитика</span>
                    </button>
                </div>
                <div class="px-4 py-2">
                    <button onclick="showSection('settings')" class="w-full flex items-center text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md">
                        <i class="fas fa-cog mr-3 sidebar-icon"></i>
                        <span class="sidebar-text">Настройки</span>
                    </button>
                </div>
            </nav>
        </div>

        <!-- Main Content -->
        <div class="main-content flex-1 ml-64 p-6 no-print" id="mainContent">
            <!-- Dashboard Section -->
            <div id="dashboard-section" class="section-content">
                <h2 class="text-2xl font-bold mb-6">Дашборд</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                    <div class="bg-blue-500 text-white p-6 rounded-lg shadow">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm">Выручка за месяц</p>
                                <h3 class="text-2xl font-bold" id="monthlyRevenue">0 ₽</h3>
                            </div>
                            <i class="fas fa-ruble-sign text-3xl opacity-50"></i>
                        </div>
                    </div>
                    <div class="bg-green-500 text-white p-6 rounded-lg shadow">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm">Прибыль за месяц</p>
                                <h3 class="text-2xl font-bold" id="monthlyProfit">0 ₽</h3>
                            </div>
                            <i class="fas fa-chart-line text-3xl opacity-50"></i>
                        </div>
                    </div>
                    <div class="bg-yellow-500 text-white p-6 rounded-lg shadow">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm">Продано товаров</p>
                                <h3 class="text-2xl font-bold" id="soldProducts">0</h3>
                            </div>
                            <i class="fas fa-cube text-3xl opacity-50"></i>
                        </div>
                    </div>
                    <div class="bg-red-500 text-white p-6 rounded-lg shadow">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm">Материалы на исходе</p>
                                <h3 class="text-2xl font-bold" id="lowMaterials">0</h3>
                            </div>
                            <i class="fas fa-exclamation-triangle text-3xl opacity-50"></i>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                    <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                        <h3 class="text-lg font-semibold mb-4">Продажи по месяцам</h3>
                        <canvas id="salesChart" height="250"></canvas>
                    </div>
                    <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                        <h3 class="text-lg font-semibold mb-4">Расход материалов</h3>
                        <canvas id="materialsChart" height="250"></canvas>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Последние продажи</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-600">
                            <thead class="bg-gray-50 dark:bg-gray-600">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Дата</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Товар</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Цена</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Прибыль</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-gray-700 divide-y divide-gray-200 dark:divide-gray-600" id="recentSalesTable">
                                <!-- Filled by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Materials Section -->
            <div id="materials-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">Материалы</h2>
                    <button onclick="showAddMaterialModal()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                        <i class="fas fa-plus mr-2"></i> Добавить материал
                    </button>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-600">
                            <thead class="bg-gray-50 dark:bg-gray-600">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Фото</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Название</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Цвет</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Цена за кг</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Остаток</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Дата закупки</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Действия</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-gray-700 divide-y divide-gray-200 dark:divide-gray-600" id="materialsTable">
                                <!-- Filled by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Products Section -->
            <div id="products-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">Продукция</h2>
                    <button onclick="showAddProductModal()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                        <i class="fas fa-plus mr-2"></i> Добавить продукт
                    </button>
                </div>

                <div class="mb-4">
                    <div class="flex space-x-2">
                        <select id="productFilterStatus" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            <option value="all">Все статусы</option>
                            <option value="В производстве">В производстве</option>
                            <option value="В продаже">В продаже</option>
                            <option value="Продан">Продан</option>
                        </select>
                        <button onclick="filterProducts()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md">Фильтровать</button>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4" id="productsGrid">
                    <!-- Filled by JavaScript -->
                </div>
            </div>

            <!-- Sales Section -->
            <div id="sales-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">Продажи</h2>
                    <div class="flex space-x-2">
                        <input type="date" id="salesDateFrom" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        <input type="date" id="salesDateTo" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        <button onclick="filterSales()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md">Фильтровать</button>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-600">
                            <thead class="bg-gray-50 dark:bg-gray-600">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Дата</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Товар</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Материал</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Цена</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Прибыль</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Действия</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-gray-700 divide-y divide-gray-200 dark:divide-gray-600" id="salesTable">
                                <!-- Filled by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Costs Section -->
            <div id="costs-section" class="section-content hidden">
                <h2 class="text-2xl font-bold mb-6">Калькулятор затрат</h2>
                
                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Настройки затрат</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Стоимость электричества (₽/кВт·ч)</label>
                            <input type="number" id="electricityCost" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white" step="0.01">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Амортизация оборудования (₽/час)</label>
                            <input type="number" id="depreciationCost" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white" step="0.01">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Дополнительные расходы (₽/час)</label>
                            <input type="number" id="otherCost" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white" step="0.01">
                        </div>
                        <div>
                            <button onclick="saveCostSettings()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md">Сохранить настройки</button>
                        </div>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Расчет себестоимости</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Стоимость пластика за кг (₽)</label>
                            <input type="number" id="plasticCostPerKg" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white" step="0.01">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Вес изделия (г)</label>
                            <input type="number" id="costWeight" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Время печати (часов)</label>
                            <input type="number" id="costTime" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white" step="0.1">
                        </div>
                        <div>
                            <button onclick="calculateCost()" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md">Рассчитать</button>
                        </div>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                    <h3 class="text-lg font-semibold mb-4">Результаты расчета</h3>
                    <div id="costResults" class="space-y-3">
                        <p class="cost-calculator">Себестоимость пластика: <span id="plasticCost" class="cost-result">0 ₽</span></p>
                        <p class="cost-calculator">Затраты на электричество: <span id="electricityCostResult" class="cost-result">0 ₽</span></p>
                        <p class="cost-calculator">Амортизация оборудования: <span id="depreciationCostResult" class="cost-result">0 ₽</span></p>
                        <div class="flex justify-between">
                            <span class="cost-calculator">Дополнительные расходы:</span>
                            <span id="otherCostResult" class="cost-result">0 ₽</span>
                        </div>
                        <p class="cost-calculator font-bold">Общая себестоимость: <span id="totalCost" class="cost-result">0 ₽</span></p>
                        <p class="cost-formula" id="costFormula"></p>
                    </div>
                </div>
            </div>

            <!-- Analytics Section -->
            <div id="analytics-section" class="section-content hidden">
                <h2 class="text-2xl font-bold mb-6">Аналитика</h2>
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                    <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                        <h3 class="text-lg font-semibold mb-4">Топ 5 материалов по прибыли</h3>
                        <canvas id="topMaterialsChart" height="300"></canvas>
                    </div>
                    <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                        <h3 class="text-lg font-semibold mb-4">Топ 5 товаров по продажам</h3>
                        <canvas id="topProductsChart" height="300"></canvas>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Остатки материалов</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-600">
                            <thead class="bg-gray-50 dark:bg-gray-600">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Материал</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Остаток (г)</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">% от начального</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Статус</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-gray-700 divide-y divide-gray-200 dark:divide-gray-600" id="materialsStatusTable">
                                <!-- Filled by JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Settings Section -->
            <div id="settings-section" class="section-content hidden">
                <h2 class="text-2xl font-bold mb-6">Настройки</h2>
                
                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Уведомления</h3>
                    <div class="space-y-4">
                        <div class="flex items-center">
                            <input id="emailNotifications" type="checkbox" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="emailNotifications" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">Email уведомления</label>
                        </div>
                        <div class="flex items-center">
                            <input id="telegramNotifications" type="checkbox" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="telegramNotifications" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">Telegram уведомления</label>
                        </div>
                        <div id="telegramSettings" class="hidden mt-4">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Telegram Bot Token</label>
                                <input type="text" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Chat ID</label>
                                <input type="text" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow mb-6">
                    <h3 class="text-lg font-semibold mb-4">Резервное копирование</h3>
                    <div class="space-y-4">
                        <div>
                            <button onclick="exportData()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                                <i class="fas fa-file-export mr-2"></i> Экспорт данных
                            </button>
                        </div>
                        <div>
                            <div class="file-upload">
                                <button class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-file-import mr-2"></i> Импорт данных
                                </button>
                                <input type="file" id="importFile" accept=".json">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-700 p-6 rounded-lg shadow">
                    <h3 class="text-lg font-semibold mb-4">Настройки печати</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Логотип для ценников</label>
                            <div class="file-upload">
                                <button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-upload mr-2"></i> Загрузить логотип
                                </button>
                                <input type="file" id="logoUpload" accept="image/*">
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Размер шрифта</label>
                            <select class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                <option>Маленький</option>
                                <option selected>Средний</option>
                                <option>Большой</option>
                            </select>
                        </div>
                        <div class="flex items-center">
                            <input id="printQR" type="checkbox" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="printQR" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">Печатать QR-код на ценнике</label>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Material Modal -->
    <div id="addMaterialModal" class="fixed z-50 inset-0 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white dark:bg-gray-700 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg font-medium leading-6 text-gray-900 dark:text-white mb-4">Добавить материал</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Название</label>
                            <input type="text" id="materialName" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Цена за кг (руб)</label>
                            <input type="number" id="materialPrice" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Цвет</label>
                            <div class="flex items-center">
                                <span id="colorPreview" class="color-preview bg-gray-500"></span>
                                <input type="color" id="materialColor" class="bg-gray-50 border border-gray-300 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white h-10">
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Дата закупки</label>
                            <input type="date" id="materialDate" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Начальный остаток (г)</label>
                            <input type="number" id="materialAmount" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Фото материала</label>
                            <div class="file-upload">
                                <button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-upload mr-2"></i> Загрузить фото
                                </button>
                                <input type="file" id="materialPhoto" accept="image/*">
                            </div>
                            <div id="materialPhotoPreview" class="mt-2 hidden">
                                <img id="materialPreviewImage" class="h-16 rounded-md lazy-load">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button id="saveMaterialButton" onclick="saveMaterial()" type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-500 text-base font-medium text-white hover:bg-blue-600 sm:ml-3 sm:w-auto sm:text-sm">
                        Сохранить
                    </button>
                    <button onclick="hideAddMaterialModal()" type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:bg-gray-600 dark:text-white dark:border-gray-500">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Product Modal -->
    <div id="addProductModal" class="fixed z-50 inset-0 overflow-y-auto hidden">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white dark:bg-gray-700 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg font-medium leading-6 text-gray-900 dark:text-white mb-4">Добавить продукт</h3>
                    <div class="grid grid-cols-2 gap-4">
                        <div class="col-span-2">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Название изделия</label>
                            <input type="text" id="productName" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Материал</label>
                            <select id="productMaterial" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                <!-- Заполняется JavaScript -->
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Вес (г)</label>
                            <input type="number" id="productWeight" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Цена (₽)</label>
                            <input type="number" id="productPrice" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Номер заказа</label>
                            <input type="text" id="productOrderNumber" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Имя клиента</label>
                            <input type="text" id="productCustomerName" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Телефон</label>
                            <input type="text" id="productCustomerPhone" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div class="col-span-2">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Комментарии</label>
                            <textarea id="productComments" rows="3" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
                        </div>
                        <div class="col-span-2">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Дата производства</label>
                            <input type="date" id="productDate" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Статус</label>
                            <select id="productStatus" class="bg-gray-50 border border-gray-300 text-gray-900 rounded-md px-3 py-2 w-full dark:bg-gray-700 dark:border-gray-600 dark:text-white">
                                <option value="В производстве">В производстве</option>
                                <option value="В продаже">В продаже</option>
                                <option value="Продан">Продан</option>
                            </select>
                        </div>
                        <div class="col-span-2">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Фото изделия (до 3)</label>
                            <div class="file-upload">
                                <button class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center">
                                    <i class="fas fa-upload mr-2"></i> Загрузить фото
                                </button>
                                <input type="file" id="productPhotos" accept="image/*" multiple>
                            </div>
                            <div id="productPhotosPreview" class="mt-2 grid grid-cols-3 gap-2 hidden">
                                <!-- Заполняется JavaScript -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button id="saveProductButton" onclick="saveProduct()" type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-500 text-base font-medium text-white hover:bg-blue-600 sm:ml-3 sm:w-auto sm:text-sm">
                        Сохранить
                    </button>
                    <button onclick="hideAddProductModal()" type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:bg-gray-600 dark:text-white dark:border-gray-500">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Image Viewer Modal -->
    <div id="imageViewer" class="fixed inset-0 bg-black bg-opacity-90 z-50 hidden items-center justify-center">
        <div class="relative w-full max-w-4xl">
            <img id="viewerImage" class="max-h-screen mx-auto">
            <button onclick="closeImageViewer()" class="absolute top-4 right-4 text-white text-2xl">
                <i class="fas fa-times"></i>
            </button>
        </div>
    </div>

    <script>
        // Initialize data
        let materials = [];
        let products = [];
        let sales = [];
        let costSettings = {
            electricity: 5.0,
            depreciation: 50.0,
            other: 20.0
        };

        // IndexedDB connection
        let db;
        const DB_NAME = '3DPrintManager';
        const DB_VERSION = 1;

        // Initialize the app with proper async/await
        async function initApp() {
            try {
                await initDatabase();
                await loadAllData();
                updateDashboard();
                renderMaterialsTable();
                renderProductsGrid();
                renderSalesTable();
                initCharts();
                setupEventListeners();
                populateCostMaterialDropdown();
            } catch (error) {
                console.error('Initialization error:', error);
                alert('Ошибка инициализации: ' + error.message);
            }
        }

        // Initialize IndexedDB
        async function initDatabase() {
            return new Promise((resolve, reject) => {
                const request = indexedDB.open(DB_NAME, DB_VERSION);

                request.onupgradeneeded = (e) => {
                    const db = e.target.result;
                    
                    // Create stores if they don't exist
                    if (!db.objectStoreNames.contains('materials')) {
                        db.createObjectStore('materials', { keyPath: 'id' });
                    }
                    if (!db.objectStoreNames.contains('products')) {
                        db.createObjectStore('products', { keyPath: 'id' });
                    }
                    if (!db.objectStoreNames.contains('sales')) {
                        db.createObjectStore('sales', { keyPath: 'id' });
                    }
                    if (!db.objectStoreNames.contains('images')) {
                        db.createObjectStore('images', { keyPath: 'key' });
                    }
                };

                request.onsuccess = (e) => {
                    db = e.target.result;
                    resolve();
                };

                request.onerror = (e) => {
                    reject(e.target.error);
                };
            });
        }

        // Load all data with proper error handling
        async function loadAllData() {
            try {
                materials = await getAll('materials') || [];
                products = await getAll('products') || [];
                sales = await getAll('sales') || [];
                
                // Load cost settings
                const settings = await getAll('costSettings');
                if (settings && settings.length > 0) {
                    costSettings = settings[0];
                    document.getElementById('electricityCost').value = costSettings.electricity;
                    document.getElementById('depreciationCost').value = costSettings.depreciation;
                    document.getElementById('otherCost').value = costSettings.other;
                }
            } catch (error) {
                console.error('Load data error:', error);
                // Initialize sample data if empty
                if (materials.length === 0) {
                    materials = [
                        { id: 1, name: 'PLA', price: 1200, date: '2023-05-15', amount: 500, initialAmount: 1000, photo: 'https://via.placeholder.com/150?text=PLA', color: '#ff9999' },
                        { id: 2, name: 'PETG', price: 1500, date: '2023-06-20', amount: 300, initialAmount: 800, photo: 'https://via.placeholder.com/150?text=PETG', color: '#99ff99' },
                        { id: 3, name: 'ABS', price: 1300, date: '2023-07-10', amount: 100, initialAmount: 500, photo: 'https://via.placeholder.com/150?text=ABS', color: '#9999ff' }
                    ];
                }
                if (products.length === 0) {
                    products = [
                        { 
                            id: 1, 
                            name: 'Кронштейн для полки', 
                            materialId: 1, 
                            weight: 50, 
                            price: 800, 
                            date: '2023-08-01', 
                            status: 'В продаже', 
                            orderNumber: 'ORD-001',
                            customerName: 'Иванов И.И.',
                            customerPhone: '8-800-123-45-67',
                            comments: 'Стандартный кронштейн для книжной полки', 
                            photos: [
                                'https://via.placeholder.com/150?text=Кронштейн1',
                                'https://via.placeholder.com/150?text=Кронштейн2'
                            ] 
                        },
                        { 
                            id: 2, 
                            name: 'Держатель для телефона', 
                            materialId: 2, 
                            weight: 30, 
                            price: 600, 
                            date: '2023-08-05', 
                            status: 'Продан',
                            orderNumber: 'ORD-002',
                            customerName: 'Петров П.П.',
                            customerPhone: '8-800-987-65-43',
                            comments: 'Универсальный держатель для смартфона', 
                            photos: [
                                'https://via.placeholder.com/150?text=Держатель1'
                            ] 
                        },
                        { 
                            id: 3, 
                            name: 'Корпус для Arduino', 
                            materialId: 3, 
                            weight: 70, 
                            price: 900, 
                            date: '2023-08-10', 
                            status: 'В производстве',
                            orderNumber: 'ORD-003',
                            customerName: 'Сидоров С.С.',
                            customerPhone: '8-800-555-35-35',
                            comments: 'Корпус для прототипа электронного устройства', 
                            photos: [
                                'https://via.placeholder.com/150?text=Корпус1',
                                'https://via.placeholder.com/150?text=Корпус2',
                                'https://via.placeholder.com/150?text=Корпус3'
                            ] 
                        }
                    ];
                }
                if (sales.length === 0) {
                    sales = [
                        { id: 1, productId: 2, date: '2023-08-15', price: 600, profit: 450 },
                        { id: 2, productId: 1, date: '2023-08-20', price: 800, profit: 620 },
                        { id: 3, productId: 3, date: '2023-08-25', price: 900, profit: 710 }
                    ];
                }
                
                // Save initial data if empty
                if (materials.length > 0) await saveAll('materials', materials);
                if (products.length > 0) await saveAll('products', products);
                if (sales.length > 0) await saveAll('sales', sales);
            }
        }

        // CRUD operations with proper error handling
        async function getAll(storeName) {
            try {
                const transaction = db.transaction(storeName, 'readonly');
                const store = transaction.objectStore(storeName);
                const request = store.getAll();
                
                return new Promise((resolve, reject) => {
                    request.onsuccess = () => resolve(request.result);
                    request.onerror = () => reject(request.error);
                });
            } catch (error) {
                console.error(`Error getting ${storeName}:`, error);
                return [];
            }
        }

        async function saveAll(storeName, data) {
            try {
                const transaction = db.transaction(storeName, 'readwrite');
                const store = transaction.objectStore(storeName);
                
                // Clear store first
                store.clear();
                
                // Add all items
                data.forEach(item => store.add(item));
                
                return new Promise((resolve, reject) => {
                    transaction.oncomplete = () => resolve();
                    transaction.onerror = () => reject(transaction.error);
                });
            } catch (error) {
                console.error(`Error saving ${storeName}:`, error);
            }
        }

        async function updateItem(storeName, item) {
            try {
                const transaction = db.transaction(storeName, 'readwrite');
                const store = transaction.objectStore(storeName);
                
                store.put(item);
                
                return new Promise((resolve, reject) => {
                    transaction.oncomplete = () => resolve();
                    transaction.onerror = () => reject(transaction.error);
                });
            } catch (error) {
                console.error(`Error updating ${storeName}:`, error);
            }
        }

        // Image handling with IndexedDB
        async function saveImage(key, dataUrl) {
            try {
                const transaction = db.transaction('images', 'readwrite');
                const store = transaction.objectStore('images');
                store.put({ key, dataUrl });
                
                return new Promise((resolve, reject) => {
                    transaction.oncomplete = () => resolve();
                    transaction.onerror = () => reject(transaction.error);
                });
            } catch (error) {
                console.error('Error saving image:', error);
            }
        }

        // Utility function to read file as data URL
        function readFileAsDataURL(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = (e) => resolve(e.target.result);
                reader.onerror = (e) => reject(e);
                reader.readAsDataURL(file);
            });
        }

        // Update dashboard with current data
        function updateDashboard() {
            // Calculate monthly revenue
            const currentMonth = new Date().getMonth();
            const monthlySales = sales.filter(sale => {
                const saleMonth = new Date(sale.date).getMonth();
                return saleMonth === currentMonth;
            });
            const monthlyRevenue = monthlySales.reduce((sum, sale) => sum + sale.price, 0);
            document.getElementById('monthlyRevenue').textContent = `${monthlyRevenue} ₽`;
            
            // Calculate monthly profit
            const monthlyProfit = monthlySales.reduce((sum, sale) => sum + sale.profit, 0);
            document.getElementById('monthlyProfit').textContent = `${monthlyProfit} ₽`;
            
            // Count sold products
            const soldProductsCount = products.filter(p => p.status === 'Продан').length;
            document.getElementById('soldProducts').textContent = soldProductsCount;
            
            // Count low materials
            const lowMaterialsCount = materials.filter(m => m.amount < 200).length;
            document.getElementById('lowMaterials').textContent = lowMaterialsCount;
            
            // Update recent sales table
            const recentSalesTable = document.getElementById('recentSalesTable');
            recentSalesTable.innerHTML = '';
            
            const recentSales = sales.slice(-5).reverse();
            recentSales.forEach(sale => {
                const product = products.find(p => p.id === sale.productId);
                if (!product) return;
                const material = materials.find(m => m.id === product.materialId);
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${formatDate(sale.date)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">${product.name}</td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${sale.price} ₽</td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${sale.profit} ₽</td>
                `;
                recentSalesTable.appendChild(row);
            });
        }

        // Render materials table
        function renderMaterialsTable() {
            const table = document.getElementById('materialsTable');
            table.innerHTML = '';
            
            materials.forEach(material => {
                const row = document.createElement('tr');
                row.className = material.amount < 200 ? 'bg-red-100 dark:bg-red-900' : '';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">
                        <img src="${material.photo}" class="h-10 w-10 rounded-full object-cover lazy-load" loading="lazy">
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">${material.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">
                        <span class="color-preview" style="background-color: ${material.color}"></span>${material.color}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${material.price} ₽</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">
                        <div class="flex items-center">
                            <div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-600 mr-2">
                                <div class="bg-blue-600 h-2.5 rounded-full" style="width: ${(material.amount / material.initialAmount) * 100}%"></div>
                            </div>
                            <span>${material.amount} г</span>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${formatDate(material.date)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button onclick="editMaterial(${material.id})" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">Изменить</button>
                        <button onclick="deleteMaterial(${material.id})" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">Удалить</button>
                    </td>
                `;
                table.appendChild(row);
            });
        }

        // Render products grid
        function renderProductsGrid(filterStatus = 'all') {
            const grid = document.getElementById('productsGrid');
            grid.innerHTML = '';
            
            let filteredProducts = products;
            if (filterStatus !== 'all') {
                filteredProducts = products.filter(p => p.status === filterStatus);
            }
            
            // Process products in batches for better performance
            const fragment = document.createDocumentFragment();
            
            filteredProducts.forEach(product => {
                const material = materials.find(m => m.id === product.materialId);
                if (!material) return;
                
                const cost = (product.weight / 1000) * material.price;
                
                const card = document.createElement('div');
                card.className = 'product-card p-3';
                card.innerHTML = `
                    <div class="relative">
                        <div class="absolute top-2 left-2 bg-blue-500 text-white text-xs px-2 py-1 rounded">
                            ${product.orderNumber || '—'}
                        </div>
                        <div class="absolute top-2 right-2 bg-green-500 text-white text-xs px-2 py-1 rounded">
                            ${product.customerName || '—'}
                        </div>
                        <div class="absolute bottom-2 right-2 bg-${getStatusColor(product.status)}-500 text-white text-xs px-2 py-1 rounded">
                            ${product.status}
                        </div>
                        <div class="h-32 overflow-hidden">
                            <img src="${product.photos[0] || 'https://via.placeholder.com/100?text=Product'}" 
                                 class="product-image lazy-load" 
                                 loading="lazy">
                        </div>
                    </div>
                    <div class="mt-2">
                        <h3 class="text-sm font-semibold mb-1 dark:text-white truncate">${product.name}</h3>
                        <div class="text-xs text-gray-600 dark:text-gray-300">
                            <p>Заказ: ${product.orderNumber || '—'}</p>
                            <p>Телефон: ${product.customerPhone || '—'}</p>
                            <p>Материал: ${material.name}</p>
                            <p>Вес: ${product.weight} г</p>
                        </div>
                        <div class="flex justify-between text-xs mt-1">
                            <span class="text-gray-600 dark:text-gray-300">Цена:</span>
                            <span class="font-medium dark:text-white">${product.price} ₽</span>
                        </div>
                        <div class="flex justify-between text-xs mt-1">
                            <span class="text-gray-600 dark:text-gray-300">Себестоимость:</span>
                            <span class="font-medium dark:text-white">${Math.round(cost)} ₽</span>
                        </div>
                        <div class="flex justify-between mt-1">
                            <button onclick="showProductPhotos(${product.id})" class="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 text-xs">
                                <i class="fas fa-images"></i>
                            </button>
                            <button onclick="editProduct(${product.id})" class="text-yellow-500 hover:text-yellow-700 dark:text-yellow-400 dark:hover:text-yellow-300 text-xs">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="deleteProduct(${product.id})" class="text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 text-xs">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                `;
                fragment.appendChild(card);
            });
            
            grid.appendChild(fragment);
        }

        // Render sales table
        function renderSalesTable(filterFrom = null, filterTo = null) {
            const table = document.getElementById('salesTable');
            table.innerHTML = '';
            
            let filteredSales = sales;
            if (filterFrom && filterTo) {
                filteredSales = sales.filter(sale => {
                    const saleDate = new Date(sale.date);
                    return saleDate >= new Date(filterFrom) && saleDate <= new Date(filterTo);
                });
            }
            
            // Process sales in batches
            const fragment = document.createDocumentFragment();
            
            filteredSales.forEach(sale => {
                const product = products.find(p => p.id === sale.productId);
                if (!product) return;
                
                const material = materials.find(m => m.id === product.materialId);
                if (!material) return;
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${formatDate(sale.date)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">${product.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${material.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${sale.price} ₽</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${sale.profit} ₽</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button onclick="deleteSale(${sale.id})" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">Удалить</button>
                    </td>
                `;
                fragment.appendChild(row);
            });
            
            table.appendChild(fragment);
        }

        // Initialize charts
        function initCharts() {
            // Sales by month chart
            const salesCtx = document.getElementById('salesChart').getContext('2d');
            const months = ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'];
            const currentMonth = new Date().getMonth();
            const salesData = Array(12).fill(0);
            
            sales.forEach(sale => {
                const saleMonth = new Date(sale.date).getMonth();
                salesData[saleMonth] += sale.price;
            });
            
            new Chart(salesCtx, {
                type: 'bar',
                data: {
                    labels: months,
                    datasets: [{
                        label: 'Выручка',
                        data: salesData,
                        backgroundColor: 'rgba(59, 130, 246, 0.5)',
                        borderColor: 'rgba(59, 130, 246, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // Materials usage chart
            const materialsCtx = document.getElementById('materialsChart').getContext('2d');
            const materialNames = materials.map(m => m.name);
            const materialUsage = materials.map(m => m.initialAmount - m.amount);
            
            new Chart(materialsCtx, {
                type: 'doughnut',
                data: {
                    labels: materialNames,
                    datasets: [{
                        data: materialUsage,
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.5)',
                            'rgba(54, 162, 235, 0.5)',
                            'rgba(255, 206, 86, 0.5)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true
                }
            });
            
            // Top materials by profit chart
            const topMaterialsCtx = document.getElementById('topMaterialsChart').getContext('2d');
            const materialProfits = {};
            
            sales.forEach(sale => {
                const product = products.find(p => p.id === sale.productId);
                if (!product) return;
                
                const material = materials.find(m => m.id === product.materialId);
                if (!material) return;
                
                if (!materialProfits[material.name]) {
                    materialProfits[material.name] = 0;
                }
                materialProfits[material.name] += sale.profit;
            });
            
            const sortedMaterials = Object.entries(materialProfits)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 5);
            
            new Chart(topMaterialsCtx, {
                type: 'bar',
                data: {
                    labels: sortedMaterials.map(m => m[0]),
                    datasets: [{
                        label: 'Прибыль',
                        data: sortedMaterials.map(m => m[1]),
                        backgroundColor: 'rgba(75, 192, 192, 0.5)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            
            // Top products by sales chart
            const topProductsCtx = document.getElementById('topProductsChart').getContext('2d');
            const productSales = {};
            
            sales.forEach(sale => {
                const product = products.find(p => p.id === sale.productId);
                if (!product) return;
                
                if (!productSales[product.name]) {
                    productSales[product.name] = 0;
                }
                productSales[product.name]++;
            });
            
            const sortedProducts = Object.entries(productSales)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 5);
            
            new Chart(topProductsCtx, {
                type: 'pie',
                data: {
                    labels: sortedProducts.map(p => p[0]),
                    datasets: [{
                        data: sortedProducts.map(p => p[1]),
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.5)',
                            'rgba(54, 162, 235, 0.5)',
                            'rgba(255, 206, 86, 0.5)',
                            'rgba(75, 192, 192, 0.5)',
                            'rgba(153, 102, 255, 0.5)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true
                }
            });
            
            // Update materials status table
            const materialsStatusTable = document.getElementById('materialsStatusTable');
            materialsStatusTable.innerHTML = '';
            
            materials.forEach(material => {
                const percentage = (material.amount / material.initialAmount) * 100;
                let status = ''; 
                let statusClass = '';
                
                if (percentage > 50) {
                    status = 'Норма';
                    statusClass = 'text-green-500';
                } else if (percentage > 20) {
                    status = 'Мало';
                    statusClass = 'text-yellow-500';
                } else {
                    status = 'На исходе';
                    statusClass = 'text-red-500';
                }
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">${material.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">${material.amount} г</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300">
                        <div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-600">
                            <div class="bg-blue-600 h-2.5 rounded-full" style="width: ${percentage}%"></div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm ${statusClass}">${status}</td>
                `;
                materialsStatusTable.appendChild(row);
            });
        }

        // Setup event listeners
        function setupEventListeners() {
            // Toggle sidebar
            document.getElementById('toggleSidebar').addEventListener('click', toggleSidebar);
            
            // Toggle theme
            document.getElementById('toggleTheme').addEventListener('click', toggleTheme);
            
            // Material photo upload
            document.getElementById('materialPhoto').addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        document.getElementById('materialPreviewImage').src = event.target.result;
                        document.getElementById('materialPhotoPreview').classList.remove('hidden');
                    };
                    reader.readAsDataURL(file);
                }
            });
            
            // Product photos upload
            document.getElementById('productPhotos').addEventListener('change', function(e) {
                const files = e.target.files;
                const previewContainer = document.getElementById('productPhotosPreview');
                previewContainer.innerHTML = '';
                
                if (files.length > 0) {
                    for (let i = 0; i < Math.min(files.length, 3); i++) {
                        const reader = new FileReader();
                        reader.onload = function(event) {
                            const img = document.createElement('img');
                            img.src = event.target.result;
                            img.className = 'h-20 w-full object-cover rounded-md lazy-load';
                            img.loading = 'lazy';
                            previewContainer.appendChild(img);
                        };
                        reader.readAsDataURL(files[i]);
                    }
                    previewContainer.classList.remove('hidden');
                }
            });
            
            // Image viewer
            document.querySelectorAll('img').forEach(img => {
                img.addEventListener('click', function() {
                    if (this.src && !this.src.includes('placeholder')) {
                        document.getElementById('viewerImage').src = this.src;
                        document.getElementById('imageViewer').classList.remove('hidden');
                        document.getElementById('imageViewer').style.display = 'flex';
                    }
                });
            });
            
            // Close image viewer
            document.getElementById('imageViewer').addEventListener('click', function(e) {
                if (e.target === this || e.target.closest('button')) {
                    this.classList.add('hidden');
                    this.style.display = 'none';
                }
            });
            
            // Color picker
            document.getElementById('materialColor').addEventListener('input', function(e) {
                document.getElementById('colorPreview').style.backgroundColor = e.target.value;
            });
            
            // Telegram notifications toggle
            document.getElementById('telegramNotifications').addEventListener('change', function(e) {
                const telegramSettings = document.getElementById('telegramSettings');
                if (e.target.checked) {
                    telegramSettings.classList.remove('hidden');
                } else {
                    telegramSettings.classList.add('hidden');
                }
            });
        }

        // Show section
        function showSection(sectionId) {
            document.querySelectorAll('.section-content').forEach(section => {
                section.classList.add('hidden');
            });
            document.getElementById(`${sectionId}-section`).classList.remove('hidden');
        }

        // Toggle sidebar
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.getElementById('mainContent');
            
            if (sidebar.classList.contains('collapsed')) {
                sidebar.classList.remove('collapsed');
                mainContent.classList.remove('ml-16');
                mainContent.classList.add('ml-64');
            } else {
                sidebar.classList.add('collapsed');
                mainContent.classList.remove('ml-64');
                mainContent.classList.add('ml-16');
            }
        }

        // Toggle theme
        function toggleTheme() {
            const body = document.body;
            const toggleThemeButton = document.getElementById('toggleTheme');
            
            if (body.classList.contains('dark-mode')) {
                body.classList.remove('dark-mode');
                body.classList.add('light-mode');
                toggleThemeButton.innerHTML = `
                    <i class="fas fa-sun mr-3 sidebar-icon"></i>
                    <span class="sidebar-text">Светлая тема</span>
                `;
            } else {
                body.classList.remove('light-mode');
                body.classList.add('dark-mode');
                toggleThemeButton.innerHTML = `
                    <i class="fas fa-moon mr-3 sidebar-icon"></i>
                    <span class="sidebar-text">Темная тема</span>
                `;
            }
        }

        // Format date
        function formatDate(dateString) {
            const options = { year: 'numeric', month: 'short', day: 'numeric' };
            return new Date(dateString).toLocaleDateString('ru-RU', options);
        }

        // Get status color
        function getStatusColor(status) {
            switch (status) {
                case 'В производстве': return 'yellow';
                case 'В продаже': return 'blue';
                case 'Продан': return 'green';
                default: return 'gray';
            }
        }

        // Material CRUD operations
        function showAddMaterialModal() {
            document.getElementById('addMaterialModal').classList.remove('hidden');
            document.getElementById('materialPhotoPreview').classList.add('hidden');
            document.getElementById('materialName').value = '';
            document.getElementById('materialPrice').value = '';
            document.getElementById('materialColor').value = '#cccccc';
            document.getElementById('colorPreview').style.backgroundColor = '#cccccc';
            document.getElementById('materialDate').value = '';
            document.getElementById('materialAmount').value = '';
            document.getElementById('materialPhoto').value = '';
            
            // Reset save button
            const saveButton = document.getElementById('saveMaterialButton');
            saveButton.textContent = 'Сохранить';
            saveButton.onclick = saveMaterial;
        }

        function hideAddMaterialModal() {
            document.getElementById('addMaterialModal').classList.add('hidden');
        }

        async function saveMaterial() {
            try {
                const name = document.getElementById('materialName').value;
                const price = parseFloat(document.getElementById('materialPrice').value);
                const color = document.getElementById('materialColor').value;
                const date = document.getElementById('materialDate').value;
                const amount = parseFloat(document.getElementById('materialAmount').value);
                const photoInput = document.getElementById('materialPhoto');
                
                if (!name || !price || !date || !amount) {
                    alert('Пожалуйста, заполните все обязательные поля');
                    return;
                }
                
                let photo = 'https://via.placeholder.com/150?text=Material';
                if (photoInput.files.length > 0) {
                    const file = photoInput.files[0];
                    photo = await readFileAsDataURL(file);
                }
                
                const materialsData = await getAll('materials');
                const newId = materialsData.length > 0 ? Math.max(...materialsData.map(m => m.id)) + 1 : 1;
                
                const newMaterial = {
                    id: newId,
                    name,
                    price,
                    color,
                    date,
                    amount,
                    initialAmount: amount,
                    photo
                };
                
                materialsData.push(newMaterial);
                await saveAll('materials', materialsData);
                
                hideAddMaterialModal();
                renderMaterialsTable();
                updateDashboard();
                initCharts();
            } catch (error) {
                console.error('Error saving material:', error);
                alert('Ошибка при сохранении материала: ' + error.message);
            }
        }

        function editMaterial(id) {
            const material = materials.find(m => m.id === id);
            if (!material) return;
            
            document.getElementById('addMaterialModal').classList.remove('hidden');
            document.getElementById('materialName').value = material.name;
            document.getElementById('materialPrice').value = material.price;
            document.getElementById('materialColor').value = material.color || '#cccccc';
            document.getElementById('colorPreview').style.backgroundColor = material.color || '#cccccc';
            document.getElementById('materialDate').value = material.date;
            document.getElementById('materialAmount').value = material.amount;
            
            if (material.photo && !material.photo.startsWith('http')) {
                document.getElementById('materialPreviewImage').src = material.photo;
                document.getElementById('materialPhotoPreview').classList.remove('hidden');
            } else {
                document.getElementById('materialPhotoPreview').classList.add('hidden');
            }
            
            // Change save button to update
            const saveButton = document.getElementById('saveMaterialButton');
            saveButton.textContent = 'Обновить';
            saveButton.onclick = async function() {
                await updateMaterial(id);
            };
        }

        async function updateMaterial(id) {
            try {
                const materialsData = await getAll('materials');
                const materialIndex = materialsData.findIndex(m => m.id === id);
                if (materialIndex === -1) return;
                
                const name = document.getElementById('materialName').value;
                const price = parseFloat(document.getElementById('materialPrice').value);
                const color = document.getElementById('materialColor').value;
                const date = document.getElementById('materialDate').value;
                const amount = parseFloat(document.getElementById('materialAmount').value);
                const photoInput = document.getElementById('materialPhoto');
                
                if (!name || !price || !date || !amount) {
                    alert('Пожалуйста, заполните все обязательные поля');
                    return;
                }
                
                let photo = materialsData[materialIndex].photo;
                if (photoInput.files.length > 0) {
                    photo = await readFileAsDataURL(photoInput.files[0]);
                }
                
                materialsData[materialIndex] = {
                    ...materialsData[materialIndex],
                    name,
                    price,
                    color,
                    date,
                    amount,
                    photo
                };
                
                await saveAll('materials', materialsData);
                
                hideAddMaterialModal();
                renderMaterialsTable();
                updateDashboard();
                initCharts();
            } catch (error) {
                console.error('Error updating material:', error);
                alert('Ошибка при обновлении материала: ' + error.message);
            }
        }

        async function deleteMaterial(id) {
            if (confirm('Вы уверены, что хотите удалить этот материал?')) {
                try {
                    // Delete material
                    const materialsData = await getAll('materials');
                    const newMaterials = materialsData.filter(m => m.id !== id);
                    await saveAll('materials', newMaterials);
                    
                    // Delete related products
                    const productsData = await getAll('products');
                    const newProducts = productsData.filter(p => p.materialId !== id);
                    await saveAll('products', newProducts);
                    
                    // Reload data
                    materials = await getAll('materials');
                    products = await getAll('products');
                    
                    renderMaterialsTable();
                    renderProductsGrid();
                    updateDashboard();
                    initCharts();
                } catch (error) {
                    console.error('Error deleting material:', error);
                    alert('Ошибка при удалении материала: ' + error.message);
                }
            }
        }

        // Product CRUD operations
        function showAddProductModal() {
            document.getElementById('addProductModal').classList.remove('hidden');
            document.getElementById('productPhotosPreview').classList.add('hidden');
            document.getElementById('productName').value = '';
            document.getElementById('productWeight').value = '';
            document.getElementById('productPrice').value = '';
            document.getElementById('productDate').value = '';
            document.getElementById('productStatus').value = 'В продаже';
            document.getElementById('productPhotos').value = '';
            document.getElementById('productOrderNumber').value = '';
            document.getElementById('productCustomerName').value = '';
            document.getElementById('productCustomerPhone').value = '';
            document.getElementById('productComments').value = '';
            
            // Fill materials dropdown
            const materialSelect = document.getElementById('productMaterial');
            materialSelect.innerHTML = '';
            materials.forEach(material => {
                const option = document.createElement('option');
                option.value = material.id;
                option.textContent = material.name;
                materialSelect.appendChild(option);
            });
        }

        function hideAddProductModal() {
            document.getElementById('addProductModal').classList.add('hidden');
        }

        async function saveProduct() {
            try {
                const name = document.getElementById('productName').value;
                const materialId = parseInt(document.getElementById('productMaterial').value);
                const weight = parseFloat(document.getElementById('productWeight').value);
                const price = parseFloat(document.getElementById('productPrice').value);
                const date = document.getElementById('productDate').value;
                const status = document.getElementById('productStatus').value;
                const orderNumber = document.getElementById('productOrderNumber').value;
                const customerName = document.getElementById('productCustomerName').value;
                const customerPhone = document.getElementById('productCustomerPhone').value;
                const comments = document.getElementById('productComments').value;
                const photosInput = document.getElementById('productPhotos');
                
                if (!name || !materialId || !weight || !price || !date || !status) {
                    alert('Пожалуйста, заполните все обязательные поля');
                    return;
                }
                
                let photos = ['https://via.placeholder.com/150?text=Product'];
                if (photosInput.files.length > 0) {
                    photos = [];
                    for (let i = 0; i < Math.min(photosInput.files.length, 3); i++) {
                        photos.push(await readFileAsDataURL(photosInput.files[i]));
                    }
                }
                
                const productsData = await getAll('products');
                const newId = productsData.length > 0 ? Math.max(...productsData.map(p => p.id)) + 1 : 1;
                
                const newProduct = {
                    id: newId,
                    name,
                    materialId,
                    weight,
                    price,
                    date,
                    status,
                    orderNumber,
                    customerName,
                    customerPhone,
                    comments,
                    photos
                };
                
                productsData.push(newProduct);
                await saveAll('products', productsData);
                
                hideAddProductModal();
                renderProductsGrid();
                updateDashboard();
                initCharts();
            } catch (error) {
                console.error('Error saving product:', error);
                alert('Ошибка при сохранении продукта: ' + error.message);
            }
        }

        function editProduct(id) {
            const product = products.find(p => p.id === id);
            if (!product) return;
            
            document.getElementById('addProductModal').classList.remove('hidden');
            document.getElementById('productName').value = product.name;
            document.getElementById('productWeight').value = product.weight;
            document.getElementById('productPrice').value = product.price;
            document.getElementById('productDate').value = product.date;
            document.getElementById('productStatus').value = product.status;
            document.getElementById('productOrderNumber').value = product.orderNumber || '';
            document.getElementById('productCustomerName').value = product.customerName || '';
            document.getElementById('productCustomerPhone').value = product.customerPhone || '';
            document.getElementById('productComments').value = product.comments || '';
            
            // Fill materials dropdown
            const materialSelect = document.getElementById('productMaterial');
            materialSelect.innerHTML = '';
            materials.forEach(material => {
                const option = document.createElement('option');
                option.value = material.id;
                option.textContent = material.name;
                option.selected = material.id === product.materialId;
                materialSelect.appendChild(option);
            });
            
            // Show photos preview
            const previewContainer = document.getElementById('productPhotosPreview');
            previewContainer.innerHTML = '';
            
            if (product.photos && product.photos.length > 0) {
                product.photos.forEach(photo => {
                    const img = document.createElement('img');
                    img.src = photo;
                    img.className = 'h-20 w-full object-cover rounded-md lazy-load';
                    img.loading = 'lazy';
                    previewContainer.appendChild(img);
                });
                previewContainer.classList.remove('hidden');
            } else {
                previewContainer.classList.add('hidden');
            }
            
            // Change save button to update
            const saveButton = document.getElementById('saveProductButton');
            saveButton.textContent = 'Обновить';
            saveButton.onclick = async function() {
                await updateProduct(id);
            };
        }

        async function updateProduct(id) {
            try {
                const productsData = await getAll('products');
                const productIndex = productsData.findIndex(p => p.id === id);
                if (productIndex === -1) return;
                
                const name = document.getElementById('productName').value;
                const materialId = parseInt(document.getElementById('productMaterial').value);
                const weight = parseFloat(document.getElementById('productWeight').value);
                const price = parseFloat(document.getElementById('productPrice').value);
                const date = document.getElementById('productDate').value;
                const status = document.getElementById('productStatus').value;
                const orderNumber = document.getElementById('productOrderNumber').value;
                const customerName = document.getElementById('productCustomerName').value;
                const customerPhone = document.getElementById('productCustomerPhone').value;
                const comments = document.getElementById('productComments').value;
                const photosInput = document.getElementById('productPhotos');
                
                if (!name || !materialId || !weight || !price || !date || !status) {
                    alert('Пожалуйста, заполните все обязательные поля');
                    return;
                }
                
                let photos = productsData[productIndex].photos;
                if (photosInput.files.length > 0) {
                    photos = [];
                    for (let i = 0; i < Math.min(photosInput.files.length, 3); i++) {
                        photos.push(await readFileAsDataURL(photosInput.files[i]));
                    }
                }
                
                productsData[productIndex] = {
                    ...productsData[productIndex],
                    name,
                    materialId,
                    weight,
                    price,
                    date,
                    status,
                    orderNumber,
                    customerName,
                    customerPhone,
                    comments,
                    photos
                };
                
                await saveAll('products', productsData);
                
                hideAddProductModal();
                renderProductsGrid();
                updateDashboard();
                initCharts();
            } catch (error) {
                console.error('Error updating product:', error);
                alert('Ошибка при обновлении продукта: ' + error.message);
            }
        }

        async function deleteProduct(id) {
            if (confirm('Вы уверены, что хотите удалить этот продукт?')) {
                try {
                    const productsData = await getAll('products');
                    const newProducts = productsData.filter(p => p.id !== id);
                    await saveAll('products', newProducts);
                    
                    // Delete related sales
                    const salesData = await getAll('sales');
                    const newSales = salesData.filter(s => s.productId !== id);
                    await saveAll('sales', newSales);
                    
                    // Reload data
                    products = await getAll('products');
                    sales = await getAll('sales');
                    
                    renderProductsGrid();
                    renderSalesTable();
                    updateDashboard();
                    initCharts();
                } catch (error) {
                    console.error('Error deleting product:', error);
                    alert('Ошибка при удалении продукта: ' + error.message);
                }
            }
        }

        // Show product photos
        function showProductPhotos(id) {
            const product = products.find(p => p.id === id);
            if (!product || !product.photos || product.photos.length === 0) return;
            
            // Create modal with larger images
            const modalHtml = `
                <div id="productPhotosModal" class="fixed inset-0 bg-black bg-opacity-75 z-50 flex items-center justify-center">
                    <div class="max-w-4xl w-full p-4">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-white text-lg">${product.name}</h3>
                            <button onclick="closeProductPhotosModal()" class="text-white text-xl">&times;</button>
                        </div>
                        <div class="grid grid-cols-1 gap-4">
                            ${product.photos.map(photo => `
                                <img src="${photo}" class="w-full rounded-lg lazy-load" loading="lazy">
                            `).join('')}
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalHtml);
        }

        function closeProductPhotosModal() {
            const modal = document.getElementById('productPhotosModal');
            if (modal) modal.remove();
        }

        // Sales operations
        function filterProducts() {
            renderProductsGrid(document.getElementById('productFilterStatus').value);
        }

        function filterSales() {
            const from = document.getElementById('salesDateFrom').value;
            const to = document.getElementById('salesDateTo').value;
            renderSalesTable(from, to);
        }

        async function deleteSale(id) {
            if(confirm('Удалить продажу?')) {
                try {
                    const salesData = await getAll('sales');
                    const newSales = salesData.filter(s => s.id !== id);
                    await saveAll('sales', newSales);
                    
                    sales = await getAll('sales');
                    renderSalesTable();
                    updateDashboard();
                } catch (error) {
                    console.error('Error deleting sale:', error);
                    alert('Ошибка при удалении продажи: ' + error.message);
                }
            }
        }

        // Cost calculator functions
        function populateCostMaterialDropdown() {
            // Нет необходимости заполнять выпадающий список материалов
            // так как калькулятор теперь не привязан к материалам
        }

        function saveCostSettings() {
            costSettings = {
                electricity: parseFloat(document.getElementById('electricityCost').value) || 5.0,
                depreciation: parseFloat(document.getElementById('depreciationCost').value) || 50.0,
                other: parseFloat(document.getElementById('otherCost').value) || 20.0
            };
            
            saveAll('costSettings', [costSettings]);
            alert('Настройки сохранены');
        }

        function calculateCost() {
            const plasticCostPerKg = parseFloat(document.getElementById('plasticCostPerKg').value);
            const weight = parseFloat(document.getElementById('costWeight').value);
            const time = parseFloat(document.getElementById('costTime').value);
            
            if (!plasticCostPerKg || !weight || !time) {
                alert('Пожалуйста, заполните все поля');
                return;
            }
            
            // Calculate plastic cost
            const plasticCost = (weight / 1000) * plasticCostPerKg;
            
            // Calculate electricity cost (assuming 0.3 kW average power usage)
            const electricityCost = time * costSettings.electricity * 0.3;
            
            // Calculate depreciation
            const depreciationCost = time * costSettings.depreciation;
            
            // Calculate other costs
            const otherCost = time * costSettings.other;
            
            // Total cost
            const totalCost = plasticCost + electricityCost + depreciationCost + otherCost;
            
            // Display results
            document.getElementById('plasticCost').textContent = `${plasticCost.toFixed(2)} ₽`;
            document.getElementById('electricityCostResult').textContent = `${electricityCost.toFixed(2)} ₽`;
            document.getElementById('depreciationCostResult').textContent = `${depreciationCost.toFixed(2)} ₽`;
            document.getElementById('otherCostResult').textContent = `${otherCost.toFixed(2)} ₽`;
            document.getElementById('totalCost').textContent = `${totalCost.toFixed(2)} ₽`;
            
            // Show formula
            document.getElementById('costFormula').textContent = 
                `Формула: (${weight}г / 1000) * ${plasticCostPerKg}₽ + ${time}ч * ${0.3 * costSettings.electricity}₽ + ${time}ч * ${costSettings.depreciation}₽ + ${time}ч * ${costSettings.other}₽`;
        }

        // Data export/import
        async function exportData() {
            try {
                const data = {
                    materials: await getAll('materials'),
                    products: await getAll('products'),
                    sales: await getAll('sales'),
                    costSettings: await getAll('costSettings')
                };
                
                const dataStr = JSON.stringify(data);
                const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
                
                const exportFile = document.createElement('a');
                exportFile.setAttribute('href', dataUri);
                exportFile.setAttribute('download', '3d_print_data.json');
                exportFile.click();
            } catch (error) {
                console.error('Error exporting data:', error);
                alert('Ошибка при экспорте данных: ' + error.message);
            }
        }

        async function importData() {
            const file = document.getElementById('importFile').files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = async function(e) {
                try {
                    const data = JSON.parse(e.target.result);
                    
                    if (data.materials) await saveAll('materials', data.materials);
                    if (data.products) await saveAll('products', data.products);
                    if (data.sales) await saveAll('sales', data.sales);
                    if (data.costSettings) await saveAll('costSettings', data.costSettings ? [data.costSettings] : []);
                    
                    // Reload data
                    materials = await getAll('materials');
                    products = await getAll('products');
                    sales = await getAll('sales');
                    
                    renderMaterialsTable();
                    renderProductsGrid();
                    renderSalesTable();
                    updateDashboard();
                    initCharts();
                    populateCostMaterialDropdown();
                    
                    alert('Данные успешно импортированы');
                } catch (error) {
                    alert('Ошибка при импорте данных: ' + error.message);
                }
            };
            reader.readAsText(file);
        }

        // Utility function to read file as data URL
        function readFileAsDataURL(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = (e) => resolve(e.target.result);
                reader.onerror = (e) => reject(e);
                reader.readAsDataURL(file);
            });
        }

        // Start app
        window.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>

исправь код