<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;
use Livewire\Attributes\Url;
use App\Models\SocialPost;
use App\Services\SocialScraper;
use App\Services\ImageCompressor;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;

new class extends Component
{
    use WithFileUploads, WithPagination;

    // ── Search & Filter ──────────────────────────────────────────
    #[Url(history: true)]
    public $search = '';

    #[Url(history: true)]
    public $platformFilter = '';

    #[Url(history: true)]
    public $statusFilter = '';

    // ── Scraper state ──────────────────────────────────────────────
    public $scrapeUrl   = '';
    public $preview     = null;
    public $scrapeError = '';

    // ── Bulk Import state ──────────────────────────────────────────
    public $activeTab = 'single'; // 'single' or 'bulk'
    public $bulkChannelInput = 'UCfxS5DCJygRmu3aQhzxlT3g';
    public $bulkNextPageToken = null;
    public $bulkImportCount = 0;
    public $bulkPlaylistId = null;
    public $isBulkImporting = false;
    public $bulkError = '';

    // ── Edit state ─────────────────────────────────────────────────
    public $editingId          = null;
    public $editUrl            = '';
    public $editTitle          = '';
    public $editDescription    = '';
    public $editAuthorName     = '';
    public $editThumbnailUrl   = '';   // existing URL or storage path
    public $editThumbnailFile  = null; // newly uploaded file
    public $editEmbedHtml      = '';
    public $storeLocally       = false;

    public function render()
    {
        return $this->view()->layout('layouts::auth');
    }

    public function setTab(string $tab): void
    {
        $this->activeTab = $tab;
        $this->cancelPreview();
        $this->cancelEdit();
    }

    public function with(): array
    {
        $query = SocialPost::latest();

        if ($this->search) {
            $query->where(function($q) {
                $q->where('title', 'like', '%' . $this->search . '%')
                  ->orWhere('description', 'like', '%' . $this->search . '%')
                  ->orWhere('author_name', 'like', '%' . $this->search . '%');
            });
        }

        if ($this->platformFilter) {
            $query->where('platform', $this->platformFilter);
        }

        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }

        return ['posts' => $query->paginate(10)];
    }

    public function updatingSearch() { $this->resetPage(); }
    public function updatingPlatformFilter() { $this->resetPage(); }
    public function updatingStatusFilter() { $this->resetPage(); }

    // ── Actions ────────────────────────────────────────────────────

    public function toggleStatus(int $id): void
    {
        $post = SocialPost::find($id);
        if ($post) {
            $post->status = ($post->status === 'show') ? 'hide' : 'show';
            $post->save();
        }
    }

    public function delete(int $id): void
    {
        $post = SocialPost::find($id);
        if ($post) {
            $this->deleteOldThumbnail($post->thumbnail_url);
            $post->delete();
            session()->flash('message', 'Post deleted successfully.');
        }
    }

    // ── Scraper ────────────────────────────────────────────────────

    public function fetch(): void
    {
        $this->validate(['scrapeUrl' => 'required|url']);
        $this->scrapeError = '';
        $this->preview     = null;

        try {
            $this->preview = (new SocialScraper())->scrape($this->scrapeUrl);
        } catch (\Exception $e) {
            $this->scrapeError = $e->getMessage();
        }
    }

    public function save(): void
    {
        if (! $this->preview) return;

        $data = $this->preview;

        if ($this->storeLocally && !empty($data['thumbnail_url'])) {
            $localPath = $this->downloadThumbnail($data['thumbnail_url']);
            if ($localPath) {
                $data['thumbnail_url'] = $localPath;
            }
        }

        SocialPost::create($data);

        $this->preview      = null;
        $this->scrapeUrl    = '';
        $this->storeLocally = false;
        session()->flash('message', 'Post saved successfully.');
    }

    public function cancelPreview(): void
    {
        $this->preview      = null;
        $this->scrapeUrl    = '';
        $this->scrapeError  = '';
        $this->storeLocally = false;
    }

    // ── Edit ───────────────────────────────────────────────────────

    public function openEdit(int $id): void
    {
        $post = SocialPost::find($id);
        if (! $post) return;

        $this->editingId         = $id;
        $this->editUrl           = $post->url ?? '';
        $this->editTitle         = $post->title ?? '';
        $this->editDescription   = $post->description ?? '';
        $this->editAuthorName    = $post->author_name ?? '';
        $this->editThumbnailUrl  = $post->thumbnail_url ?? '';
        $this->editEmbedHtml     = $post->embed_html ?? '';
        $this->editThumbnailFile = null;
        $this->storeLocally      = false;

        // Dismiss any open preview
        $this->preview = null;
    }

    public function refetch(): void
    {
        if (! $this->editUrl) return;

        try {
            $data = (new SocialScraper())->scrape($this->editUrl);
            $this->editTitle        = $data['title'] ?? $this->editTitle;
            $this->editDescription  = $data['description'] ?? $this->editDescription;
            $this->editAuthorName   = $data['author_name'] ?? $this->editAuthorName;
            $this->editThumbnailUrl = $data['thumbnail_url'] ?? $this->editThumbnailUrl;
            $this->editEmbedHtml    = $data['embed_html'] ?? $this->editEmbedHtml;

            session()->flash('edit_message', 'Data refetched from platform.');
        } catch (\Exception $e) {
            session()->flash('edit_error', 'Refetch failed: ' . $e->getMessage());
        }
    }

    public function updatePost(): void
    {
        $this->validate([
            'editTitle'         => 'required|string|max:500',
            'editAuthorName'    => 'nullable|string|max:255',
            'editDescription'   => 'nullable|string',
            'editThumbnailUrl'  => 'nullable|string', // could be a path or a URL
            'editThumbnailFile' => 'nullable|image|max:2048',
            'editEmbedHtml'     => 'nullable|string',
        ]);

        $post = SocialPost::find($this->editingId);
        if (! $post) return;

        $thumbnailUrl = $post->thumbnail_url; // keep existing by default

        if ($this->editThumbnailFile) {
            // Delete old uploaded thumbnail if it was a storage file
            $this->deleteOldThumbnail($post->thumbnail_url);
            $thumbnailUrl = app(ImageCompressor::class)->compress($this->editThumbnailFile, 'social-thumbnails');
        } elseif ($this->storeLocally && !empty($this->editThumbnailUrl) && str_starts_with($this->editThumbnailUrl, 'http')) {
            // User requested to store the current URL locally
            $this->deleteOldThumbnail($post->thumbnail_url);
            $localPath = $this->downloadThumbnail($this->editThumbnailUrl);
            $thumbnailUrl = $localPath ?: $this->editThumbnailUrl;
        } elseif ($this->editThumbnailUrl !== $post->thumbnail_url) {
            // URL was manually changed — delete old file if it was stored
            $this->deleteOldThumbnail($post->thumbnail_url);
            $thumbnailUrl = $this->editThumbnailUrl;
        }

        $post->update([
            'title'         => $this->editTitle,
            'description'   => $this->editDescription,
            'author_name'   => $this->editAuthorName,
            'thumbnail_url' => $thumbnailUrl,
            'embed_html'    => $this->editEmbedHtml,
        ]);

        $this->cancelEdit();
        session()->flash('message', 'Post updated successfully.');
    }

    public function cancelEdit(): void
    {
        $this->editingId         = null;
        $this->editUrl           = '';
        $this->editTitle         = '';
        $this->editDescription   = '';
        $this->editAuthorName    = '';
        $this->editThumbnailUrl  = '';
        $this->editThumbnailFile = null;
        $this->editEmbedHtml     = '';
        $this->storeLocally      = false;
        $this->resetValidation();
    }

    private function deleteOldThumbnail(?string $path): void
    {
        if ($path && ! str_starts_with($path, 'http')) {
            Storage::disk('public')->delete($path);
        }
    }

    private function downloadThumbnail(string $url): ?string
    {
        try {
            $response = Http::get($url);
            if ($response->successful()) {
                return app(ImageCompressor::class)->compressFromContent($response->body(), 'social-thumbnails');
            }
        } catch (\Exception $e) {
            // Log or handle error
        }
        return null;
    }

    public function startBulkImport(): void
    {
        $this->validate(['bulkChannelInput' => 'required']);
        $this->bulkError = '';
        $this->bulkImportCount = 0;
        $this->bulkNextPageToken = null;
        $this->isBulkImporting = true;

        $apiKey = config('services.youtube.api_key');
        
        // --- LITE MODE (RSS) ---
        if (!$apiKey) {
            $this->runLiteImport();
            return;
        }

        // --- FULL MODE (API) ---
        try {
            // Resolve channel to get uploads playlist ID
            $params = [
                'key' => $apiKey,
                'part' => 'contentDetails',
            ];

            if (str_starts_with($this->bulkChannelInput, '@')) {
                $params['forHandle'] = $this->bulkChannelInput;
            } else {
                $params['id'] = $this->bulkChannelInput;
            }

            $response = Http::get('https://www.googleapis.com/youtube/v3/channels', $params);

            if (!$response->successful() || empty($response->json()['items'])) {
                throw new \Exception('Channel not found or API key invalid.');
            }

            $this->bulkPlaylistId = $response->json()['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
            
            // Trigger first page processing
            $this->processBulkPage();
        } catch (\Exception $e) {
            $this->bulkError = $e->getMessage();
            $this->isBulkImporting = false;
        }
    }

    private function runLiteImport(): void
    {
        $channelId = $this->bulkChannelInput;

        // If it starts with @, we can't easily get the ID without an API key or scraping
        if (str_starts_with($channelId, '@')) {
            $this->bulkError = 'Lite Mode (No API Key) requires a Channel ID (starting with UC...). Handles (@) are only supported with an API key.';
            $this->isBulkImporting = false;
            return;
        }

        try {
            $rssUrl = "https://www.youtube.com/feeds/videos.xml?channel_id={$channelId}";
            $response = Http::get($rssUrl);

            if (!$response->successful()) {
                throw new \Exception('Could not fetch RSS feed. Ensure the Channel ID is correct.');
            }

            $xml = new \SimpleXMLElement($response->body());
            $xml->registerXPathNamespace('yt', 'http://www.youtube.com/xml/schemas/2015');
            $xml->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');

            $entries = $xml->entry;
            if (!$entries) {
                throw new \Exception('No videos found in the RSS feed.');
            }

            foreach ($entries as $entry) {
                $videoId = (string) $entry->children('yt', true)->videoId;
                $url = "https://www.youtube.com/watch?v={$videoId}";
                
                $media = $entry->children('media', true)->group;
                $thumbnail = (string) $media->thumbnail->attributes()->url;
                $description = (string) $media->description;

                SocialPost::updateOrCreate(
                    ['url' => $url],
                    [
                        'platform' => 'youtube',
                        'title' => (string) $entry->title,
                        'description' => $description,
                        'thumbnail_url' => $thumbnail,
                        'author_name' => (string) $entry->author->name,
                        'status' => 'show',
                        'embed_html' => '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . $videoId . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="width:100%;aspect-ratio:16/9;border-radius:6px;"></iframe>',
                    ]
                );
                $this->bulkImportCount++;
            }

            $this->isBulkImporting = false;
            session()->flash('message', "Lite Import complete. Fetched {$this->bulkImportCount} latest videos via RSS.");
        } catch (\Exception $e) {
            $this->bulkError = "Lite Import Error: " . $e->getMessage();
            $this->isBulkImporting = false;
        }
    }

    public function processBulkPage(): void
    {
        if (!$this->isBulkImporting || !$this->bulkPlaylistId) return;

        try {
            $response = Http::get('https://www.googleapis.com/youtube/v3/playlistItems', [
                'key' => config('services.youtube.api_key'),
                'playlistId' => $this->bulkPlaylistId,
                'part' => 'snippet',
                'maxResults' => 50,
                'pageToken' => $this->bulkNextPageToken,
            ]);

            if (!$response->successful()) {
                throw new \Exception('Failed to fetch playlist items.');
            }

            $data = $response->json();
            foreach ($data['items'] as $item) {
                $videoId = $item['snippet']['resourceId']['videoId'];
                $url = "https://www.youtube.com/watch?v={$videoId}";
                
                SocialPost::updateOrCreate(
                    ['url' => $url],
                    [
                        'platform' => 'youtube',
                        'title' => $item['snippet']['title'],
                        'description' => $item['snippet']['description'] ?? '',
                        'thumbnail_url' => $item['snippet']['thumbnails']['high']['url'] ?? $item['snippet']['thumbnails']['default']['url'] ?? '',
                        'author_name' => $item['snippet']['channelTitle'],
                        'status' => 'show',
                        'embed_html' => '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . $videoId . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="width:100%;aspect-ratio:16/9;border-radius:6px;"></iframe>',
                    ]
                );
                $this->bulkImportCount++;
            }

            $this->bulkNextPageToken = $data['nextPageToken'] ?? null;

            if (!$this->bulkNextPageToken) {
                $this->isBulkImporting = false;
                session()->flash('message', "Bulk import complete. Total processed: {$this->bulkImportCount}");
            }
        } catch (\Exception $e) {
            $this->bulkError = "Import error: " . $e->getMessage();
            $this->isBulkImporting = false;
        }
    }
};
?>

<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

    <div class="flex border-b border-gray-200 mb-6">
        <button wire:click="setTab('single')" class="px-6 py-2 text-sm font-bold {{ $activeTab === 'single' ? 'border-b-2 border-[#99BC85] text-[#99BC85]' : 'text-gray-400' }}">Single Post</button>
        <button wire:click="setTab('bulk')" class="px-6 py-2 text-sm font-bold {{ $activeTab === 'bulk' ? 'border-b-2 border-[#99BC85] text-[#99BC85]' : 'text-gray-400' }}">Bulk YouTube Import</button>
    </div>

    {{-- ═══════════════════════════════════════════════════════════ --}}
    {{-- SCRAPER CARD (hidden while editing)                         --}}
    {{-- ═══════════════════════════════════════════════════════════ --}}
    @if(! $editingId)
    <div class="card p-6 mb-8">
        @if($activeTab === 'single')
            <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 items-center">
                        <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>

                        <label class="flex items-center gap-2 cursor-pointer ml-auto">
                            <input type="checkbox" wire:model="storeLocally" class="rounded border-gray-300 text-[#99BC85] focus:ring-[#99BC85]">
                            <span class="text-xs font-semibold text-gray-500">Store thumbnail locally</span>
                        </label>
                    </div>
                </div>
            @endif
        @else
            {{-- Bulk YouTube Import --}}
            <div class="space-y-4">
                <div class="flex items-center justify-between">
                    <div>
                        <h2 class="text-sm font-bold uppercase tracking-widest text-gray-400">Bulk YouTube Channel Import</h2>
                        <p class="text-xs text-gray-500 mt-1">Import all videos from a specific channel automatically.</p>
                    </div>
                    @if($isBulkImporting)
                        <div class="flex items-center gap-3 bg-blue-50 text-blue-700 px-4 py-2 rounded-full border border-blue-100">
                            <i class="fa-solid fa-circle-notch fa-spin text-sm"></i>
                            <span class="text-xs font-bold">Importing: {{ $bulkImportCount }} processed...</span>
                        </div>
                    @endif
                </div>

                @if(! $isBulkImporting)
                    <div class="flex gap-3 mt-4">
                        <div class="flex-1 relative">
                            <i class="fa-brands fa-youtube absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                            <input type="text" wire:model="bulkChannelInput"
                                placeholder="Channel ID (UC...) or Handle (@username)"
                                class="input-field w-full pl-10 text-sm"
                                wire:keydown.enter="startBulkImport">
                        </div>
                        <button wire:click="startBulkImport" wire:loading.attr="disabled"
                            class="px-6 py-2 text-sm font-bold text-white rounded-md transition-colors"
                            style="background-color:#99BC85;">
                            Start Import
                        </button>
                    </div>
                    <p class="text-[10px] text-gray-400 mt-2">
                        <i class="fa-solid fa-circle-info mr-1"></i> 
                        Requires a <strong>YouTube API Key</strong> in your .env file. Full history will be imported 50 videos at a time.
                    </p>
                @else
                    <div class="mt-6 py-8 border-2 border-dashed border-gray-100 rounded-xl flex flex-col items-center justify-center text-center">
                        <div class="w-16 h-16 bg-blue-50 text-blue-500 rounded-full flex items-center justify-center mb-4 animate-pulse">
                            <i class="fa-brands fa-youtube text-3xl"></i>
                        </div>
                        <h3 class="text-sm font-bold text-gray-700">Importing Content</h3>
                        <p class="text-xs text-gray-400 mt-1 max-w-xs">Please keep this page open. We are fetching videos from the channel and saving them to your feed.</p>
                        
                        <div class="mt-6 w-full max-w-sm bg-gray-100 rounded-full h-1.5 overflow-hidden">
                            <div class="bg-blue-500 h-full transition-all duration-500" style="width: 100%; opacity: 0.5;"></div>
                        </div>
                    </div>

                    {{-- Auto-trigger next page --}}
                    <div wire:poll.1s="processBulkPage"></div>
                @endif

                @if($bulkError)
                    <div class="mt-4 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>{{ $bulkError }}</span>
                    </div>
                @endif
            </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>
            <div class="flex items-center gap-4">
                <button wire:click="refetch" wire:loading.attr="disabled" class="text-xs font-bold text-[#99BC85] hover:underline flex items-center gap-2">
                    <i class="fa-solid fa-sync" wire:loading.class="fa-spin" wire:target="refetch"></i>
                    <span wire:loading.remove wire:target="refetch">Refetch Data</span>
                    <span wire:loading wire:target="refetch">Refetching...</span>
                </button>
                <button wire:click="cancelEdit" class="text-gray-400 hover:text-gray-700 text-sm">
                    <i class="fa-solid fa-xmark"></i> Cancel
                </button>
            </div>
        </div>

        @if (session()->has('edit_message'))
            <div class="bg-green-50 border border-green-200 text-green-700 px-4 py-2 rounded mb-4 text-xs">{{ session('edit_message') }}</div>
        @endif
        @if (session()->has('edit_error'))
            <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-2 rounded mb-4 text-xs">{{ session('edit_error') }}</div>
        @endif

        <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">
                <div class="flex items-center justify-between mb-4">
                    <label class="block text-[11px] font-bold text-gray-500 uppercase tracking-wider">Thumbnail</label>
                    <label class="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" wire:model="storeLocally" class="rounded border-gray-300 text-[#99BC85] focus:ring-[#99BC85]">
                        <span class="text-xs font-semibold text-gray-500">Download & store locally</span>
                    </label>
                </div>

                <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 flex-col md:flex-row md:items-center justify-between gap-4">
            <h2 class="text-sm font-bold text-gray-700">Saved Posts</h2>
            
            <div class="flex flex-wrap items-center gap-3">
                <div class="relative">
                    <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs"></i>
                    <input type="text" wire:model.live.debounce.300ms="search" placeholder="Search posts..." 
                        class="pl-9 pr-4 py-1.5 text-xs border border-gray-200 rounded-md focus:ring-1 focus:ring-[#99BC85] focus:border-[#99BC85] w-48">
                </div>

                <select wire:model.live="platformFilter" class="text-xs border border-gray-200 rounded-md py-1.5 pl-2 pr-8 focus:ring-1 focus:ring-[#99BC85] focus:border-[#99BC85]">
                    <option value="">All Platforms</option>
                    <option value="youtube">YouTube</option>
                    <option value="instagram">Instagram</option>
                    <option value="facebook">Facebook</option>
                </select>

                <select wire:model.live="statusFilter" class="text-xs border border-gray-200 rounded-md py-1.5 pl-2 pr-8 focus:ring-1 focus:ring-[#99BC85] focus:border-[#99BC85]">
                    <option value="">All Status</option>
                    <option value="show">Visible</option>
                    <option value="hide">Hidden</option>
                </select>

                <span class="text-[10px] font-bold text-gray-400 uppercase tracking-widest ml-2">{{ $posts->total() }} total</span>
            </div>
        </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 found matching your criteria.</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        <div class="px-6 py-4 border-t border-gray-100">
            {{ $posts->links() }}
        </div>
    </div>

</div>
