<div>
    
    <div class="fixed top-0 left-0 right-0 w-full bg-white flex items-center justify-between p-4 z-50 border-b border-gray-200">
        <div class="flex items-center">
            <div class="w-10 h-10 bg-red-500 rounded flex items-center justify-center mr-3">
                <span class="text-white font-bold text-sm">3I.</span>
            </div>
            <h1 class="text-2xl font-bold">Agregar archivos SCSS</h1>
        </div>
        <div class="flex items-center gap-3">
            <a href="<?php echo e(route('products.scss.version.show', [$product, $scssVersion])); ?>"
                class="text-gray-700 hover:text-gray-900 px-4 py-2">
                Cancelar
            </a>
            <button type="button"
                    wire:click="syncAndSave"
                    wire:loading.attr="disabled"
                    class="bg-3ip hover:bg-3ip-light text-white px-4 py-2 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed">
                <span wire:loading.remove>Guardar archivos</span>
                <span wire:loading>Guardando...</span>
            </button>
        </div>
    </div>

    
    <div class="w-full px-20 pt-24 pb-8">
        <div class="mx-auto max-w-4xl">
            <div class="w-full rounded-lg bg-white border border-gray-200 px-8 py-6">

                
                <div class="mb-6 pb-6 border-b border-gray-200">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs text-gray-500 mb-1">Producto</label>
                            <p class="font-semibold text-gray-900"><?php echo e($product->name); ?></p>
                            <p class="text-xs text-gray-600 font-mono"><?php echo e($product->slug); ?></p>
                        </div>
                        <div>
                            <label class="block text-xs text-gray-500 mb-1">Versión</label>
                            <p class="font-mono font-semibold text-gray-900"><?php echo e($scssVersion->version); ?></p>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($scssVersion->description): ?>
                                <p class="text-sm text-gray-600 mt-1"><?php echo e($scssVersion->description); ?></p>
                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                        </div>
                    </div>
                </div>

                <form id="scss-create-form" class="space-y-6">
                    
                    <div>
                        <div class="flex items-center justify-between mb-4">
                            <label class="block text-lg font-semibold text-gray-900">Archivos SCSS</label>
                            <button type="button"
                                    wire:click="addFile"
                                    class="flex items-center text-sm px-3 py-1.5 bg-green-600 text-white rounded-lg hover:bg-green-700">
                                <img src="<?php echo e(asset('vendor/blade-untitledui-icons/plus.svg')); ?>" alt="Añadir" class="w-4 h-4 mr-1 svg-fill-white">
                                Añadir otro archivo
                            </button>
                        </div>

                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__currentLoopData = $files; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $file): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="mb-6 p-4 border border-gray-200 rounded-lg bg-gray-50" wire:key="file-<?php echo e($index); ?>">
                                <div class="flex items-center justify-between mb-4">
                                    <h3 class="font-semibold text-gray-900">Archivo #<?php echo e($index + 1); ?></h3>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(count($files) > 1): ?>
                                        <button type="button"
                                                wire:click="removeFile(<?php echo e($index); ?>)"
                                                class="flex items-center text-sm px-3 py-1.5 bg-red-600 text-white rounded-lg hover:bg-red-700">
                                            <img src="<?php echo e(asset('vendor/blade-untitledui-icons/trash.svg')); ?>" alt="Eliminar" class="w-4 h-4 mr-1 svg-fill-white">
                                            Eliminar
                                        </button>
                                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                </div>

                                
                                <div class="mb-4">
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Nombre del archivo (sin extensión) *</label>
                                    <input type="text"
                                           wire:model="files.<?php echo e($index); ?>.filename"
                                           placeholder="variables, mixins, etc."
                                           class="w-full rounded-lg border border-gray-200 px-4 py-2 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-orange-300 <?php $__errorArgs = ['files.' . $index . '.filename'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>">
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['files.' . $index . '.filename'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <p class="text-red-600 text-sm mt-1"><?php echo e($message); ?></p>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                </div>

                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Contenido SCSS/SASS *</label>
                                    <div wire:ignore>
                                        <textarea id="scss-editor-<?php echo e($index); ?>"
                                                  wire:model.live="fileContents.<?php echo e($index); ?>"
                                                  class="w-full rounded-lg border border-gray-200 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-orange-300 <?php $__errorArgs = ['files.' . $index . '.content'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> border-red-500 <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>"
                                                  rows="15"></textarea>
                                    </div>
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['files.' . $index . '.content'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <p class="text-red-600 text-sm mt-1"><?php echo e($message); ?></p>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['files'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="text-red-600 text-sm mt-1"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        let scssEditors = {};

        function initializeScssEditor(index) {
            const textareaId = `scss-editor-${index}`;
            const textarea = document.getElementById(textareaId);

            if (!textarea) {
                return;
            }

            // Si ya existe un editor, destruirlo primero
            if (scssEditors[index]) {
                try {
                    scssEditors[index].destroy();
                } catch (e) {
                    console.warn('Error al destruir editor anterior:', e);
                }
            }

            // Inicializar nuevo editor
            scssEditors[index] = CodeMirror.fromTextArea(textarea, {
                theme: 'oneDark',
            });

            // Sincronizar con Livewire (con debounce)
            let updateTimeout;
            scssEditors[index].on('change', function(cm) {
                if (updateTimeout) {
                    clearTimeout(updateTimeout);
                }
                updateTimeout = setTimeout(function() {
                    window.Livewire.find('<?php echo e($_instance->getId()); ?>').set('fileContents.' + index, cm.getValue(), false);
                    // También actualizar files directamente para asegurar sincronización
                    window.Livewire.find('<?php echo e($_instance->getId()); ?>').set('files.' + index + '.content', cm.getValue(), false);
                }, 300);
            });
            
            // Sincronizar valor inicial
            const initialValue = window.Livewire.find('<?php echo e($_instance->getId()); ?>').get('fileContents.' + index) || '';
            if (initialValue) {
                scssEditors[index].setValue(initialValue);
            }
        }

        function destroyScssEditor(index) {
            if (scssEditors[index]) {
                try {
                    scssEditors[index].destroy();
                } catch (e) {
                    console.warn('Error al destruir editor:', e);
                }
                delete scssEditors[index];
            }
        }

        // Inicializar editores cuando el DOM esté listo
        document.addEventListener('DOMContentLoaded', function() {
            <?php $__currentLoopData = $files; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $file): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                initializeScssEditor(<?php echo e($index); ?>);
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        });

        // Escuchar cambios de Livewire
        document.addEventListener('livewire:init', function() {
            // Escuchar cuando se actualiza el componente
            Livewire.hook('morph.updated', ({ el, component }) => {
                // Verificar si hay nuevos editores que inicializar
                <?php $__currentLoopData = $files; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $file): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    const textarea<?php echo e($index); ?> = document.getElementById('scss-editor-<?php echo e($index); ?>');
                    if (textarea<?php echo e($index); ?> && !scssEditors[<?php echo e($index); ?>]) {
                        setTimeout(() => initializeScssEditor(<?php echo e($index); ?>), 150);
                    }
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            });

            // Escuchar cuando se agrega un archivo
            Livewire.on('fileAdded', (index) => {
                setTimeout(() => {
                    initializeScssEditor(index);
                    // Asegurar que el contenido inicial esté sincronizado
                    const textarea = document.getElementById(`scss-editor-${index}`);
                    if (textarea && scssEditors[index]) {
                        const content = window.Livewire.find('<?php echo e($_instance->getId()); ?>').get('fileContents.' + index) || '';
                        if (content) {
                            scssEditors[index].setValue(content);
                        }
                    }
                }, 200);
            });

            // Escuchar cuando se elimina un archivo
            Livewire.on('fileRemoved', (index) => {
                destroyScssEditor(index);
            });

            // Sincronizar CodeMirror antes de guardar
            Livewire.on('syncCodeMirror', () => {
                // Sincronizar todos los editores con Livewire
                Object.keys(scssEditors).forEach(index => {
                    if (scssEditors[index]) {
                        const content = scssEditors[index].getValue();
                        window.Livewire.find('<?php echo e($_instance->getId()); ?>').set('fileContents.' + index, content, false);
                        window.Livewire.find('<?php echo e($_instance->getId()); ?>').set('files.' + index + '.content', content, false);
                    }
                });
            });

            // Guardar después de sincronizar
            Livewire.on('saveAfterSync', () => {
                setTimeout(() => {
                    window.Livewire.find('<?php echo e($_instance->getId()); ?>').call('save');
                }, 100);
            });
        });
    </script>
</div><?php /**PATH /var/www/html/resources/views/livewire/scss/create.blade.php ENDPATH**/ ?>