

<div class="form-manager">
    <div class="manager-header">
        <div class="header-content">
            <h1 class="content-title">Create New Project</h1>
            <p class="content-subtitle">Follow the steps to curate your new portfolio entry.</p>
        </div>
        <div class="header-actions">
            <a href="<?php echo base_url('admin/projects'); ?>" class="btn-action btn-outline">
                <i class="fas fa-arrow-left"></i>
                Back to Projects
            </a>
        </div>
    </div>

    <div class="form-card-container">
        <!-- Wizard Steps Indicator -->
        <div class="wizard-progress">
            <div class="step-item active" id="indicator1">
                <div class="step-circle">1</div>
                <div class="step-text">Basic Info</div>
            </div>
            <div class="step-line"></div>
            <div class="step-item" id="indicator2">
                <div class="step-circle">2</div>
                <div class="step-text">Media Upload</div>
            </div>
            <div class="step-line"></div>
            <div class="step-item" id="indicator3">
                <div class="step-circle">3</div>
                <div class="step-text">Thumbnail</div>
            </div>
        </div>

        <div class="wizard-content">
             <!-- Step 1: Basic Information -->
             <div class="wizard-step active" id="step1">
                <form id="basicInfoForm" class="modern-form">
                    <div class="form-grid-split">
                        <div class="form-column">
                            <div class="form-group-modern">
                                <label for="title">Project Title <span class="required-star">*</span></label>
                                <input type="text" id="title" name="title" class="form-control-modern" placeholder="e.g. Summer Campaign 2026" required autofocus>
                            </div>

                            <div class="form-row-modern">
                                <div class="form-group-modern">
                                    <label for="client_name">Client Name <span class="required-star">*</span></label>
                                    <input type="text" id="client_name" name="client_name" class="form-control-modern" placeholder="Select or type new..." list="clients_list" required>
                                    <datalist id="clients_list">
                                        <?php if(isset($clients) && !empty($clients)): ?>
                                            <?php foreach($clients as $c): ?>
                                                <option value="<?php echo htmlspecialchars($c->name); ?>">
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </datalist>
                                </div>
                                <div class="form-group-modern">
                                    <label for="model_name">Model Name</label>
                                    <input type="text" id="model_name" name="model_name" class="form-control-modern" placeholder="Optional">
                                </div>
                            </div>

                            <div class="form-group-modern">
                                <label for="description">Description</label>
                                <textarea id="description" name="description" class="form-control-modern" rows="5" placeholder="Project description..."></textarea>
                            </div>
                        </div>

                        <div class="form-column">
                            <div class="form-row-modern">
                                <div class="form-group-modern">
                                    <label for="shoot_date">Shoot Date</label>
                                    <input type="date" id="shoot_date" name="shoot_date" class="form-control-modern">
                                </div>
                                <div class="form-group-modern">
                                    <label for="project_size">Grid Size <span class="required-star">*</span></label>
                                    <select id="project_size" name="project_size" class="form-control-modern" required>
                                        <option value="small">Small</option>
                                        <option value="medium" selected>Medium</option>
                                        <option value="large">Large</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group-modern">
                                <label for="display_order">Display Order</label>
                                <input type="number" id="display_order" name="display_order" class="form-control-modern" value="0">
                            </div>

                            <div class="form-group-modern">
                                <div class="checkbox-wrapper">
                                    <input type="checkbox" id="is_featured" name="is_featured" value="1">
                                    <label for="is_featured">Feature this project on homepage</label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-footer-actions">
                        <button type="button" class="btn-action btn-primary" onclick="validateStep1()">
                            Next Step <i class="fas fa-arrow-right"></i>
                        </button>
                    </div>
                </form>
            </div>

            <!-- Step 2: Media Upload -->
             <div class="wizard-step" id="step2">
                <div class="upload-container">
                    <div class="upload-zone" id="uploadZone">
                        <div class="upload-content">
                            <i class="fas fa-cloud-upload-alt upload-icon"></i>
                            <h4>Drag & Drop Files Here</h4>
                            <p>Supports JPG, PNG, WEBP, MP4, MOV (Max 50MB)</p>
                            <button type="button" class="btn-action btn-outline btn-sm" onclick="document.getElementById('fileInput').click()">
                                Browse Files
                            </button>
                        </div>
                        <input type="file" id="fileInput" multiple accept="image/*,video/*" class="file-input-hidden">
                    </div>

                    <div class="upload-progress" id="uploadProgress" style="display: none;">
                        <div class="progress-bar">
                            <div class="progress-fill" id="progressFill"></div>
                        </div>
                        <div class="progress-text" id="progressText">Uploading...</div>
                    </div>

                    <div class="uploaded-files-area">
                        <div class="files-header">
                            <h4>Uploaded Files <span id="fileCount">(0)</span></h4>
                        </div>
                        <div class="uploaded-files-grid" id="uploadedFiles">
                            <!-- Files inserted here -->
                        </div>
                    </div>
                </div>

                <div class="form-footer-actions">
                    <button type="button" class="btn-action btn-outline" onclick="prevStep(1)">
                        <i class="fas fa-arrow-left"></i> Previous
                    </button>
                    <button type="button" class="btn-action btn-primary" onclick="nextStep(3)" id="nextToThumbnail" disabled>
                        Next Step <i class="fas fa-arrow-right"></i>
                    </button>
                </div>
            </div>

            <!-- Step 3: Thumbnail Selection -->
            <div class="wizard-step" id="step3">
                <div class="thumbnail-selection-area">
                    <div class="section-info">
                        <h3>Select Cover Thumbnail</h3>
                        <p>Choose the media asset that will represent this project.</p>
                    </div>

                    <div class="thumbnail-grid" id="thumbnailGrid">
                        <!-- Options inserted here -->
                    </div>
                    
                    <div class="empty-state" id="noThumbnailOption">
                        <i class="fas fa-images"></i>
                        <p>No media uploaded. Go back and add some files.</p>
                    </div>
                    
                    <input type="hidden" id="selectedThumbnailId" name="thumbnail_id" value="">
                </div>

                <div class="form-footer-actions">
                    <button type="button" class="btn-action btn-outline" onclick="prevStep(2)">
                        <i class="fas fa-arrow-left"></i> Previous
                    </button>
                    <button type="button" class="btn-action btn-primary" id="createProjectBtn" disabled onclick="submitProject()">
                        <i class="fas fa-check"></i> Create Project
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    /* Global Form Manager Styles (reused) */
    .manager-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        margin-bottom: 2.5rem;
    }
    .content-title { font-size: 1.75rem; font-weight: 800; color: #000; margin-bottom: 0.25rem; }
    .content-subtitle { color: #6b7280; font-size: 0.95rem; }
    .form-card-container { background: #fff; border-radius: 20px; border: 1px solid #e5e7eb; padding: 2.5rem; min-height: 600px; display: flex; flex-direction: column; }
    
    /* Wizard Progress */
    .wizard-progress {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 4rem;
        padding: 0 4rem;
    }
    
    .step-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 0.5rem;
        position: relative;
        z-index: 2;
        width: 100px;
    }
    
    .step-circle {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #fff;
        border: 2px solid #e5e7eb;
        color: #9ca3af;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        font-size: 0.9rem;
        transition: all 0.3s;
    }
    
    .step-text {
        font-size: 0.8rem;
        font-weight: 600;
        color: #9ca3af;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        transition: all 0.3s;
    }
    
    .step-item.active .step-circle {
        border-color: #000;
        background: #000;
        color: #fff;
    }
    
    .step-item.active .step-text {
        color: #000;
    }
    
    .step-line {
        flex: 1;
        height: 2px;
        background: #e5e7eb;
        margin-top: -24px;
        position: relative;
        z-index: 1;
    }

    /* Wizard Content Utils */
    .wizard-step { display: none; margin-top: 1rem; flex: 1; }
    .wizard-step.active { display: block; animation: fadeIn 0.4s ease-out; }
    
    @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

    /* Form Styles */
    .form-grid-split { display: grid; grid-template-columns: 1.5fr 1fr; gap: 3rem; }
    .form-row-modern { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
    .form-group-modern { margin-bottom: 1.5rem; }
    .form-group-modern label { display: block; font-size: 0.9rem; font-weight: 600; color: #111827; margin-bottom: 0.5rem; }
    .required-star { color: #ef4444; }
    .form-control-modern {
        width: 100%; padding: 0.75rem 1rem; background: #f9fafb; border: 1px solid #e5e7eb;
        border-radius: 10px; font-size: 0.95rem; color: #111827; transition: all 0.2s;
    }
    .form-control-modern:focus { outline: none; border-color: #000; background: #fff; box-shadow: 0 0 0 4px rgba(0,0,0,0.05); }

    .checkbox-wrapper {
        display: flex; align-items: center; gap: 0.75rem; padding: 1rem;
        background: #f9fafb; border-radius: 10px; border: 1px solid #e5e7eb; cursor: pointer;
    }
    .checkbox-wrapper input { width: 1.25rem; height: 1.25rem; cursor: pointer; }
    .checkbox-wrapper label { margin: 0; cursor: pointer; }

    /* Buttons */
    .form-footer-actions {
        margin-top: 4rem; padding-top: 2rem; border-top: 1px solid #f3f4f6;
        display: flex; justify-content: space-between; align-items: center;
    }
    .btn-action {
        padding: 0.875rem 1.75rem; border-radius: 12px; font-weight: 700; font-size: 0.95rem;
        border: 1px solid transparent; cursor: pointer; display: inline-flex; align-items: center; gap: 0.75rem; text-decoration: none; transition: all 0.2s;
    }
    .btn-primary { background: #000; color: #fff; }
    .btn-primary:hover { background: #333; transform: translateY(-2px); box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); }
    .btn-primary:disabled { background: #9ca3af; cursor: not-allowed; transform: none; box-shadow: none; }
    .btn-outline { background: transparent; border-color: #e5e7eb; color: #374151; }
    .btn-outline:hover { border-color: #000; color: #000; }
    .btn-sm { padding: 0.5rem 1rem; font-size: 0.85rem; }

    /* Upload Zone */
    .upload-zone {
        border: 2px dashed #e5e7eb; border-radius: 16px; padding: 4rem 2rem;
        text-align: center; background: #f9fafb; cursor: pointer; transition: all 0.2s;
        margin-bottom: 2rem;
    }
    .upload-zone:hover { border-color: #000; background: #f3f4f6; }
    .upload-content h4 { font-size: 1.2rem; font-weight: 700; margin: 1rem 0 0.5rem; }
    .upload-content p { color: #6b7280; font-size: 0.9rem; margin-bottom: 1.5rem; }
    .upload-icon { font-size: 4rem; color: #d1d5db; }
    .file-input-hidden { display: none; }

    /* Uploaded Files */
    .uploaded-files-grid {
        display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 1rem;
        margin-top: 1rem; max-height: 400px; overflow-y: auto;
    }
    .file-item {
        background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 0.75rem;
        position: relative; transition: all 0.2s;
    }
    .file-item:hover { border-color: #000; transform: translateY(-2px); }
    .file-preview {
        height: 120px; border-radius: 8px; overflow: hidden; background: #f3f4f6; margin-bottom: 0.5rem;
        display: flex; align-items: center; justify-content: center;
    }
    .file-preview img, .file-preview video { width: 100%; height: 100%; object-fit: cover; }
    .file-info span { font-size: 0.8rem; color: #4b5563; display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500;}
    .remove-file-btn {
        position: absolute; top: -8px; right: -8px; width: 24px; height: 24px;
        background: #ef4444; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center;
        cursor: pointer; font-size: 0.75rem; border: none; box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        opacity: 0; transition: all 0.2s;
    }
    .file-item:hover .remove-file-btn { opacity: 1; }

    /* Thumbnail Selection */
    .thumbnail-grid {
        display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 1.5rem; margin-top: 2rem;
    }
    .thumbnail-option {
        cursor: pointer; border: 3px solid transparent; border-radius: 12px; overflow: hidden;
        transition: all 0.2s; position: relative; opacity: 0.7;
    }
    .thumbnail-option:hover { opacity: 1; transform: scale(1.02); }
    .thumbnail-option.selected { border-color: #000; opacity: 1; box-shadow: 0 10px 20px -5px rgba(0,0,0,0.1); }
    .thumb-preview { height: 160px; background: #000; }
    .thumb-preview img, .thumb-preview video { width: 100%; height: 100%; object-fit: cover; }
    .selected-badge {
        position: absolute; top: 10px; right: 10px; background: #000; color: #fff;
        width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
        opacity: 0; transform: scale(0); transition: all 0.2s;
    }
    .thumbnail-option.selected .selected-badge { opacity: 1; transform: scale(1); }

    .section-info h3 { font-size: 1.25rem; font-weight: 700; margin-bottom: 0.25rem; }
    .section-info p { color: #6b7280; font-size: 0.9rem; }
    
    .empty-state {
        grid-column: 1 / -1; text-align: center; color: #9ca3af; padding: 4rem;
        border: 2px dashed #e5e7eb; border-radius: 12px;
    }
    .empty-state i { font-size: 3rem; margin-bottom: 1rem; }

    /* Responsive */
    @media (max-width: 900px) {
        .form-grid-split { grid-template-columns: 1fr; gap: 2rem; }
        .wizard-progress { padding: 0 1rem; }
    }
</style>

<script>
    let currentStep = 1;
    let uploadedFiles = [];
    let selectedThumbnailId = null;

    function nextStep(step) {
        // Validate Step 1
        if (currentStep === 1) {
             const title = document.getElementById('title').value;
             const client = document.getElementById('client_name').value;
             if(!title || !client) {
                 alert('Please fill in required fields');
                 return;
             }
        }
        
        document.getElementById('step' + currentStep).classList.remove('active');
        document.getElementById('indicator' + currentStep).classList.remove('active');
        
        document.getElementById('step' + step).classList.add('active');
        document.getElementById('indicator' + step).classList.add('active');
        currentStep = step;

        if (step === 3) renderThumbnailOptions();
        window.scrollTo(0, 0);
    }

    function prevStep(step) {
        document.getElementById('step' + currentStep).classList.remove('active');
        document.getElementById('indicator' + currentStep).classList.remove('active');
        
        document.getElementById('step' + step).classList.add('active');
        document.getElementById('indicator' + step).classList.add('active');
        currentStep = step;
        window.scrollTo(0, 0);
    }

    function validateStep1() {
        if(document.getElementById('basicInfoForm').checkValidity()) {
            nextStep(2);
        } else {
            document.getElementById('basicInfoForm').reportValidity();
        }
    }

    // File Upload Handling
    document.getElementById('uploadZone').addEventListener('click', () => {
        document.getElementById('fileInput').click();
    });

    document.getElementById('fileInput').addEventListener('change', handleFileSelect);

    // Simple Drag and Drop
    const dropZone = document.getElementById('uploadZone');
    dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.style.borderColor = '#000'; });
    dropZone.addEventListener('dragleave', (e) => { e.preventDefault(); dropZone.style.borderColor = '#e5e7eb'; });
    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.style.borderColor = '#e5e7eb';
        handleFiles(e.dataTransfer.files);
    });

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

    function handleFiles(files) {
        const fileList = Array.from(files);
        // Simulate upload (In real app, use FormData and fetch)
        // For this demo/redesign, we'll create object URLs
        
        fileList.forEach(file => {
             // Basic Validation
             if (file.size > 50 * 1024 * 1024) { alert('File too large'); return; }

             const id = Date.now() + Math.random().toString(36).substr(2, 9);
             const type = file.type.startsWith('video/') ? 'video' : 'image';
             const url = URL.createObjectURL(file);
             
             uploadedFiles.push({ id, file, type, url });
        });

        updateFileList();
        updateButtons();
    }

    function updateFileList() {
        const container = document.getElementById('uploadedFiles');
        document.getElementById('fileCount').textContent = `(${uploadedFiles.length})`;
        
        container.innerHTML = uploadedFiles.map(file => `
            <div class="file-item">
                <button type="button" class="remove-file-btn" onclick="removeFile('${file.id}')">&times;</button>
                <div class="file-preview">
                    ${file.type === 'video' 
                        ? `<video src="${file.url}" muted playsinline></video>` 
                        : `<img src="${file.url}" alt="">`}
                </div>
                <div class="file-info">
                    <span>${file.file.name}</span>
                </div>
            </div>
        `).join('');
    }

    function removeFile(id) {
        uploadedFiles = uploadedFiles.filter(f => f.id !== id);
        updateFileList();
        updateButtons();
    }

    function updateButtons() {
        const hasFiles = uploadedFiles.length > 0;
        document.getElementById('nextToThumbnail').disabled = !hasFiles;
    }

    function renderThumbnailOptions() {
        const container = document.getElementById('thumbnailGrid');
        
        if (uploadedFiles.length === 0) {
            document.getElementById('noThumbnailOption').style.display = 'block';
            container.innerHTML = '';
            return;
        }

        document.getElementById('noThumbnailOption').style.display = 'none';
        container.innerHTML = uploadedFiles.map(file => `
            <div class="thumbnail-option ${selectedThumbnailId === file.id ? 'selected' : ''}" onclick="selectThumbnail('${file.id}')">
                <div class="selected-badge"><i class="fas fa-check"></i></div>
                <div class="thumb-preview">
                    ${file.type === 'video' 
                        ? `<video src="${file.url}" muted playsinline></video>` 
                        : `<img src="${file.url}" alt="">`}
                </div>
            </div>
        `).join('');
        
        updateCreateButton();
    }

    window.selectThumbnail = function(id) {
        selectedThumbnailId = id;
        document.getElementById('selectedThumbnailId').value = id;
        renderThumbnailOptions(); // Re-render to show selection
    };

    function updateCreateButton() {
         document.getElementById('createProjectBtn').disabled = !selectedThumbnailId;
    }

    window.submitProject = function() {
        // Collect all data
        const formData = new FormData(document.getElementById('basicInfoForm'));
        
        // Add Files as array
        uploadedFiles.forEach((f) => {
            formData.append('media_files[]', f.file);
        });
        
        // Find and add Thumbnail Index
        const thumbIndex = uploadedFiles.findIndex(f => f.id === selectedThumbnailId);
        if (thumbIndex !== -1) {
             formData.append('thumbnail_index', thumbIndex);
        }

        const btn = document.getElementById('createProjectBtn');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating...';
        btn.disabled = true;

        // Submit to Backend
        fetch('<?php echo base_url("admin/add_wizard"); ?>', { 
            method: 'POST', 
            body: formData 
        })
        .then(response => response.text())
        .then(text => {
            try {
                const data = JSON.parse(text);
                if (data.success) {
                    btn.innerHTML = '<i class="fas fa-check"></i> Created';
                    setTimeout(() => {
                        window.location.href = '<?php echo base_url("admin/projects"); ?>';
                    }, 1000);
                } else {
                    alert('Error: ' + (data.error || 'Unknown error occurred'));
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }
            } catch (e) {
                console.error('Server response:', text);
                alert('Server Error (' + response.status + ' ' + response.statusText + '): ' + text.substring(0, 200) + '...'); 
                btn.innerHTML = originalText;
                btn.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Upload Failed: ' + error.message);
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
    }
    
    // Global exposure for inline onclicks
    window.removeFile = removeFile;
</script>

