<?php
use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\SocialPost;
use App\Services\SocialScraper;
use Illuminate\Support\Facades\Storage;
?>

<div class="max-content">

    <header class="flex justify-between items-start mb-10">
        <div>
            <h1 class="text-2xl font-semibold tracking-tight text-gray-900">Social Media Feed</h1>
            <p class="text-sm text-gray-500 mt-1">Paste a YouTube, Instagram, or Facebook URL to scrape and display it on the website.</p>
        </div>
    </header>

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

    {{-- ═══════════════════════════════════════════════════════════ --}}
    {{-- SCRAPER CARD (hidden while editing)                         --}}
    {{-- ═══════════════════════════════════════════════════════════ --}}
    @if(! $editingId)
    <div class="card p-6 mb-8">
        <h2 class="text-sm font-bold uppercase tracking-widest text-gray-400 mb-5">Add New Post from URL</h2>

        @if(! $preview)
            <div class="flex gap-3">
                <input type="url" wire:model="scrapeUrl"
                    placeholder="https://www.youtube.com/watch?v=...  or  instagram.com/p/...  or  facebook.com/..."
                    class="input-field flex-1 text-sm"
                    wire:keydown.enter="fetch">
                <button wire:click="fetch" wire:loading.attr="disabled"
                    class="px-6 py-2 text-sm font-bold text-white rounded-md transition-colors"
                    style="background-color:#99BC85;">
                    <span wire:loading.remove wire:target="fetch">Fetch</span>
                    <span wire:loading wire:target="fetch">Fetching...</span>
                </button>
            </div>

            @error('scrapeUrl')
                <p class="text-red-500 text-xs mt-2">{{ $message }}</p>
            @enderror

            @if($scrapeError)
                <div class="mt-3 bg-red-50 border border-red-200 text-red-600 text-sm px-4 py-3 rounded-md flex items-start gap-2">
                    <i class="fa-solid fa-circle-exclamation mt-0.5 shrink-0"></i>
                    <span>{{ $scrapeError }}</span>
                </div>
            @endif

            <div class="flex gap-4 mt-4">
                <span class="flex items-center gap-1.5 text-[11px] text-gray-400 font-semibold"><i class="fa-brands fa-youtube text-red-500"></i> YouTube</span>
                <span class="flex items-center gap-1.5 text-[11px] text-gray-400 font-semibold"><i class="fa-brands fa-instagram text-pink-500"></i> Instagram</span>
                <span class="flex items-center gap-1.5 text-[11px] text-gray-400 font-semibold"><i class="fa-brands fa-facebook text-blue-600"></i> Facebook</span>
            </div>

        @else
            <div class="border border-green-200 bg-green-50/40 rounded-lg p-5">
                <div class="flex items-center gap-2 mb-4">
                    <i class="fa-solid fa-circle-check text-green-600"></i>
                    <span class="text-sm font-bold text-green-700">Fetched successfully — preview below</span>
                </div>
                <div class="flex gap-5 items-start">
                    @if($preview['thumbnail_url'])
                        <img src="{{ $preview['thumbnail_url'] }}" alt="thumbnail"
                            class="w-36 h-24 object-cover rounded-md border border-gray-200 shrink-0">
                    @endif
                    <div class="flex-1 min-w-0">
                        @php $icon = match($preview['platform']) { 'youtube' => 'fa-brands fa-youtube text-red-600', 'instagram' => 'fa-brands fa-instagram text-pink-500', 'facebook' => 'fa-brands fa-facebook text-blue-600', default => 'fa-solid fa-share-nodes text-gray-400' }; @endphp
                        <div class="flex items-center gap-2 mb-2">
                            <i class="{{ $icon }} text-lg"></i>
                            <span class="text-[11px] font-bold uppercase tracking-widest text-gray-400">{{ ucfirst($preview['platform']) }}</span>
                        </div>
                        <p class="font-bold text-gray-900 text-sm leading-snug mb-1">{{ $preview['title'] ?: '(No title)' }}</p>
                        @if($preview['author_name']) <p class="text-xs text-gray-500 mb-1"><span class="font-semibold">By:</span> {{ $preview['author_name'] }}</p> @endif
                        @if($preview['description']) <p class="text-xs text-gray-400 line-clamp-2">{{ $preview['description'] }}</p> @endif
                        <a href="{{ $preview['url'] }}" target="_blank" class="text-[11px] text-gray-400 hover:underline truncate block mt-1">{{ $preview['url'] }}</a>
                    </div>
                </div>
                <div class="flex gap-3 mt-5 pt-4 border-t border-green-200">
                    <button wire:click="save" wire:loading.attr="disabled" class="px-6 py-2 text-sm font-bold text-white rounded-md" style="background-color:#99BC85;">
                        <span wire:loading.remove wire:target="save">Save to Feed</span>
                        <span wire:loading wire:target="save">Saving...</span>
                    </button>
                    <button wire:click="cancelPreview" class="px-4 py-2 text-sm font-semibold text-gray-600 bg-white border border-gray-200 rounded-md hover:bg-gray-50">Cancel</button>
                </div>
            </div>
        @endif
    </div>
    @endif

    {{-- ═══════════════════════════════════════════════════════════ --}}
    {{-- EDIT CARD                                                   --}}
    {{-- ═══════════════════════════════════════════════════════════ --}}
    @if($editingId)
    <div class="card p-6 mb-8 border-l-4" style="border-left-color:#99BC85;">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-sm font-bold uppercase tracking-widest text-gray-400">Edit Post</h2>
            <button wire:click="cancelEdit" class="text-gray-400 hover:text-gray-700 text-sm">
                <i class="fa-solid fa-xmark"></i> Cancel
            </button>
        </div>

        <form wire:submit.prevent="updatePost" class="space-y-5">

            <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                <!-- Title -->
                <div class="md:col-span-2">
                    <label class="block text-[11px] font-bold text-gray-500 uppercase tracking-wider mb-1.5">Title <span class="text-red-400">*</span></label>
                    <input type="text" wire:model="editTitle" class="input-field w-full text-sm">
                    @error('editTitle') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                </div>

                <!-- Author -->
                <div>
                    <label class="block text-[11px] font-bold text-gray-500 uppercase tracking-wider mb-1.5">Author / Channel</label>
                    <input type="text" wire:model="editAuthorName" class="input-field w-full text-sm" placeholder="e.g. Bikash Barta">
                    @error('editAuthorName') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                </div>

                <!-- Description -->
                <div>
                    <label class="block text-[11px] font-bold text-gray-500 uppercase tracking-wider mb-1.5">Description</label>
                    <input type="text" wire:model="editDescription" class="input-field w-full text-sm" placeholder="Short description (optional)">
                </div>
            </div>

            <!-- Thumbnail Section -->
            <div class="border border-gray-100 rounded-lg p-5 bg-gray-50/50">
                <label class="block text-[11px] font-bold text-gray-500 uppercase tracking-wider mb-4">Thumbnail</label>

                <div class="flex flex-col md:flex-row gap-6 items-start">
                    <!-- Current Thumbnail Preview -->
                    <div class="shrink-0">
                        <p class="text-[10px] text-gray-400 uppercase font-bold mb-2">Current</p>
                        @if($editThumbnailUrl)
                            <img src="{{ str_starts_with($editThumbnailUrl, 'http') ? $editThumbnailUrl : Storage::url($editThumbnailUrl) }}"
                                alt="current thumbnail"
                                class="w-36 h-24 object-cover rounded-md border border-gray-200">
                        @else
                            <div class="w-36 h-24 bg-gray-100 rounded-md border border-gray-200 flex items-center justify-center">
                                <i class="fa-solid fa-image text-gray-300 text-xl"></i>
                            </div>
                        @endif
                    </div>

                    <div class="flex-1 space-y-4 w-full">
                        <!-- Upload new file -->
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 uppercase tracking-wider mb-1.5">
                                Upload New Image <span class="normal-case text-gray-400 font-normal">(replaces current)</span>
                            </label>
                            <input type="file" wire:model="editThumbnailFile" accept="image/*"
                                class="w-full text-sm text-gray-500 file:mr-3 file:py-1.5 file:px-4 file:rounded file:border-0 file:text-xs file:font-bold file:bg-gray-200 file:text-gray-700 hover:file:bg-gray-300 cursor-pointer">
                            @error('editThumbnailFile') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror

                            @if($editThumbnailFile)
                                <div class="mt-3 flex items-center gap-3">
                                    <img src="{{ $editThumbnailFile->temporaryUrl() }}" alt="preview"
                                        class="w-24 h-16 object-cover rounded border border-gray-200">
                                    <span class="text-xs text-green-600 font-semibold">New thumbnail ready to save</span>
                                </div>
                            @endif
                        </div>

                        <!-- Or paste URL -->
                        <div>
                            <label class="block text-[11px] font-bold text-gray-500 uppercase tracking-wider mb-1.5">
                                Or Paste Thumbnail URL
                            </label>
                            <input type="url" wire:model="editThumbnailUrl" class="input-field w-full text-sm"
                                placeholder="https://example.com/image.jpg">
                            @error('editThumbnailUrl') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
                            <p class="text-[10px] text-gray-400 mt-1">Leave blank to keep current. URL is ignored if a file is uploaded above.</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Embed HTML -->
            <div>
                <label class="block text-[11px] font-bold text-gray-500 uppercase tracking-wider mb-1.5">Embed HTML</label>
                <textarea wire:model="editEmbedHtml" rows="4"
                    class="input-field w-full text-xs font-mono resize-y"
                    placeholder="<iframe ...></iframe>"></textarea>
                <p class="text-[10px] text-gray-400 mt-1">This is the code displayed on the frontend. Edit only if the embed is broken.</p>
                @error('editEmbedHtml') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
            </div>

            <!-- Actions -->
            <div class="flex gap-3 pt-2">
                <button type="submit" wire:loading.attr="disabled"
                    class="px-8 py-2 text-sm font-bold text-white rounded-md transition-colors disabled:opacity-60"
                    style="background-color:#99BC85;">
                    <span wire:loading.remove wire:target="updatePost">Save Changes</span>
                    <span wire:loading wire:target="updatePost">Saving...</span>
                </button>
                <button type="button" wire:click="cancelEdit"
                    class="px-4 py-2 text-sm font-semibold text-gray-600 bg-white border border-gray-200 rounded-md hover:bg-gray-50">
                    Cancel
                </button>
            </div>

        </form>
    </div>
    @endif

    {{-- ═══════════════════════════════════════════════════════════ --}}
    {{-- POSTS TABLE                                                 --}}
    {{-- ═══════════════════════════════════════════════════════════ --}}
    <div class="card">
        <div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
            <h2 class="text-sm font-bold text-gray-700">Saved Posts</h2>
            <span class="text-xs text-gray-400">{{ $posts->count() }} total</span>
        </div>
        <div class="overflow-x-auto">
            <table>
                <thead>
                    <tr>
                        <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Post</th>
                        <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Platform</th>
                        <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Author</th>
                        <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Added</th>
                        <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3 bg-gray-50 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @forelse($posts as $post)
                        @php
                            $thumbSrc = $post->thumbnail_url
                                ? (str_starts_with($post->thumbnail_url, 'http')
                                    ? $post->thumbnail_url
                                    : Storage::url($post->thumbnail_url))
                                : null;
                            $isEditing = $editingId === $post->id;
                        @endphp
                        <tr class="transition-colors {{ $isEditing ? 'bg-green-50/30' : 'hover:bg-gray-50/50' }}">
                            <td class="px-6 py-4">
                                <div class="flex items-center gap-3">
                                    @if($thumbSrc)
                                        <img src="{{ $thumbSrc }}" alt="thumb"
                                            class="w-16 h-11 object-cover rounded border border-gray-100 shrink-0">
                                    @else
                                        <div class="w-16 h-11 bg-gray-100 rounded border border-gray-100 shrink-0 flex items-center justify-center">
                                            <i class="fa-solid fa-image text-gray-300 text-sm"></i>
                                        </div>
                                    @endif
                                    <div class="min-w-0">
                                        <p class="text-sm font-semibold text-gray-900 truncate max-w-xs">{{ $post->title ?: '(No title)' }}</p>
                                        <a href="{{ $post->url }}" target="_blank"
                                            class="text-[11px] text-gray-400 hover:underline truncate max-w-xs block">{{ Str::limit($post->url, 50) }}</a>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="flex items-center gap-1.5 text-xs font-semibold text-gray-600 max-w-[120px] truncate">
                                    <i class="{{ $post->platform_icon }}"></i>
                                    {{ ucfirst($post->platform) }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 max-w-[150px] truncate">{{ $post->author_name ?: '—' }}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-xs text-gray-400">{{ $post->created_at->format('d M Y') }}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <button wire:click="toggleStatus({{ $post->id }})"
                                    class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none
                                    {{ $post->status === 'show' ? 'bg-green-500' : 'bg-gray-200' }}">
                                    <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform
                                        {{ $post->status === 'show' ? 'translate-x-6' : 'translate-x-1' }}">
                                    </span>
                                </button>
                                <span class="ml-2 text-[11px] font-bold {{ $post->status === 'show' ? 'text-green-600' : 'text-gray-400' }}">
                                    {{ $post->status === 'show' ? 'Visible' : 'Hidden' }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-right text-sm space-x-3">
                                @if($isEditing)
                                    <span class="text-xs font-bold" style="color:#99BC85;">Editing...</span>
                                @else
                                    <button wire:click="openEdit({{ $post->id }})" wire:loading.attr="disabled"
                                        class="text-xs font-semibold text-gray-500 hover:text-gray-900 transition-colors disabled:opacity-50">
                                        Edit
                                    </button>
                                @endif
                                <button wire:click="delete({{ $post->id }})"
                                    wire:confirm="Delete this post from the feed?"
                                    wire:loading.attr="disabled"
                                    class="text-xs font-semibold text-red-400 hover:text-red-600 transition-colors disabled:opacity-50">
                                    <span wire:loading.remove wire:target="delete({{ $post->id }})">Delete</span>
                                    <span wire:loading wire:target="delete({{ $post->id }})">...</span>
                                </button>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="6" class="px-6 py-12 text-center">
                                <i class="fa-brands fa-youtube text-3xl text-gray-200 mb-3 block"></i>
                                <p class="text-gray-400 text-sm">No posts saved yet. Paste a URL above to get started.</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

</div>