<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('header', null, []); ?> 
        <style>
            .dash-header-title {
                font-weight: 600;
                font-size: 1.5rem;
                letter-spacing: -0.01em;
                color: #0f0f0f;
            }
        </style>
        <h2 class="dash-header-title">Tambah Produk</h2>
     <?php $__env->endSlot(); ?>

    <style>
        * { box-sizing: border-box; }

        .cprod-wrap { 
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 
        }

        .cprod-inner {
            max-width: 1200px;
            margin: 0 auto;
            padding: 32px 24px;
        }

        /* ── TOP BAR ── */
        .cprod-topbar {
            margin-bottom: 24px;
        }

        .cprod-eyebrow {
            font-size: 0.65rem;
            font-weight: 600;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            color: #999;
            margin-bottom: 4px;
        }

        .cprod-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #0f0f0f;
            letter-spacing: -0.01em;
        }

        /* ── ALERTS ── */
        .cprod-alert {
            border-radius: 8px;
            padding: 12px 16px;
            font-size: 0.8rem;
            margin-bottom: 20px;
            border-left: 3px solid;
        }

        .cprod-alert-success { background: #e8f5e9; border-color: #2e7d32; color: #2e7d32; }
        .cprod-alert-error   { background: #ffebee; border-color: #c62828; color: #c62828; }

        /* ── 2 COLUMN LAYOUT ── */
        .cprod-two-columns {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        /* ── SECTION CARD ── */
        .cprod-section {
            background: #fff;
            border: 1px solid #ebebeb;
            border-radius: 12px;
            padding: 20px 24px;
            margin-bottom: 20px;
        }

        .cprod-section-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 12px;
            margin-bottom: 20px;
        }

        .cprod-section-title {
            font-size: 1rem;
            font-weight: 600;
            color: #0f0f0f;
        }

        .cprod-section-sub {
            font-size: 0.7rem;
            color: #bbb;
            margin-top: 2px;
        }

        /* ── FORM FIELDS ── */
        .cprod-label {
            display: block;
            font-size: 0.65rem;
            font-weight: 600;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            color: #999;
            margin-bottom: 6px;
        }

        .cprod-label-req { color: #c62828; }

        .cprod-input,
        .cprod-select,
        .cprod-textarea {
            width: 100%;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            font-size: 0.85rem;
            color: #1a1a1a;
            background: #fff;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 10px 12px;
            transition: border-color 0.15s;
            outline: none;
        }

        .cprod-input:focus,
        .cprod-select:focus,
        .cprod-textarea:focus { border-color: #0f0f0f; }

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

        .form-grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        /* ── UPLOAD ZONE ── */
        .cprod-upload-zone {
            border: 2px dashed #e0e0e0;
            border-radius: 12px;
            padding: 24px;
            text-align: center;
            cursor: pointer;
            transition: border-color 0.15s, background 0.15s;
        }

        .cprod-upload-zone:hover { border-color: #0f0f0f; background: #fafafa; }
        .cprod-upload-zone.drag-over { border-color: #0f0f0f; background: #f0f0f0; }

        .cprod-upload-zone-icon { font-size: 1.6rem; color: #ccc; margin-bottom: 8px; }
        .cprod-upload-zone-text { font-size: 0.8rem; color: #999; }
        .cprod-upload-zone-hint { font-size: 0.68rem; color: #ccc; margin-top: 4px; }

        /* ── IMAGE PREVIEW GRID ── */
        .image-preview-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 8px;
            margin-top: 16px;
        }

        .image-preview-item {
            position: relative;
            border: 1px solid #ebebeb;
            border-radius: 8px;
            overflow: hidden;
            aspect-ratio: 1;
        }

        .image-preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .image-preview-cover-badge {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: #0f0f0f;
            color: #fff;
            font-size: 9px;
            text-align: center;
            padding: 3px 0;
            letter-spacing: 0.05em;
        }

        .image-delete-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: rgba(0,0,0,0.6);
            color: white;
            border: none;
            border-radius: 50%;
            width: 22px;
            height: 22px;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.15s;
        }

        .image-delete-btn:hover { background: rgba(198,40,40,0.9); }

        /* ── STOCK BADGE ── */
        .cprod-stock-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: #f5f5f5;
            border: 1px solid #e8e8e8;
            border-radius: 30px;
            padding: 6px 14px;
            font-size: 0.7rem;
            color: #999;
            letter-spacing: 0.05em;
            text-transform: uppercase;
        }

        .cprod-stock-num {
            font-size: 0.9rem;
            font-weight: 600;
            color: #0f0f0f;
        }

        /* ── ADD VARIANT BUTTON ── */
        .cprod-add-variant-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            background: none;
            border: 1px solid #e0e0e0;
            border-radius: 30px;
            padding: 7px 16px;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            font-size: 0.65rem;
            font-weight: 600;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            color: #666;
            cursor: pointer;
            transition: border-color 0.15s, color 0.15s;
        }

        .cprod-add-variant-btn:hover { border-color: #0f0f0f; color: #0f0f0f; }

        /* ── VARIANT TABLE ── */
        .variant-table {
            width: 100%;
            border-collapse: collapse;
        }

        .variant-table th {
            text-align: left;
            padding: 10px 8px;
            font-size: 0.6rem;
            font-weight: 600;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            color: #999;
            background: #fafafa;
            border-bottom: 1px solid #f0f0f0;
        }

        .variant-table td {
            padding: 10px 8px;
            border-bottom: 1px solid #f5f5f5;
            vertical-align: middle;
        }

        .variant-table tr:last-child td { border-bottom: none; }

        .variant-img-preview {
            width: 48px;
            height: 48px;
            border-radius: 8px;
            background: #f5f5f5;
            border: 1px solid #ebebeb;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .variant-img-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .variant-input-sm {
            width: 100%;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            font-size: 0.8rem;
            padding: 8px 8px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            outline: none;
        }

        .variant-input-sm:focus { border-color: #0f0f0f; }

        .variant-select-sm {
            width: 100%;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            font-size: 0.8rem;
            padding: 8px 8px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            background: #fff;
            outline: none;
        }

        .variant-color-input {
            width: 40px;
            height: 36px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            cursor: pointer;
            padding: 2px;
        }

        .variant-delete-btn {
            background: none;
            border: none;
            cursor: pointer;
            color: #ccc;
            transition: color 0.15s;
            padding: 4px;
        }

        .variant-delete-btn:hover { color: #c62828; }

        /* ── FORM ACTIONS ── */
        .cprod-actions {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 12px;
            margin-top: 24px;
        }

        .cprod-btn-cancel {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            font-size: 0.7rem;
            font-weight: 600;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            color: #999;
            text-decoration: none;
            padding: 10px 20px;
            border: 1px solid #e0e0e0;
            border-radius: 30px;
            transition: border-color 0.15s, color 0.15s;
        }

        .cprod-btn-cancel:hover { border-color: #0f0f0f; color: #0f0f0f; }

        .cprod-btn-submit {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            font-size: 0.7rem;
            font-weight: 600;
            letter-spacing: 0.05em;
            text-transform: uppercase;
            color: #fff;
            background: #0f0f0f;
            padding: 10px 28px;
            border: none;
            border-radius: 30px;
            cursor: pointer;
            transition: background 0.15s;
        }

        .cprod-btn-submit:hover { background: #333; }

        /* ── PICKER POPUP ── */
        .variant-picker {
            position: absolute;
            background: #fff;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            z-index: 100;
            min-width: 200px;
        }

        .picker-thumb {
            width: 50px;
            height: 50px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            cursor: pointer;
            overflow: hidden;
            position: relative;
        }

        .picker-thumb.selected { border-color: #0f0f0f; box-shadow: 0 0 0 2px rgba(0,0,0,0.1); }
        .picker-thumb img { width: 100%; height: 100%; object-fit: cover; }

        .hidden { display: none; }
        .relative { position: relative; }
        .mt-2 { margin-top: 8px; }
        .text-center { text-align: center; }
        
        .image-count-badge {
            margin-top: 10px;
            font-size: 0.75rem;
            color: #666;
            text-align: center;
        }
    </style>

    <div class="cprod-wrap">
        <div class="cprod-inner">

            
            <div class="cprod-topbar">
                <div class="cprod-title">Tambah Produk Baru</div>
            </div>

            
            <?php if(session('success')): ?>
                <div class="cprod-alert cprod-alert-success"><?php echo e(session('success')); ?></div>
            <?php endif; ?>
            <?php if($errors->any()): ?>
                <div class="cprod-alert cprod-alert-error">
                    <strong style="display:block;margin-bottom:6px;">Terdapat kesalahan:</strong>
                    <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div>· <?php echo e($error); ?></div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
            <?php endif; ?>

            <form action="<?php echo e(route('admin.products.store')); ?>" method="POST" enctype="multipart/form-data" id="product-form">
                <?php echo csrf_field(); ?>

                
                <div class="cprod-two-columns">
                    
                    <div class="cprod-section">
                        <div class="cprod-section-header">
                            <div class="cprod-section-title">Informasi Dasar</div>
                        </div>

                        <div class="form-grid-2">
                            <div class="grid-full" style="grid-column: span 2;">
                                <label class="cprod-label">Nama Produk <span class="cprod-label-req">*</span></label>
                                <input type="text" name="name" id="product-name" value="<?php echo e(old('name')); ?>" class="cprod-input" required>
                            </div>

                            <div>
                                <label class="cprod-label">Kategori <span class="cprod-label-req">*</span></label>
                                <select name="category_id" class="cprod-select" required>
                                    <option value="">Pilih Kategori</option>
                                    <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($category->id); ?>" <?php echo e(old('category_id') == $category->id ? 'selected' : ''); ?>>
                                            <?php echo e($category->name); ?>

                                        </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>

                            <div>
                                <label class="cprod-label">Brand</label>
                                <select name="brand_id" class="cprod-select">
                                    <option value="">Pilih Brand (Opsional)</option>
                                    <?php $__currentLoopData = $brands; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $brand): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($brand->id); ?>" <?php echo e(old('brand_id') == $brand->id ? 'selected' : ''); ?>>
                                            <?php echo e($brand->name); ?>

                                        </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>

                            <div>
                                <label class="cprod-label">Berat (gram)</label>
                                <input type="number" name="weight" value="<?php echo e(old('weight', 1000)); ?>" min="1" class="cprod-input">
                            </div>

                            <div style="grid-column: span 2;">
                                <label class="cprod-label">Deskripsi</label>
                                <textarea name="description" rows="3" class="cprod-textarea"
                                    placeholder="Tuliskan deskripsi produk..."><?php echo e(old('description')); ?></textarea>
                            </div>
                        </div>
                    </div>

                    
                    <div class="cprod-section">
                        <div class="cprod-section-header">
                            <div class="cprod-section-title">Foto Produk</div>
                            <div class="cprod-section-sub">Foto pertama = cover | Bisa pilih banyak gambar sekaligus</div>
                        </div>

                        <div class="cprod-upload-zone" id="uploadZone">
                            <div class="cprod-upload-zone-icon">📷</div>
                            <div class="cprod-upload-zone-text">Klik atau drag & drop untuk upload foto</div>
                            <div class="cprod-upload-zone-hint">JPG, PNG, WEBP · Maks 5MB per file · Bisa pilih banyak gambar sekaligus (Ctrl+Click atau Shift+Click)</div>
                            <input type="file" name="images[]" id="images" class="hidden" accept="image/*" multiple>
                        </div>

                        <div id="image-preview-container" class="image-preview-grid"></div>
                        <div id="image-count" class="image-count-badge"></div>
                    </div>
                </div>

                
                <div class="cprod-section">
                    <div class="cprod-section-header">
                        <div>
                            <div class="cprod-section-title">Varian Produk</div>
                            <div class="cprod-section-sub">Setiap varian dapat memiliki foto berbeda</div>
                        </div>
                        <div style="display:flex;align-items:center;gap:10px;">
                            <div class="cprod-stock-badge">
                                Total Stok &nbsp;<span id="total-stock-display" class="cprod-stock-num">0</span>
                            </div>
                            <button type="button" class="cprod-add-variant-btn" onclick="addVariant()">
                                + Tambah Varian
                            </button>
                        </div>
                    </div>

                    <input type="hidden" name="stock" id="total-stock-input" value="0">
                    
                    <div style="overflow-x: auto;">
                        <table class="variant-table" id="variant-table">
                            <thead>
                                <tr>
                                    <th style="width:60px">Foto</th>
                                    <th>Ukuran</th>
                                    <th>Warna</th>
                                    <th style="width:50px">Kode</th>
                                    <th>Harga (Rp)</th>
                                    <th>Stok</th>
                                    <th>SKU</th>
                                    <th>Aksi</th>
                                    <th style="width:40px"></th>
                                </tr>
                            </thead>
                            <tbody id="variant-container"></tbody>
                        </table>
                    </div>
                </div>

                
                <div class="cprod-actions">
                    <a href="<?php echo e(route('admin.products.index')); ?>" class="cprod-btn-submit">Batal</a>
                    <button type="submit" class="cprod-btn-submit">Simpan Produk</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Store all image files
        let imageFiles = [];
        let uploadedImages = [];

        // Color name to hex converter
        function colorNameToHex(colorName) {
            const colorMap = {
                'merah': '#FF0000',
                'merah tua': '#8B0000',
                'kuning': '#FFFF00',
                'hijau': '#00FF00',
                'hijau tua': '#006400',
                'biru': '#0000FF',
                'biru muda': '#87CEEB',
                'biru tua': '#00008B',
                'hitam': '#000000',
                'putih': '#FFFFFF',
                'abu': '#808080',
                'abu-abu': '#808080',
                'coklat': '#8B4513',
                'orange': '#FFA500',
                'ungu': '#800080',
                'pink': '#FFC0CB',
                'toska': '#00FFFF',
                'navy': '#000080',
                'maroon': '#800000',
                'salem': '#097969',
                'krem': '#FFFDD0',
                'perak': '#C0C0C0',
                'emas': '#FFD700'
            };
            return colorMap[colorName.toLowerCase()] || '#000000';
        }

        // Auto generate SKU
        function generateSKU(variantIdx) {
            const productName = document.getElementById('product-name')?.value || 'PROD';
            const size = document.querySelector(`select[name="variants[${variantIdx}][size]"]`)?.value || '';
            const color = document.querySelector(`input[name="variants[${variantIdx}][color]"]`)?.value || '';
            
            let sku = productName.substring(0, 3).toUpperCase();
            if (size) sku += `-${size}`;
            if (color) sku += `-${color.substring(0, 3).toUpperCase()}`;
            sku += `-${Math.floor(Math.random() * 1000)}`;
            
            return sku;
        }

        function previewImages(files) {
            const container = document.getElementById('image-preview-container');
            if (!files || !files.length) return;

            const validFiles = [];
            const invalidFiles = [];

            // Filter valid image files
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (file.type.startsWith('image/')) {
                    if (file.size <= 5 * 1024 * 1024) { // 5MB limit
                        validFiles.push(file);
                    } else {
                        invalidFiles.push(`${file.name} (terlalu besar, maks 5MB)`);
                    }
                } else {
                    invalidFiles.push(`${file.name} (bukan file gambar)`);
                }
            }

            if (invalidFiles.length > 0) {
                alert(`File berikut tidak bisa diupload:\n${invalidFiles.join('\n')}`);
            }

            if (validFiles.length === 0) return;

            // Add new files to existing files
            validFiles.forEach(file => {
                imageFiles.push(file);
            });

            // Clear existing previews
            container.innerHTML = '';
            uploadedImages = [];

            const results = new Array(imageFiles.length);
            let loaded = 0;

            imageFiles.forEach((file, i) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    results[i] = e.target.result;
                    loaded++;
                    if (loaded === imageFiles.length) {
                        results.forEach((dataUrl, idx) => {
                            uploadedImages[idx] = { 
                                index: idx, 
                                dataUrl, 
                                name: imageFiles[idx].name,
                                file: imageFiles[idx]
                            };
                            
                            // Create preview element
                            const previewDiv = document.createElement('div');
                            previewDiv.className = 'image-preview-item';
                            previewDiv.innerHTML = `
                                <img src="${dataUrl}" alt="Preview ${idx + 1}">
                                ${idx === 0 ? '<div class="image-preview-cover-badge">COVER</div>' : ''}
                                <button type="button" class="image-delete-btn" onclick="removeImage(${idx})">✕</button>
                            `;
                            container.appendChild(previewDiv);
                        });
                        
                        // Update image count
                        document.getElementById('image-count').innerHTML = `${imageFiles.length} file gambar`;
                        
                        refreshAllVariantPickers();
                        
                        // Update the file input with all images
                        updateFileInput(imageFiles);
                    }
                };
                reader.readAsDataURL(file);
            });
        }
        
        function removeImage(imageIndex) {
            if (confirm('Hapus foto ini?')) {
                imageFiles.splice(imageIndex, 1);
                
                // Refresh preview grid
                refreshImagePreviews();
                
                // Update file input
                updateFileInput(imageFiles);
                
                refreshAllVariantPickers();
            }
        }
        
        function refreshImagePreviews() {
            const container = document.getElementById('image-preview-container');
            container.innerHTML = '';
            uploadedImages = [];
            
            if (imageFiles.length === 0) {
                document.getElementById('image-count').innerHTML = 'Belum ada gambar';
                return;
            }
            
            const results = new Array(imageFiles.length);
            let loaded = 0;
            
            imageFiles.forEach((file, i) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    results[i] = e.target.result;
                    loaded++;
                    if (loaded === imageFiles.length) {
                        results.forEach((dataUrl, idx) => {
                            uploadedImages[idx] = { 
                                index: idx, 
                                dataUrl, 
                                name: imageFiles[idx].name,
                                file: imageFiles[idx]
                            };
                            
                            const previewDiv = document.createElement('div');
                            previewDiv.className = 'image-preview-item';
                            previewDiv.innerHTML = `
                                <img src="${dataUrl}" alt="Preview ${idx + 1}">
                                ${idx === 0 ? '<div class="image-preview-cover-badge">COVER</div>' : ''}
                                <button type="button" class="image-delete-btn" onclick="removeImage(${idx})">✕</button>
                            `;
                            container.appendChild(previewDiv);
                        });
                        
                        document.getElementById('image-count').innerHTML = `${imageFiles.length} file gambar`;
                    }
                };
                reader.readAsDataURL(file);
            });
        }
        
        function updateFileInput(files) {
            // Create a new FileList-like object using DataTransfer
            const dataTransfer = new DataTransfer();
            files.forEach(file => {
                dataTransfer.items.add(file);
            });
            const fileInput = document.getElementById('images');
            fileInput.files = dataTransfer.files;
        }

        function buildPickerContent(variantIdx) {
            let html = `<div style="display:flex;flex-wrap:wrap;gap:8px;">`;
            
            html += `<div class="picker-thumb" data-imgindex="" title="Tanpa foto" style="display:flex;align-items:center;justify-content:center;">
                        <svg width="20" height="20" fill="none" stroke="#ccc" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </div>`;

            uploadedImages.forEach(img => {
                html += `
                    <div class="picker-thumb" data-imgindex="${img.index}" title="Foto ${img.index + 1}">
                        <img src="${img.dataUrl}" alt="">
                    </div>`;
            });

            html += `</div>`;
            if (uploadedImages.length === 0) {
                html += `<p style="font-size:0.7rem;color:#ccc;margin-top:8px;">Upload foto produk terlebih dahulu.</p>`;
            }
            return html;
        }

        function refreshAllVariantPickers() {
            document.querySelectorAll('.variant-picker-content').forEach(pickerEl => {
                const variantIdx = pickerEl.dataset.variantidx;
                pickerEl.innerHTML = buildPickerContent(variantIdx);
                bindPickerEvents(pickerEl, variantIdx);
            });
        }

        function bindPickerEvents(pickerEl, variantIdx) {
            pickerEl.querySelectorAll('.picker-thumb').forEach(thumb => {
                thumb.addEventListener('click', function(e) {
                    e.stopPropagation();
                    const imgIndex = this.dataset.imgindex;
                    const previewWrap = document.getElementById(`variant-img-${variantIdx}`);
                    const hiddenInput = document.getElementById(`hidden-img-index-${variantIdx}`);

                    hiddenInput.value = imgIndex;

                    if (imgIndex !== '' && uploadedImages[parseInt(imgIndex)]) {
                        previewWrap.innerHTML = `<img src="${uploadedImages[parseInt(imgIndex)].dataUrl}" style="width:100%;height:100%;object-fit:cover;">`;
                    } else {
                        previewWrap.innerHTML = `<svg width="20" height="20" fill="none" stroke="#ccc" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                                d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                        </svg>`;
                    }

                    document.getElementById(`picker-popup-${variantIdx}`).classList.add('hidden');
                });
            });
        }

        function togglePicker(variantIdx) {
            const popup = document.getElementById(`picker-popup-${variantIdx}`);
            document.querySelectorAll('.variant-picker-popup').forEach(p => {
                if (p.id !== `picker-popup-${variantIdx}`) p.classList.add('hidden');
            });
            popup.classList.toggle('hidden');
        }

        // Update color code when color name changes
        function updateColorCode(variantIdx) {
            const colorNameInput = document.querySelector(`input[name="variants[${variantIdx}][color]"]`);
            const colorCodeInput = document.querySelector(`input[name="variants[${variantIdx}][color_code]"]`);
            
            if (colorNameInput && colorCodeInput) {
                const hexColor = colorNameToHex(colorNameInput.value);
                colorCodeInput.value = hexColor;
            }
        }

        // Auto fill SKU
        function autoFillSKU(variantIdx) {
            const skuInput = document.querySelector(`input[name="variants[${variantIdx}][sku_variant]"]`);
            if (skuInput && !skuInput.value) {
                skuInput.value = generateSKU(variantIdx);
            }
        }

        let variantIndex = 0;

        function addVariant() {
            const idx = variantIndex;
            const html = `
                <tr id="variant-row-${idx}">
                    <td>
                        <div class="relative">
                            <div id="variant-img-${idx}" class="variant-img-preview" onclick="togglePicker(${idx})">
                                <svg width="20" height="20" fill="none" stroke="#ccc" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                                        d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                                </svg>
                            </div>
                            <div id="picker-popup-${idx}" class="variant-picker hidden variant-picker-popup">
                                <div class="variant-picker-content" data-variantidx="${idx}"></div>
                            </div>
                            <input type="hidden" name="variants[${idx}][image_index]" id="hidden-img-index-${idx}" value="">
                        </div>
                    </td>
                    <td>
                        <select name="variants[${idx}][size]" class="variant-select-sm" required onchange="autoFillSKU(${idx})">
                            <option value="">Pilih</option>
                            <option value="S">S</option>
                            <option value="M">M</option>
                            <option value="L">L</option>
                            <option value="XL">XL</option>
                            <option value="XXL">XXL</option>
                        </select>
                    </td>
                    <td>
                        <input type="text" name="variants[${idx}][color]" placeholder="Nama warna" class="variant-input-sm" required 
                               oninput="updateColorCode(${idx}); autoFillSKU(${idx})">
                    </td>
                    <td>
                        <input type="color" name="variants[${idx}][color_code]" value="#000000" class="variant-color-input">
                    </td>
                    <td>
                        <input type="number" name="variants[${idx}][price]" placeholder="0" min="0" class="variant-input-sm" required>
                    </td>
                    <td>
                        <input type="number" name="variants[${idx}][stock]" placeholder="0" min="0" oninput="recalcStock()" class="variant-input-sm" required>
                    </td>
                    <td>
                        <input type="text" name="variants[${idx}][sku_variant]" placeholder="SKU (akan auto terisi)" class="variant-input-sm" 
                               onfocus="autoFillSKU(${idx})">
                    </td>
                    <td>
                        <button type="button" class="variant-delete-btn" onclick="removeVariant(${idx})">
                            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                            </svg>
                        </button>
                    </td>
                </tr>
            `;

            document.getElementById('variant-container').insertAdjacentHTML('beforeend', html);

            const pickerContent = document.querySelector(`#picker-popup-${idx} .variant-picker-content`);
            if (pickerContent) {
                pickerContent.innerHTML = buildPickerContent(idx);
                bindPickerEvents(pickerContent, idx);
            }

            variantIndex++;
        }

        function removeVariant(idx) {
            document.getElementById(`variant-row-${idx}`).remove();
            recalcStock();
        }

        function recalcStock() {
            let total = 0;
            document.querySelectorAll('#variant-container input[name*="[stock]"]').forEach(inp => {
                total += parseInt(inp.value) || 0;
            });
            document.getElementById('total-stock-display').textContent = total.toLocaleString('id-ID');
            document.getElementById('total-stock-input').value = total;
        }

        // Setup drag and drop
        function setupDragAndDrop() {
            const uploadZone = document.getElementById('uploadZone');
            const fileInput = document.getElementById('images');

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

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            ['dragenter', 'dragover'].forEach(eventName => {
                uploadZone.addEventListener(eventName, highlight, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                uploadZone.addEventListener(eventName, unhighlight, false);
            });

            function highlight(e) {
                uploadZone.classList.add('drag-over');
            }

            function unhighlight(e) {
                uploadZone.classList.remove('drag-over');
            }

            uploadZone.addEventListener('drop', handleDrop, false);
            uploadZone.addEventListener('click', function() {
                fileInput.click();
            });

            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                previewImages(files);
            }

            fileInput.addEventListener('change', function(e) {
                if (this.files && this.files.length) {
                    previewImages(this.files);
                }
            });
        }

        // Before submit, ensure all image files are properly attached
        document.getElementById('product-form').addEventListener('submit', function(e) {
            // Update file input with latest image files
            updateFileInput(imageFiles);
        });

        document.addEventListener('DOMContentLoaded', function () {
            addVariant();
            setupDragAndDrop();
            document.getElementById('image-count').innerHTML = 'Belum ada gambar';
            
            // Auto generate SKU for first variant
            setTimeout(() => {
                if (document.querySelector('#variant-container tr')) {
                    autoFillSKU(0);
                }
            }, 100);
        });

        // Close picker when clicking outside
        document.addEventListener('click', function(e) {
            if (!e.target.closest('.variant-picker-popup') && !e.target.closest('.variant-img-preview')) {
                document.querySelectorAll('.variant-picker-popup').forEach(p => p.classList.add('hidden'));
            }
        });
    </script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?><?php /**PATH C:\laragon\www\ecommerce_app\resources\views/admin/products/create.blade.php ENDPATH**/ ?>