<!-- Add Portfolio Item -->
<div class="max-w-5xl mx-auto">
    <div class="bg-white shadow rounded-lg">
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex items-center justify-between">
                <div>
                    <h3 class="text-xl font-semibold text-gray-900">
                        <i class="fas fa-plus-circle mr-2 text-blue-600"></i>
                        Добавить новый проект
                    </h3>
                    <p class="mt-1 text-sm text-gray-500">Заполните информацию о проекте для добавления в портфолио</p>
                </div>
                <div class="flex space-x-3">
                    <button type="button" onclick="saveDraft()" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i class="fas fa-save mr-2"></i>
                        Сохранить черновик
                    </button>
                    <a href="/admin/portfolio" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        <i class="fas fa-arrow-left mr-2"></i>
                        Назад к списку
                    </a>
                </div>
            </div>
        </div>
        
        <form id="portfolioForm" class="p-6">
            <!-- Progress indicator -->
            <div class="mb-8">
                <div class="flex items-center">
                    <div class="flex items-center text-blue-600 relative">
                        <div class="rounded-full h-8 w-8 bg-blue-600 text-white flex items-center justify-center text-sm font-medium">1</div>
                        <span class="ml-3 text-sm font-medium text-blue-600">Основная информация</span>
                    </div>
                    <div class="flex-1 mx-4 h-1 bg-gray-200"></div>
                    <div class="flex items-center text-gray-500">
                        <div class="rounded-full h-8 w-8 bg-gray-200 text-gray-600 flex items-center justify-center text-sm font-medium">2</div>
                        <span class="ml-3 text-sm font-medium text-gray-500">Медиа и изображения</span>
                    </div>
                    <div class="flex-1 mx-4 h-1 bg-gray-200"></div>
                    <div class="flex items-center text-gray-500">
                        <div class="rounded-full h-8 w-8 bg-gray-200 text-gray-600 flex items-center justify-center text-sm font-medium">3</div>
                        <span class="ml-3 text-sm font-medium text-gray-500">Публикация</span>
                    </div>
                </div>
            </div>

            <div class="space-y-8">
                <!-- Шаг 1: Основная информация -->
                <div class="bg-gray-50 rounded-lg p-6">
                    <h4 class="text-lg font-medium text-gray-900 mb-6">
                        <i class="fas fa-info-circle mr-2 text-blue-600"></i>
                        Основная информация о проекте
                    </h4>
                    
                    <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                        <!-- Title -->
                        <div class="sm:col-span-2">
                            <label for="title" class="block text-sm font-medium text-gray-700 mb-2">
                                Название проекта *
                                <span class="text-gray-500 font-normal">(отображается в портфолио)</span>
                            </label>
                            <input type="text" name="title" id="title" required 
                                   placeholder="Например: Интернет-магазин электроники TechStore"
                                   class="block w-full border-gray-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                            <p class="mt-1 text-sm text-gray-500">Используйте описательное название, которое четко передает суть проекта</p>
                        </div>
                        
                        <!-- Short Description -->
                        <div class="sm:col-span-2">
                            <label for="shortDescription" class="block text-sm font-medium text-gray-700 mb-2">
                                Краткое описание *
                                <span class="text-gray-500 font-normal">(1-2 предложения)</span>
                            </label>
                            <textarea name="shortDescription" id="shortDescription" rows="2" required
                                      placeholder="Современный интернет-магазин с удобной системой каталогов и интеграцией платежных систем"
                                      class="block w-full border-gray-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                                      maxlength="200"></textarea>
                            <div class="mt-1 flex justify-between text-sm text-gray-500">
                                <span>Отображается в превью проекта</span>
                                <span id="shortDescCount">0/200</span>
                            </div>
                        </div>
                        
                        <!-- Category -->
                        <div>
                            <label for="category" class="block text-sm font-medium text-gray-700 mb-2">Категория *</label>
                            <select name="category" id="category" required
                                    class="block w-full border-gray-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                                <option value="">Выберите категорию</option>
                                <% categories.forEach(cat => { %>
                                    <option value="<%= cat %>"><%= getCategoryName(cat) %></option>
                                <% }); %>
                            </select>
                        </div>
                        
                        <!-- Duration -->
                        <div>
                            <label for="duration" class="block text-sm font-medium text-gray-700 mb-2">
                                Длительность проекта
                                <span class="text-gray-500 font-normal">(в днях)</span>
                            </label>
                            <input type="number" name="duration" id="duration" min="1" max="365"
                                   placeholder="30"
                                   class="block w-full border-gray-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                        </div>
                        
                        <!-- Client Name -->
                        <div>
                            <label for="clientName" class="block text-sm font-medium text-gray-700 mb-2">
                                Название клиента
                                <span class="text-gray-500 font-normal">(необязательно)</span>
                            </label>
                            <input type="text" name="clientName" id="clientName" 
                                   placeholder="ООО «ТехноСтор»"
                                   class="block w-full border-gray-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                        </div>
                        
                        <!-- Demo URL -->
                        <div>
                            <label for="demoUrl" class="block text-sm font-medium text-gray-700 mb-2">
                                Ссылка на демо
                                <span class="text-gray-500 font-normal">(живая версия)</span>
                            </label>
                            <input type="url" name="demoUrl" id="demoUrl" 
                                   placeholder="https://techstore.example.com"
                                   class="block w-full border-gray-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                        </div>
                        
                        <!-- GitHub URL -->
                        <div>
                            <label for="githubUrl" class="block text-sm font-medium text-gray-700 mb-2">
                                GitHub репозиторий
                                <span class="text-gray-500 font-normal">(если публичный)</span>
                            </label>
                            <input type="url" name="githubUrl" id="githubUrl" 
                                   placeholder="https://github.com/username/project"
                                   class="block w-full border-gray-300 rounded-lg shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
                        </div>
                    </div>
                </div>
        
        <!-- Description -->
        <div>
            <label for="description" class="block text-sm font-medium text-gray-700">Подробное описание</label>
            <textarea name="description" id="description" rows="4" required
                      class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"></textarea>
        </div>
        
        <!-- Technologies -->
        <div>
            <label for="technologies" class="block text-sm font-medium text-gray-700">Технологии (через запятую)</label>
            <input type="text" name="technologies" id="technologies" 
                   placeholder="React, Node.js, PostgreSQL"
                   class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
        </div>
        
        <!-- Images -->
        <div>
            <label class="block text-sm font-medium text-gray-700">Изображения проекта</label>
            <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                <div class="space-y-1 text-center">
                    <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
                        <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    </svg>
                    <div class="flex text-sm text-gray-600">
                        <label for="images" class="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500">
                            <span>Загрузить файлы</span>
                            <input id="images" name="images" type="file" class="sr-only" multiple accept="image/*">
                        </label>
                        <p class="pl-1">или перетащите сюда</p>
                    </div>
                    <p class="text-xs text-gray-500">PNG, JPG, WEBP до 10MB</p>
                </div>
            </div>
            <div id="imagePreview" class="mt-4 grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4"></div>
        </div>
        
        <!-- Options -->
        <div class="flex items-center space-x-6">
            <div class="flex items-center">
                <input id="featured" name="featured" type="checkbox" 
                       class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                <label for="featured" class="ml-2 block text-sm text-gray-900">
                    Рекомендуемый проект
                </label>
            </div>
            
            <div class="flex items-center">
                <input id="isPublished" name="isPublished" type="checkbox" checked
                       class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                <label for="isPublished" class="ml-2 block text-sm text-gray-900">
                    Опубликовать
                </label>
            </div>
        </div>
        
        <!-- Submit Buttons -->
        <div class="flex justify-end space-x-3">
            <a href="/admin/portfolio" class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded">
                Отмена
            </a>
            <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                <i class="fas fa-save mr-1"></i>
                Сохранить
            </button>
        </div>
    </form>
</div>

<script>
document.getElementById('portfolioForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    // Convert technologies string to array
    const technologies = formData.get('technologies');
    if (technologies) {
        formData.set('technologies', JSON.stringify(technologies.split(',').map(t => t.trim())));
    }
    
    try {
        const response = await fetch('/api/admin/portfolio', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            window.location.href = '/admin/portfolio';
        } else {
            alert('Ошибка при создании проекта: ' + data.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Ошибка при создании проекта');
    }
});

// Image preview
document.getElementById('images').addEventListener('change', function(e) {
    const preview = document.getElementById('imagePreview');
    preview.innerHTML = '';
    
    for (let i = 0; i < e.target.files.length; i++) {
        const file = e.target.files[i];
        const reader = new FileReader();
        
        reader.onload = function(e) {
            const div = document.createElement('div');
            div.className = 'relative';
            div.innerHTML = `
                <img src="${e.target.result}" class="h-24 w-full object-cover rounded-md">
                <button type="button" onclick="this.parentElement.remove()" 
                        class="absolute top-0 right-0 -mt-2 -mr-2 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs">
                    ×
                </button>
            `;
            preview.appendChild(div);
        };
        
        reader.readAsDataURL(file);
    }
});
</script>