<div>
    <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>

    <form>

        <div class="position-relative mb-3">
            <input
                type="text"
                class="form-control"
                placeholder="Üst sayfa seçmek için arayın..."
                wire:model.live="query"
                wire:keydown.escape="resetSearch"
                wire:keydown.tab="resetSearch"
                wire:keydown.arrow-up="decrementHighlight"
                wire:keydown.arrow-down="incrementHighlight"
                wire:keydown.enter.prevent="selectPage"
            />

            @if(!empty($query))
                <div class="position-fixed top-0 bottom-0 left-0 right-0" wire:click="resetSearch"></div>
                <div class="position-absolute w-100 bg-white shadow-lg list-group" style="max-height: 150px; overflow-y: auto; z-index:10;">
                    @forelse($pages as $i => $page)
                    <a
                        id="item-{{ $i }}"
                        href="javascript:void(0)"
                        wire:click="selectPage({{ $i }})"
                        style="padding: 10px;"
                        class="list-item {{ $highlightIndex === $i ? 'bg-primary text-white' : '' }}"
                    >
                        {{ $page->title }}
                    </a>
                @empty
                    <div class="list-item" style="padding: 10px;">Sonuç bulunamadı!</div>
                @endforelse
                </div>
            @endif
        </div>

        @if($selectedPage)
            <div class="mb-3" style="display: flex; justify-content: start; text-align: center; align-items: center;">
                <span> <b>Seçilen üst sayfa:</b> {{ $selectedPageName }}</span>
                <a class="btn btn-sm btn-link text-white" wire:click.prevent="resetParent">
                    <svg class="nav-icon text-danger" style="width: 20px; height: 20px;"><use xlink:href="{{ URL::to('admin/vendors/@coreui/icons/svg/free.svg#cil-x') }}"></use></svg>
                </a>
            </div>
        @endif

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="title">Başlık *</label>
            <div class="col-sm-10">
                <input class="form-control" id="title" type="text" wire:model.live="title" required
                    autocomplete="off">
                <div>
                    @error('title')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="slug">Slug *</label>
            <div class="col-sm-10">
                <div class="input-group mb-3"><span class="input-group-text"
                        id="basic-addon3">{{ url('/') }}/</span>
                    <input class="form-control" id="slug" type="text" wire:model.live="slug" autocomplete="off">
                </div>
                <div>
                    @error('slug')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="description">Açıklama</label>
            <div class="col-sm-10">
                <input class="form-control" id="description" type="text" wire:model.live="description"
                    autocomplete="off">
                <div>
                    @error('description')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </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="row mb-3">
            <label class="col-sm-2 col-form-label" for="content">Alternatif İçerik</label>
            <div class="col-sm-10">
                <div wire:ignore>
                    <textarea wire:model="alternative_content" class="form-control" name="alternative_content" id="alternative_content"></textarea>
                </div>
                <div>
                    @error('alternative_content')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <hr />
        <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 0; margin: 0 0 30px 0;">
            <h3 class="text-primary">Görseller</h3>
            <button class="btn btn-primary text-white" type="button" id="lfm1" data-path="path-lfm1" data-preview="holder-lfm1" style="height: 5rem;"> Dosya <br/> Yöneticisi </button>
        </div>

        <div id="inputs-container">
            <div class="row" wire:sortable="updateOrder">
                @foreach($inputs as $index => $input)
                    <div class="col-lg-3 mb-4" wire:sortable.item="{{ $input['id'] }}" wire:key="item-{{ $input['id'] }}-{{ $index }}">
                        <div style="display: flex; justify-content: center;" wire:sortable.handle style="cursor:move;">
                            <div style="display: flex; flex-direction: column; justify-content: center; text-align: center; gap: 10px;">
                                <div>
                                    <input type="hidden" wire:model="inputs.{{ $index }}.fileName" class="form-control" readonly>
                                    <input type="hidden" wire:model="inputs.{{ $index }}.filePath" name="image_paths[]">
                                    <img src="{{ $input['filePath'] }}" style="width: 200px; height: 200px; object-fit: contain;"/>
                                </div>
                                <div>
                                    <input class="form-control" wire:model="inputs.{{ $index }}.title" type="text" autocomplete="off" placeholder="başlık / grup adı" style="text-align: center;" onmousedown="event.stopPropagation();"
                                    ontouchstart="event.stopPropagation();">
                                </div>
                            </div>
                            <span>
                                <a href="javascript:void(0)" wire:click.prevent="removeInput({{ $index }})">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width:24px; color: var(--cui-link-color);">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                                    </svg>
                                </a>
                            </span>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
        <hr />

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="meta_title">Meta - Başlık</label>
            <div class="col-sm-10">
                <input class="form-control" id="meta_title" type="text" wire:model="meta_title" required
                    autocomplete="off">
                <div>
                    @error('meta_title')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="meta_keywords">Meta - Anahtar Kelimeler</label>
            <div class="col-sm-10">
                <input class="form-control" id="meta_keywords" type="text" wire:model="meta_keywords" required
                    autocomplete="off">
                <div>
                    @error('meta_keywords')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="meta_description">Meta - Açıklama</label>
            <div class="col-sm-10">
                <textarea class="form-control" id="meta_description" wire:model="meta_description" required autocomplete="off"></textarea>
                <div>
                    @error('meta_description')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <hr>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="status">Durum</label>
            <div class="col-sm-10" style="display: flex; justify-content: start; align-items: center;">
                <div class="form-check form-switch form-switch-xl">
                    <input class="form-check-input" id="status" type="checkbox" wire:model.live="status" @if($status) checked @endif>
                </div>
                <div>
                    @error('status')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="display_in_navigation">Navigasyonda Göster</label>
            <div class="col-sm-10" style="display: flex; justify-content: start; align-items: center;">
                <div class="form-check form-switch form-switch-xl">
                    <input class="form-check-input" id="display_in_navigation" type="checkbox" wire:model.live="display_in_navigation" @if($display_in_navigation) checked @endif>
                </div>
                <div>
                    @error('display_in_navigation')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <button class="btn btn-primary" type="submit" wire:click.prevent="save" wire:loading.attr="disabled" wire:target="save">Güncelle</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(selector, propertyName, initialData) {
            ClassicEditor
                .create(document.querySelector(selector), {
                    removePlugins: ['Title'],
                    extraPlugins: [MyCustomUploadAdapterPlugin],
                    height: 250,
                    htmlSupport: {
                        allow: [
                            {
                                name: /.*/,
                                attributes: {
                                    class: true
                                }
                            }
                        ]
                    }
                })
                .then(editor => {
                    editor.editing.view.change(writer => {
                        writer.setStyle('height', '250px', editor.editing.view.document.getRoot());
                    });
    
                    editor.model.document.on('change:data', () => {
                        @this.set(propertyName, editor.getData());
                    });
    
                    Livewire.on('languageChanged', function(event) {
                        editor.setData(event[propertyName]);
                    });
    
                    editor.setData(initialData);
                })
                .catch(error => {
                    console.error(error);
                });
        }
    
        function initCKEditors() {
            initCKEditor('#content', 'content', @json($content));
            initCKEditor('#alternative_content', 'alternative_content', @json($alternative_content));
        }
    </script>

@endpush