<?php
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Post;
use App\Models\Category;
use Illuminate\Support\Str;
?>

<div class="max-content">
    <header class="flex justify-between items-center mb-10">
        <div>
            <h1 class="text-2xl font-semibold tracking-tight text-gray-900">Create New Post</h1>
            <p class="text-sm text-gray-500 mt-1">Compose a new article or progress note.</p>
        </div>
        <div class="flex gap-3">
            <a href="{{ route('admin.blog') }}" wire:navigate class="px-4 py-2 border border-gray-300 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-50 transition-colors">Cancel</a>
            <button type="button" wire:click="save" wire:loading.attr="disabled" class="px-4 py-2 bg-sage text-white text-sm font-medium rounded-md hover:bg-sage-dark transition-colors disabled:opacity-50" style="background-color: #99BC85;">
                <span wire:loading.remove wire:target="save">Publish Post</span>
                <span wire:loading wire:target="save">Publishing...</span>
            </button>
        </div>
    </header>

    @if (session()->has('message'))
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
            <span class="block sm:inline">{{ session('message') }}</span>
        </div>
    @endif

    <form wire:submit.prevent="save" class="space-y-8">
        <!-- Content Card -->
        <div class="card p-8 space-y-6">
            <h2 class="text-sm font-semibold border-b border-gray-100 pb-4 mb-2 text-gray-900">Main Content</h2>
            <div>
                <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Post Title</label>
                <input type="text" wire:model.live="title" class="input-field w-full text-lg font-medium" placeholder="Enter post title..." required>
                @error('title') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Slug</label>
                    <input type="text" wire:model="slug" class="input-field w-full" placeholder="e.g. new-project-update">
                    @error('slug') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                </div>
                <div>
                    <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Category</label>
                    <select wire:model="category_id" class="input-field w-full">
                        <option value="">Select Category</option>
                        @foreach($categories as $category)
                            <option value="{{ $category->id }}">{{ $category->name }}</option>
                        @endforeach
                    </select>
                    @error('category_id') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                </div>
            </div>

            <div>
                <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Featured Image</label>
                <div class="flex flex-col gap-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="text-xs text-gray-400">Image URL</label>
                            <input type="text" wire:model="image_url" class="input-field w-full" placeholder="https://images.unsplash.com/...">
                        </div>
                        <div>
                            <label class="text-xs text-gray-400">Or Upload File</label>
                            <input type="file" wire:model="image_file" class="input-field w-full">
                            <div wire:loading wire:target="image_file" class="text-xs text-gray-500 mt-1">Uploading...</div>
                        </div>
                    </div>
                    <div>
                        <label class="text-xs text-gray-400">Image Caption</label>
                        <input type="text" wire:model="image_caption" class="input-field w-full" placeholder="Enter image caption...">
                    </div>
                    @if ($image_file)
                        <div class="mt-2">
                            <img src="{{ $image_file->temporaryUrl() }}" class="w-32 h-20 object-cover rounded-md border">
                        </div>
                    @endif
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 pt-4">
                <div class="flex items-center gap-3">
                    <input type="checkbox" wire:model="is_featured" id="is_featured" class="w-4 h-4 text-sage border-gray-300 rounded focus:ring-sage">
                    <label for="is_featured" class="text-sm font-medium text-gray-700">Mark as Featured (Hero Section)</label>
                </div>
                <div class="flex items-center gap-3">
                    <input type="checkbox" wire:model="is_breaking" id="is_breaking" class="w-4 h-4 text-sage border-gray-300 rounded focus:ring-sage">
                    <label for="is_breaking" class="text-sm font-medium text-gray-700">Mark as Breaking (News Ticker)</label>
                </div>
            </div>

            <div wire:ignore>
                <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2 text-gray-900">Content</label>
                <div id="editor" style="height: 300px;"></div>
            </div>
            @error('content') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
        </div>

        <!-- SEO Card -->
        <div class="card p-8 space-y-6">
            <h2 class="text-sm font-semibold border-b border-gray-100 pb-4 mb-2 text-gray-900">SEO Details</h2>
            <div>
                <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Meta Title</label>
                <input type="text" wire:model="meta_title" class="input-field w-full" placeholder="Focus keyword title for search engines...">
            </div>
            <div>
                <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Meta Description</label>
                <textarea wire:model="meta_description" rows="3" class="input-field w-full resize-none" placeholder="Brief summary for search results (approx. 150-160 characters)..."></textarea>
            </div>
            <div>
                <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Keywords</label>
                <input type="text" wire:model="meta_keywords" class="input-field w-full" placeholder="e.g. sanitation, odisha, sustainable growth (comma separated)">
            </div>
        </div>

        <div class="flex justify-end gap-3 pb-12">
            <button type="button" wire:click="saveAsDraft" wire:loading.attr="disabled" class="px-4 py-2 border border-gray-300 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-50 transition-colors">
                <span wire:loading.remove wire:target="saveAsDraft">Save as Draft</span>
                <span wire:loading wire:target="saveAsDraft">Saving...</span>
            </button>
            <button type="submit" wire:loading.attr="disabled" class="px-8 py-2 bg-sage text-white text-sm font-medium rounded-md hover:bg-sage-dark transition-colors disabled:opacity-50" style="background-color: #99BC85;">
                <span wire:loading.remove wire:target="save">Publish Post</span>
                <span wire:loading wire:target="save">Publishing...</span>
            </button>
        </div>
    </form>

    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <style>
    .ql-video-modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; justify-content: center; align-items: center; }
    .ql-video-modal.active { display: flex; }
    .ql-video-modal .modal-content { background: #fff; padding: 24px; border-radius: 8px; width: 420px; max-width: 90%; box-shadow: 0 4px 24px rgba(0,0,0,0.15); }
    .ql-video-modal .modal-content h3 { margin: 0 0 4px; font-size: 16px; font-weight: 600; color: #111827; }
    .ql-video-modal .modal-content p.hint { margin: 0 0 12px; font-size: 12px; color: #6b7280; }
    .ql-video-modal input { width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 6px; margin-bottom: 16px; font-size: 14px; outline: none; box-sizing: border-box; }
    .ql-video-modal input:focus { border-color: #99BC85; box-shadow: 0 0 0 2px rgba(153,188,133,0.25); }
    .ql-video-modal .btn-row { display: flex; justify-content: flex-end; gap: 8px; }
    .ql-video-modal button { padding: 8px 20px; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500; border: none; }
    .ql-video-modal .btn-cancel { background: #f3f4f6; color: #374151; }
    .ql-video-modal .btn-cancel:hover { background: #e5e7eb; }
    .ql-video-modal .btn-insert { background: #99BC85; color: #fff; }
    .ql-video-modal .btn-insert:hover { background: #86a872; }
    .video-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; margin: 1rem 0; }
    .video-container iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0; }
    </style>
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
    <script>
        let quillInstance = null;
        function extractYouTubeId(url) {
            const patterns = [
                /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/,
                /^([a-zA-Z0-9_-]{11})$/
            ];
            for (const p of patterns) {
                const m = url.match(p);
                if (m) return m[1];
            }
            return null;
        }
        function closeVideoModal() {
            document.getElementById('qlVideoModal').classList.remove('active');
            document.getElementById('qlVideoUrl').value = '';
        }
        function insertVideo() {
            const url = document.getElementById('qlVideoUrl').value.trim();
            const videoId = extractYouTubeId(url);
            if (!videoId) { alert('Invalid YouTube URL'); return; }
            const html = '<div class="video-container"><iframe width="560" height="315" src="https://www.youtube.com/embed/' + videoId + '" frameborder="0" allowfullscreen></iframe></div><p><br></p>';
            const range = quillInstance.getSelection(true);
            quillInstance.clipboard.dangerouslyPasteHTML(range.index, html);
            closeVideoModal();
        }
        (function() {
            function initQuill() {
                const editorEl = document.getElementById('editor');
                if (!editorEl || editorEl.classList.contains('ql-container')) return;
                
                const quill = new Quill('#editor', {
                    theme: 'snow',
                    modules: {
                        toolbar: [
                            [{ 'header': [1, 2, 3, false] }],
                            ['bold', 'italic', 'underline', 'strike'],
                            ['link', 'blockquote', 'code-block', 'image', 'video'],
                            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                            ['clean']
                        ]
                    }
                });

                quill.root.innerHTML = @js($content);

                quill.on('text-change', function() {
                    @this.set('content', quill.root.innerHTML);
                });

                const toolbar = quill.getModule('toolbar');
                if (toolbar) {
                    toolbar.addHandler('video', function() {
                        document.getElementById('qlVideoModal').classList.add('active');
                    });
                }
                quillInstance = quill;
            }

            initQuill();
            document.addEventListener('livewire:navigated', initQuill);
        })();
    </script>

    <div class="ql-video-modal" id="qlVideoModal">
        <div class="modal-content">
            <h3>Insert YouTube Video</h3>
            <p class="hint">Paste a YouTube, YouTube Shorts, or youtu.be link</p>
            <input type="text" id="qlVideoUrl" placeholder="https://www.youtube.com/watch?v=...">
            <div class="btn-row">
                <button class="btn-cancel" onclick="closeVideoModal()">Cancel</button>
                <button class="btn-insert" onclick="insertVideo()">Insert</button>
            </div>
        </div>
    </div>
</div>