<div>
    <form>
        <div style="display: flex; justify-content: end; align-items: center; gap: 10px; margin-bottom: 10px;">
            Düzenlenen diller:
            @foreach ($languages as $language)
                <a href="#" wire:click.prevent="changeLanguage('{{ $language->short }}')"
                    wire:key="lang-{{ $language->id }}"
                    class="btn btn-sm {{ $selectedLanguage == $language->short ? 'btn-primary' : 'btn-outline-primary' }}">
                    {{ strtoupper($language->short) }}
                </a>
            @endforeach
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="name">Başlık *</label>
            <div class="col-sm-10">
                <input class="form-control" id="name" type="text" wire:model.live="name" required autocomplete="off">
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="isSingleSelect">Seçim Türü *</label>
            <div class="col-sm-10">
                <select class="form-control" name="isSingleSelect" wire:model.live="isSingleSelect" required>
                    <option value="">Seçiniz...</option>
                    <option value="1">Tek seçilebilir</option>
                    <option value="2">Çoklu seçilebilir</option>
                </select>
                @error('isSingleSelect')
                        <span class="error">{{ $message }}</span>
                @enderror
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="content">İçerik</label>
            <div class="col-sm-10">
                <div wire:ignore>
                    <textarea wire:model="content" class="form-control" name="content" id="content"></textarea>
                </div>
                <div>
                    @error('content')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="mb-3">
            <x-file-manager id="fm1" name="image" title="Görsel" :path="$image_path" />
        </div>

        <button class="btn btn-primary" type="submit" wire:click.prevent="saveAndRedirect" wire:loading.attr="disabled" wire:target="save, saveAndRedirect">Kaydet</button>
        <button class="btn btn-primary" type="submit" wire:click.prevent="save" wire:loading.attr="disabled" wire:target="save, saveAndRedirect">Kaydet ve Eklemeye Devam Et</button>
    </form>
</div>

@push('js')
    <script>
        function ensureVisible(element) {
            var container = element.closest('.list-group');

            if (container) {
                var containerTop = container.offsetTop - 100;
                var containerHeight = container.clientHeight;
                var elementTop = element.offsetTop;
                var elementHeight = element.clientHeight;
                var scrollTop = container.scrollTop;

                if (elementTop < containerTop) {
                    container.scrollTop = elementTop - containerTop;
                } else if (elementTop + elementHeight > containerTop + containerHeight) {
                    container.scrollTop = (elementTop + elementHeight) - (containerTop + containerHeight);
                }
            }
        }
    </script>

    <script>
        class MyUploadAdapter {
            constructor(loader) {
                this.loader = loader;
            }

            upload() {
                return this.loader.file
                    .then(file => new Promise((resolve, reject) => {
                        this._initRequest();
                        this._initListeners(resolve, reject, file);
                        this._sendRequest(file);
                    }));
            }

            abort() {
                if (this.xhr) {
                    this.xhr.abort();
                }
            }

            _initRequest() {
                const xhr = this.xhr = new XMLHttpRequest();
                xhr.open('POST', '{{ route('admin.pages.ckeditor-upload') }}', true);
                xhr.setRequestHeader('X-CSRF-TOKEN', '{{ csrf_token() }}');
                xhr.responseType = 'json';
            }

            _initListeners(resolve, reject, file) {
                const xhr = this.xhr;
                const loader = this.loader;
                const genericErrorText = `Couldn't upload file: ${file.name}.`;

                xhr.addEventListener('error', () => reject(genericErrorText));
                xhr.addEventListener('abort', () => reject());
                xhr.addEventListener('load', () => {
                    const response = xhr.response;

                    if (!response || response.error) {
                        return reject(response && response.error ? response.error.message : genericErrorText);
                    }

                    resolve({
                        default: response.url
                    });
                });

                if (xhr.upload) {
                    xhr.upload.addEventListener('progress', evt => {
                        if (evt.lengthComputable) {
                            loader.uploadTotal = evt.total;
                            loader.uploaded = evt.loaded;
                        }
                    });
                }
            }

            _sendRequest(file) {
                const data = new FormData();
                data.append('upload', file);
                this.xhr.send(data);
            }
        }

        function MyCustomUploadAdapterPlugin(editor) {
            editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
                return new MyUploadAdapter(loader);
            };
        }
    </script>

    <script>
        function initCKEditor() {
            ClassicEditor
                .create(document.querySelector('#content'), {
                    removePlugins: ['Title'],
                    extraPlugins: [MyCustomUploadAdapterPlugin],
                    height: 400,
                })
                .then(editor => {
                    editor.editing.view.change(writer => {
                        writer.setStyle('height', '400px', editor.editing.view.document.getRoot());
                    });

                    editor.model.document.on('change:data', () => {
                        @this.set('content', editor.getData());
                    });

                    Livewire.on('languageChanged', function(event) {
                        editor.setData(event.content);
                    });
                })
                .catch(error => {
                    console.error(error);
                });
        }
    </script>

@endpush
