<!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-photo { width: 80px; height: 80px; object-fit: cover; }
        .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; }
        .materials-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 1rem; }
        .material-item { border: 1px solid #e5e7eb; padding: 0.5rem; border-radius: 0.375rem; cursor: pointer; }
        .material-item.selected { border-color: #2563eb; background-color: #eff6ff; }
    </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-2 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="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                    <!-- Settings -->
                    <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>
                    
                    <!-- Manual Calculator -->
                    <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="manualMaterialCost" 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="manualWeight" 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="manualTime" 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="calculateManualCost()" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md">Рассчитать</button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Material-based Calculator -->
                    <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>
                                <select id="costMaterial" 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">
                                    <!-- Filled by 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="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>
                    
                    <!-- Markup Section -->
                    <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>
                                <input type="number" id="baseCost" 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" readonly>
                            </div>
                            <div class="flex space-x-4">
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Тип наценки</label>
                                    <select id="markupType" 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="percent">Процент</option>
                                        <option value="fixed">Рубли</option>
                                    </select>
                                </div>
                                <div class="flex-1">
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Значение</label>
                                    <input type="number" id="markupValue" 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>
                            <div>
                                <button onclick="calculateMarkup()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md">Рассчитать цену</button>
                            </div>
                            <div class="mt-4">
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Рекомендованная цена</label>
                                <input type="number" id="recommendedPrice" 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>

            <!-- 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>
                </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">
                                <input type="color" id="materialColor" class="h-10 w-10 rounded-full border border-gray-300 mr-2">
                                <span id="colorHexValue">#000000</span>
                            </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">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button 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-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="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">
                                <!-- Filled by 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="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>
                            <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">
                                <!-- Filled by JavaScript -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button 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 Storage -->
    <div id="imageStorage" class="hidden"></div>

    <script>
        // Initialize data
        let materials = [];
        let products = [];
        let sales = [];
        let images = {}; // For storing image data
        let currentTheme = 'dark';
        let sidebarCollapsed = false;
        let costSettings = {
            electricity: 5.0,
            depreciation: 50.0,
            other: 20.0
        };

        // Sample initial data
        function initializeSampleData() {
            if (localStorage.getItem('materials') === null) {
                materials = [
                    { id: 1, name: 'PLA', price: 1200, date: '2023-05-15', amount: 500, initialAmount: 1000, photo: 'https://via.placeholder.com/150?text=PLA', color: '#ffffff' },
                    { id: 2, name: 'PETG', price: 1500, date: '2023-06-20', amount: 300, initialAmount: 800, photo: 'https://via.placeholder.com/150?text=PETG', color: '#f56565' },
                    { id: 3, name: 'ABS', price: 1300, date: '2023-07-10', amount: 100, initialAmount: 500, photo: 'https://via.placeholder.com/150?text=ABS', color: '#48bb78' }
                ];
                localStorage.setItem('materials', JSON.stringify(materials));
            } else {
                materials = JSON.parse(localStorage.getItem('materials'));
            }

            if (localStorage.getItem('products') === null) {
                products = [
                    { 
                        id: 1, 
                        name: 'Кронштейн для полки', 
                        materialId: 1, 
                        weight: 50, 
                        price: 800, 
                        date: '2023-08-01', 
                        status: 'В продаже', 
                        photos: [
                            'https://via.placeholder.com/150?text=Кронштейн1',
                            'https://via.placeholder.com/150?text=Кронштейн2'
                        ] 
                    },
                    { 
                        id: 2, 
                        name: 'Держатель для лейки душа', 
                        materialId: 2, 
                        weight: 48, 
                        price: 400, 
                        date: '2023-08-05', 
                        status: 'В продаже', 
                        photos: [
                            'https://via.placeholder.com/150?text=Держатель1',
                            'https://via.placeholder.com/150?text=Держатель2'
                        ] 
                    },
                    { 
                        id: 3, 
                        name: 'Держатель для лейки душа', 
                        materialId: 2, 
                        weight: 48, 
                        price: 400, 
                        date: '2023-08-10', 
                        status: 'В продаже', 
                        photos: [
                            'https://via.placeholder.com/150?text=Держатель3',
                            'https://via.placeholder.com/150?text=Держатель4'
                        ] 
                    }
                ];
                localStorage.setItem('products', JSON.stringify(products));
            } else {
                products = JSON.parse(localStorage.getItem('products'));
            }

            if (localStorage.getItem('sales') === null) {
                sales = [
                    { id: 1, productId: 2, date: '2023-08-15', price: 400, profit: 344 },
                    { id: 2, productId: 1, date: '2023-08-20', price: 800, profit: 620 },
                    { id: 3, productId: 3, date: '2023-08-25', price: 400, profit: 344 }
                ];
                localStorage.setItem('sales', JSON.stringify(sales));
            } else {
                sales = JSON.parse(localStorage.getItem('sales'));
            }
            
            if (localStorage.getItem('costSettings') === null) {
                localStorage.setItem('costSettings', JSON.stringify(costSettings));
            } else {
                costSettings = JSON.parse(localStorage.getItem('costSettings'));
            }
            
            // Load images from storage
            if (localStorage.getItem('images') !== null) {
                images = JSON.parse(localStorage.getItem('images'));
            }
        }

        // Initialize the app
        function initApp() {
            initializeSampleData();
            updateDashboard();
            renderMaterialsTable();
            renderProductsGrid();
            renderSalesTable();
            initCharts();
            setupEventListeners();
            populateCostMaterialDropdown();
            populateMaterialDropdown();
            loadCostSettings();
        }

        // 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.getElement.computedStyleMap('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);
                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 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>
                `;
                recentSalesTable.appendChild(row);
            });
        }

        // Render materials table
        function renderMaterialsTable() {
            const table = document.getElementById('materialsTable');
            table.innerHTML = '';
            
            materials.forEach(material => {
                // Convert hex color to RGB for tailwind
                const textColor = material.color ? `text-[${material.color}]` : 'text-gray-900';
                
                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 || 'https://via.placeholder.com/100?text=No+Photo'}" class="h-10 w-10 rounded-full object-cover">
                    </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">${material.price} ₽</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm ${textColor}">
                        <span class="color-sample" style="background-color: ${material.color || '#000000'}"></span>
                        ${material.color || 'Н/Д'}
                    </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);
            }
            
            filteredProducts.forEach(product => {
                const material = materials.find(m => m.id === product.materialId);
                const cost = (product.weight / 1000) * material.price;
                
                const card = document.createElement('div');
                card.className = 'bg-white dark:bg-gray-700 rounded-lg shadow overflow-hidden product-card';
                card.innerHTML = `
                    <div class="relative">
                        <div class="h-32 overflow-hidden">
                            ${product.photos && product.photos.length > 0 ? 
                                `<img src="${product.photos[0]}" class="w-full h-full object-cover">` : 
                                '<div class="w-full h-full bg-gray-200 flex items-center justify-center dark:bg-gray-600">Нет фото</div>'
                            }
                        </div>
                        <div class="absolute top-2 right-2 bg-${getStatusColor(product.status)}-500 text-white text-xs px-2 py-1 rounded">
                            ${product.status}
                        </div>
                    </div>
                    <div class="p-3">
                        <h3 class="text-sm font-semibold mb-1 dark:text-white">${product.name}</h3>
                        <div class="flex justify-between text-xs mb-0.5">
                            <span class="text-gray-600 dark:text-gray-300">Материал:</span>
                            <span class="font-medium dark:text-white">${material.name}</span>
                        </div>
                        <div class="flex justify-between text-xs mb-0.5">
                            <span class="text-gray-600 dark:text-gray-300">Вес:</span>
                            <span class="font-medium dark:text-white">${product.weight} г</span>
                        </div>
                        <div class="flex justify-between text-xs mb-0.5">
                            <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 text-xs mb-1.5">
                            <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">
                            <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 mr-1"></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 mr-1"></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 mr-1"></i> Удалить
                            </button>
                        </div>
                    </div>
                `;
                grid.appendChild(card);
            });
        }

        // 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);
                });
            }
            
            filteredSales.forEach(sale => {
                const product = products.find(p => p.id === sale.productId);
                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 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>
                `;
                table.appendChild(row);
            });
        }

        // 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);
                const material = materials.find(m => m.id === product.materialId);
                
                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 (!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-16 w-full object-cover rounded-md'; // Уменьшил размер
                            previewContainer.appendChild(img);
                        };
                        reader.readAsDataURL(files[i]);
                    }
                    previewContainer.classList.remove('hidden');
                }
            });
            
            // 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');
                }
            });
            
            // Color picker
            document.getElementById('materialColor').addEventListener('input', function(e) {
                document.getElementById('colorHexValue').textContent = e.target.value;
            });
        }

        // 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 (sidebarCollapsed) {
                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');
            }
            
            sidebarCollapsed = !sidebarCollapsed;
        }

        // Toggle theme
        function toggleTheme() {
            const body = document.body;
            const toggleThemeButton = document.getElementById('toggleTheme');
            
            if (currentTheme === 'dark') {
                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>
                `;
                currentTheme = 'light';
            } 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>
                `;
                currentTheme = 'dark';
            }
        }

        // 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 = '#000000';
            document.getElementById('colorHexValue').textContent = '#000000';
            document.getElementById('materialDate').value = '';
            document.getElementById('materialAmount').value = '';
            document.getElementById('materialPhoto').value = '';
        }

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

        function saveMaterial() {
            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 reader = new FileReader();
                reader.onload = function(e) {
                    const newMaterial = {
                        id: materials.length > 0 ? Math.max(...materials.map(m => m.id)) + 1 : 1,
                        name,
                        price,
                        color,
                        date,
                        amount,
                        initialAmount: amount,
                        photo: e.target.result
                    };
                    
                    materials.push(newMaterial);
                    localStorage.setItem('materials', JSON.stringify(materials));
                    
                    // Store image in local storage
                    if (!images) images = {};
                    images[`material_${newMaterial.id}`] = e.target.result;
                    localStorage.setItem('images', JSON.stringify(images));
                    
                    hideAddMaterialModal();
                    renderMaterialsTable();
                    updateDashboard();
                    initCharts();
                };
                reader.readAsDataURL(photoInput.files[0]);
            } else {
                const newMaterial = {
                    id: materials.length > 0 ? Math.max(...materials.map(m => m.id)) + 1 : 1,
                    name,
                    price,
                    color,
                    date,
                    amount,
                    initialAmount: amount,
                    photo
                };
                
                materials.push(newMaterial);
                localStorage.setItem('materials', JSON.stringify(materials));
                
                hideAddMaterialModal();
                renderMaterialsTable();
                updateDashboard();
                initCharts();
            }
        }

        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 || '#000000';
            document.getElementById('colorHexValue').textContent = material.color || '#000000';
            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.querySelector('#addMaterialModal button:first-of-type');
            saveButton.textContent = 'Обновить';
            saveButton.onclick = function() {
                updateMaterial(id);
            };
        }

        function updateMaterial(id) {
            const materialIndex = materials.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 = materials[materialIndex].photo;
            if (photoInput.files.length > 0) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    materials[materialIndex] = {
                        ...materials[materialIndex],
                        name,
                        price,
                        color,
                        date,
                        amount,
                        photo: e.target.result
                    };
                    
                    localStorage.setItem('materials', JSON.stringify(materials));
                    
                    // Update image in local storage
                    if (!images) images = {};
                    images[`material_${id}`] = e.target.result;
                    localStorage.setItem('images', JSON.stringify(images));
                    
                    hideAddMaterialModal();
                    renderMaterialsTable();
                    updateDashboard();
                    initCharts();
                };
                reader.readAsDataURL(photoInput.files[0]);
            } else {
                materials[materialIndex] = {
                    ...materials[materialIndex],
                    name,
                    price,
                    color,
                    date,
                    amount,
                    photo
                };
                
                localStorage.setItem('materials', JSON.stringify(materials));
                
                hideAddMaterialModal();
                renderMaterialsTable();
                updateDashboard();
                initCharts();
            }
        }

        function deleteMaterial(id) {
            if (confirm('Вы уверены, что хотите удалить этот материал?')) {
                materials = materials.filter(m => m.id !== id);
                localStorage.setItem('materials', JSON.stringify(materials));
                
                // Also delete products that use this material
                products = products.filter(p => p.materialId !== id);
                localStorage.setItem('products', JSON.stringify(products));
                
                // Remove any images associated with this material
                if (images && images[`material_${id}`]) {
                    delete images[`material_${id}`];
                    localStorage.setItem('images', JSON.stringify(images));
                }
                
                renderMaterialsTable();
                renderProductsGrid();
                updateDashboard();
                initCharts();
            }
        }

        // 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 = '';
            
            // 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);
            });
            
            // Set save button to add
            const saveButton = document.querySelector('#addProductModal button:first-of-type');
            saveButton.textContent = 'Сохранить';
            saveButton.onclick = saveProduct;
        }

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

        function saveProduct() {
            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 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++) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        photos.push(e.target.result);
                        
                        // Store image in local storage
                        if (!images) images = {};
                        images[`product_${newProduct.id}_${i}`] = e.target.result;
                        localStorage.setItem('images', JSON.stringify(images));
                    };
                    reader.readAsDataURL(photosInput.files[i]);
                }
            }
            
            const newProduct = {
                id: products.length > 0 ? Math.max(...products.map(p => p.id)) + 1 : 1,
                name,
                materialId,
                weight,
                price,
                date,
                status,
                photos
            };
            
            products.push(newProduct);
            localStorage.setItem('products', JSON.stringify(products));
            
            hideAddProductModal();
            renderProductsGrid();
            updateDashboard();
            initCharts();
        }

        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;
            
            // 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-16 w-full object-cover rounded-md'; // Уменьшил размер
                    previewContainer.appendChild(img);
                });
                previewContainer.classList.remove('hidden');
            } else {
                previewContainer.classList.add('hidden');
            }
            
            // Change save button to update
            const saveButton = document.querySelector('#addProductModal button:first-of-type');
            saveButton.textContent = 'Обновить';
            saveButton.onclick = function() {
                updateProduct(id);
            };
        }

        function updateProduct(id) {
            const productIndex = products.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 photosInput = document.getElementById('productPhotos');
            
            if (!name || !materialId || !weight || !price || !date || !status) {
                alert('Пожалуйста, заполните все обязательные поля');
                return;
            }
            
            let photos = products[productIndex].photos;
            if (photosInput.files.length > 0) {
                photos = [];
                for (let i = 0; i < Math.min(photosInput.files.length, 3); i++) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        photos.push(e.target.result);
                        
                        // Store image in local storage
                        if (!images) images = {};
                        images[`product_${id}_${i}`] = e.target.result;
                        localStorage.setItem('images', JSON.stringify(images));
                    };
                    reader.readAsDataURL(photosInput.files[i]);
                }
            }
            
            products[productIndex] = {
                ...products[productIndex],
                name,
                materialId,
                weight,
                price,
                date,
                status,
                photos
            };
            
            localStorage.setItem('products', JSON.stringify(products));
            
            hideAddProductModal();
            renderProductsGrid();
            updateDashboard();
            initCharts();
        }

        function deleteProduct(id) {
            if (confirm('Вы уверены, что хотите удалить этот продукт?')) {
                products = products.filter(p => p.id !== id);
                localStorage.setItem('products', JSON.stringify(products));
                
                // Also delete sales of this product
                sales = sales.filter(s => s.productId !== id);
                localStorage.setItem('sales', JSON.stringify(sales));
                
                // Remove any images associated with this product
                if (images) {
                    for (let i = 0; i < 3; i++) {
                        if (images[`product_${id}_${i}`]) {
                            delete images[`product_${id}_${i}`];
                        }
                    }
                    localStorage.setItem('images', JSON.stringify(images));
                }
                
                renderProductsGrid();
                renderSalesTable();
                updateDashboard();
                initCharts();
            }
        }

        // 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">
                            `).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);
        }

        function deleteSale(id) {
            if(confirm('Удалить продажу?')) {
                sales = sales.filter(s => s.id !== id);
                localStorage.setItem('sales', JSON.stringify(sales));
                renderSalesTable();
                updateDashboard();
            }
        }

        // Cost calculator functions
        function populateCostMaterialDropdown() {
            const select = document.getElementById('costMaterial');
            select.innerHTML = '';
            
            materials.forEach(material => {
                const option = document.createElement('option');
                option.value = material.id;
                option.textContent = material.name;
                select.appendChild(option);
            });
        }

        function loadCostSettings() {
            if (localStorage.getItem('costSettings') !== null) {
                costSettings = JSON.parse(localStorage.getItem('costSettings'));
                document.getElementById('electricityCost').value = costSettings.electricity;
                document.getElementById('depreciationCost').value = costSettings.depreciation;
                document.getElementById('otherCost').value = costSettings.other;
            }
        }

        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
            };
            
            localStorage.setItem('costSettings', JSON.stringify(costSettings));
            alert('Настройки сохранены');
        }

        function calculateCost() {
            const materialId = parseInt(document.getElementById('costMaterial').value);
            const weight = parseFloat(document.getElementById('costWeight').value);
            const time = parseFloat(document.getElementById('costTime').value);
            
            if (!materialId || !weight || !time) {
                alert('Пожалуйста, заполните все поля');
                return;
            }
            
            const material = materials.find(m => m.id === materialId);
            if (!material) return;
            
            // Calculate plastic cost
            const plasticCost = (weight / 1000) * material.price;
            
            // 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) * ${material.price}₽ + ${time}ч * ${0.3 * costSettings.electricity}₽ + ${time}ч * ${costSettings.depreciation}₽ + ${time}ч * ${costSettings.other}₽`;
        }

        function calculateManualCost() {
            const materialCost = parseFloat(document.getElementById('manualMaterialCost').value);
            const weight = parseFloat(document.getElementById('manualWeight').value);
            const time = parseFloat(document.getElementById('manualTime').value);
            
            if (!materialCost || !weight || !time) {
                alert('Пожалуйста, заполните все поля');
                return;
            }
            
            // Calculate plastic cost
            const plasticCost = (weight / 1000) * materialCost;
            
            // 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) * ${materialCost}₽ + ${time}ч * ${0.3 * costSettings.electricity}₽ + ${time}ч * ${costSettings.depreciation}₽ + ${time}ч * ${costSettings.other}₽`;
        }

        function calculateMarkup() {
            const baseCost = parseFloat(document.getElementById('totalCost').textContent.replace(' ₽', ''));
            const markupType = document.getElementById('markupType').value;
            const markupValue = parseFloat(document.getElementById('markupValue').value);
            
            if (!baseCost || !markupValue) {
                alert('Пожалуйста, сначала рассчитайте себестоимость и укажите наценку');
                return;
            }
            
            let recommendedPrice;
            if (markupType === 'percent') {
                recommendedPrice = baseCost * (1 + markupValue / 100);
            } else {
                recommendedPrice = baseCost + markupValue;
            }
            
            document.getElementById('recommendedPrice').value = recommendedPrice.toFixed(2);
        }

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