@extends('layouts.app')

@section('title', 'Edit Artikel')

@section('content')
<div class="bg-gray-50 min-h-screen">


    <div class="h-48 md:h-64 bg-gradient-to-r from-blue-900 via-blue-600 to-blue-400 w-full absolute top-0 left-0 z-0"></div>

    <div class="container max-w-6xl mx-auto px-4 py-8 relative z-10">

  
        @if(session('success') || session('error'))
        <div x-data="{ show: true }"
             x-show="show"
             x-transition
             x-init="setTimeout(() => show = false, 4000)"
             class="fixed top-24 right-6 z-[999] max-w-xs w-full p-4 rounded-xl shadow-xl border-l-4
             {{ session('success') ? 'bg-green-50 border-green-500 text-green-700' : 'bg-red-50 border-red-500 text-red-700' }}">

            <div class="flex justify-between items-center">
                <span class="text-sm font-semibold">
                    {{ session('success') ?: session('error') }}
                </span>
                <button @click="show=false" class="text-lg">✕</button>
            </div>
        </div>
        @endif

        <form action="{{ route('admin.articles.update', $article) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')

            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-8">
                <div class="text-white">
                    <h1 class="text-2xl md:text-3xl font-bold">Edit Artikel</h1>
                    <p class="text-blue-100 text-sm">Perbarui artikel dengan mudah</p>
                </div>

                <div class="flex flex-col sm:flex-row gap-2 w-full md:w-auto">
                    <a href="{{ route('admin.articles.index') }}"
                        class="w-full sm:w-auto text-center px-4 py-2 rounded-xl bg-white/10 backdrop-blur border border-white/20 text-white hover:bg-white/20 transition">
                        Kembali
                    </a>

                    <button type="submit"
                        class="w-full sm:w-auto px-4 py-2 rounded-xl bg-white text-blue-900 font-semibold shadow hover:shadow-lg hover:-translate-y-0.5 transition">
                        ✔ Update
                    </button>
                </div>
            </div>


            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

                <div class="lg:col-span-2 space-y-6">

           
                    <div class="bg-white rounded-2xl p-6 shadow-sm border">
                        <label class="text-sm font-semibold text-gray-700 mb-2 block">Judul Artikel</label>
                        <input type="text" name="title"
                            class="w-full rounded-xl border-gray-300 focus:ring-2 focus:ring-blue-500"
                            value="{{ old('title', $article->title) }}" required>
                    </div>

                    <div class="bg-white rounded-2xl p-6 shadow-sm border">
                        <label class="text-sm font-semibold text-gray-700 mb-3 block">Konten</label>
                        <textarea name="content" id="content">{{ old('content', $article->content) }}</textarea>
                    </div>

                </div>

    
                <div class="space-y-6">

                    <div class="bg-white rounded-2xl p-5 shadow-sm border">
                        <label class="text-sm font-semibold text-gray-700 mb-2 block">Kategori</label>

                        <select name="category_id"
                            class="w-full rounded-xl border-gray-300 focus:ring-2 focus:ring-blue-500">
                            @foreach ($categories as $category)
                                <option value="{{ $category->id }}"
                                    {{ old('category_id', $article->category_id) == $category->id ? 'selected' : '' }}>
                                    {{ $category->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div class="bg-white rounded-2xl p-5 shadow-sm border">

                        <h3 class="text-sm font-semibold text-gray-700 mb-4">Gambar Artikel</h3>

                        @if ($article->images->isNotEmpty())
                        <div class="grid grid-cols-2 gap-3 mb-4">
                            @foreach ($article->images as $image)
                            <div x-data="{ checked: false }" class="relative group">

                                <img src="{{ asset('storage/' . $image->path) }}"
                                     class="h-28 w-full object-cover rounded-xl transition"
                                     :class="{ 'ring-2 ring-red-500': checked }">

                                <div class="absolute inset-0 bg-black/0 group-hover:bg-black/60 transition flex items-center justify-center rounded-xl">
                                    <input type="checkbox"
                                           name="delete_images[]"
                                           value="{{ $image->id }}"
                                           x-model="checked"
                                           class="opacity-0 group-hover:opacity-100 w-5 h-5 cursor-pointer">

                                    <span class="absolute text-white text-xs opacity-0 group-hover:opacity-100">
                                        Hapus
                                    </span>
                                </div>

                            </div>
                            @endforeach
                        </div>
                        @endif

                        <div x-data="imageUploader()">
                            <div @dragover.prevent @drop.prevent="dropHandler($event)"
                                class="border-2 border-dashed border-gray-300 rounded-xl p-5 text-center hover:border-blue-400 transition">

                                <p class="text-sm text-gray-600">
                                    <label for="images" class="text-blue-600 font-semibold cursor-pointer">
                                        Upload
                                    </label>
                                    atau drag file
                                </p>

                                <input id="images" name="images[]" type="file" class="hidden" multiple
                                    @change="handleFileSelect($event)">
                            </div>

                            <div class="mt-3 grid grid-cols-2 gap-2">
                                <template x-for="(preview, i) in previews" :key="i">
                                    <div class="relative">
                                        <img :src="preview.url" class="h-24 w-full object-cover rounded-xl">
                                        <button @click.prevent="removePreview(i)"
                                            class="absolute top-1 right-1 bg-red-500 text-white w-5 h-5 text-xs rounded-full">
                                            ✕
                                        </button>
                                    </div>
                                </template>
                            </div>
                        </div>

                    </div>

                </div>
            </div>
        </form>
    </div>
</div>
@endsection


@push('scripts')


<script src="https://cdn.ckeditor.com/ckeditor5/41.4.2/classic/ckeditor.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    ClassicEditor
        .create(document.querySelector('#content'))
        .then(editor => {
            editor.editing.view.change(writer => {
                writer.setStyle('min-height', '250px', editor.editing.view.document.getRoot());
            });
        })
        .catch(error => console.error(error));
});
</script>

<script>
function imageUploader() {
    return {
        previews: [],
        files: [],
        handleFileSelect(e) {
            this.addFiles(Array.from(e.target.files));
        },
        dropHandler(e) {
            this.addFiles(Array.from(e.dataTransfer.files));
        },
        addFiles(files) {
            files.forEach(file => {
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = e => this.previews.push({ url: e.target.result });
                    reader.readAsDataURL(file);
                    this.files.push(file);
                }
            });
            this.updateInput();
        },
        removePreview(i) {
            this.previews.splice(i,1);
            this.files.splice(i,1);
            this.updateInput();
        },
        updateInput() {
            const dt = new DataTransfer();
            this.files.forEach(f => dt.items.add(f));
            document.getElementById('images').files = dt.files;
        }
    }
}
</script>

@endpush