<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\Product;
use App\Models\ProductGroup;
use App\Models\Tld;
use App\PageBuilder\ComponentRegistry;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Vite;

class PageBuilderBlocksController extends Controller
{
    public function __construct()
    {
        // canvasCss public — canvas iframe auth header gönderemez (cross-origin css link)
        $this->middleware(['auth:sanctum', 'permission:manage pages'])->except('canvasCss');
    }

    /**
     * DomainSearchComponent trait panel'inde TLD picker'ı için aktif TLD listesi.
     */
    public function activeTlds(): JsonResponse
    {
        $tlds = Tld::query()
            ->where('status', 'active')
            ->orderBy('order')
            ->get(['tld'])
            ->pluck('tld')
            ->values();

        return response()->json(['data' => $tlds]);
    }

    public function index(ComponentRegistry $registry): JsonResponse
    {
        $byCategory = $registry->byCategory();
        $output = [];
        foreach ($byCategory as $category => $components) {
            $output[$category] = collect($components)
                ->map(fn ($c) => $c->jsBlockDefinition())
                ->all();
        }

        return response()->json(['categories' => $output]);
    }

    /**
     * Link picker: posts (announcement / blog / kb) için arama.
     * Status=published, locale awareness, q ile başlık/slug filtreleme.
     */
    public function searchPosts(Request $request): JsonResponse
    {
        $q = trim((string) $request->query('q', ''));
        $locale = $request->query('locale');

        $query = Post::query()->where('status', 'published');
        if ($locale) $query->where('locale', $locale);
        if ($q !== '') {
            $query->where(fn ($w) => $w->where('title', 'like', "%{$q}%")->orWhere('slug', 'like', "%{$q}%"));
        }

        $posts = $query->limit(20)->get(['id', 'title', 'slug', 'locale', 'type']);

        return response()->json([
            'data' => $posts->map(fn ($p) => [
                'id'        => $p->id,
                'title'     => $p->title,
                'sub_label' => "{$p->type} • /{$p->slug}",
                'url'       => $this->postUrl($p),
                'locale'    => $p->locale,
            ]),
        ]);
    }

    /**
     * Link picker: ürün araması.
     */
    public function searchProducts(Request $request): JsonResponse
    {
        $q = trim((string) $request->query('q', ''));

        $query = Product::query();
        if ($q !== '') {
            $query->where(fn ($w) => $w->where('name', 'like', "%{$q}%")->orWhere('slug', 'like', "%{$q}%"));
        }

        $products = $query->limit(20)->get(['id', 'name', 'slug']);

        return response()->json([
            'data' => $products->map(fn ($p) => [
                'id'        => $p->id,
                'title'     => $p->name,
                'sub_label' => "/products/{$p->slug}",
                'url'       => '/products/' . $p->slug,
            ]),
        ]);
    }

    /**
     * Link picker: ürün grubu araması.
     */
    public function searchProductGroups(Request $request): JsonResponse
    {
        $q = trim((string) $request->query('q', ''));

        $query = ProductGroup::query();
        if ($q !== '') {
            $query->where(fn ($w) => $w->where('name', 'like', "%{$q}%")->orWhere('slug', 'like', "%{$q}%"));
        }

        $groups = $query->limit(20)->get(['id', 'name', 'slug']);

        return response()->json([
            'data' => $groups->map(fn ($g) => [
                'id'        => $g->id,
                'title'     => $g->name,
                'sub_label' => "/{$g->slug}",
                'url'       => '/' . $g->slug,
            ]),
        ]);
    }

    /**
     * Canvas iframe için tam store CSS'ini serve et — gerçek frontend ile birebir
     * görsel eşleşmesi için. Bootstrap + Poppins + Font Awesome + tüm theme tokens.
     */
    public function canvasCss(): Response
    {
        $css = '';
        $files = [
            base_path('resources/css/store/app.css'),
            base_path('resources/css/store/tables.css'),
        ];
        foreach ($files as $f) {
            if (file_exists($f)) {
                $content = file_get_contents($f);
                // Tüm @import'ları kaldır — Bootstrap/FA/Poppins zaten canvasStyles array'inde CDN olarak yüklü
                $content = preg_replace('/@import\s+(?:url\([^)]*\)|[\'"][^\'"]+[\'"])\s*;?/', '', $content);
                $css .= "/* === " . basename($f) . " === */\n" . $content . "\n\n";
            }
        }

        // Canvas-spesifik ek: page-builder-body wrapper benzeri light theme zorla
        // + padding/typography token'ları (preview layout'taki kurallarla birebir aynı)
        $css .= <<<CSS
/* === page-builder canvas overrides === */
html, body { background: var(--bs-body-bg, #fff); color: var(--bs-body-color, #1e293b); }
body { font-family: 'Poppins', system-ui, -apple-system, 'Segoe UI', sans-serif !important; padding: 0; margin: 0; font-size: 1rem; }

.page-builder-body .py-sm { padding-top: 2rem !important; padding-bottom: 2rem !important; }
.page-builder-body .py-md { padding-top: 3rem !important; padding-bottom: 3rem !important; }
.page-builder-body .py-lg { padding-top: 5rem !important; padding-bottom: 5rem !important; }
.page-builder-body .py-xl { padding-top: 7rem !important; padding-bottom: 7rem !important; }

.page-builder-body .display-4 { font-size: 3.5rem; line-height: 1.2; font-weight: 700; }
.page-builder-body .display-5 { font-size: 3rem;   line-height: 1.2; font-weight: 700; }
.page-builder-body .lead      { font-size: 1.25rem; line-height: 1.6; font-weight: 300; }
.page-builder-body h2         { font-size: 2.25rem; line-height: 1.25; font-weight: 600; }
.page-builder-body h3         { font-size: 1.75rem; line-height: 1.3; font-weight: 600; }
.page-builder-body h4         { font-size: 1.5rem;  line-height: 1.3; font-weight: 600; }
.page-builder-body h5         { font-size: 1.25rem; line-height: 1.4; font-weight: 600; }
.page-builder-body p          { font-size: 1rem;    line-height: 1.7; }
.page-builder-body section    { display: block; }
CSS;

        return response($css, 200, [
            'Content-Type' => 'text/css; charset=utf-8',
            'Cache-Control' => 'public, max-age=300',
        ]);
    }

    private function postUrl(Post $post): string
    {
        return match ($post->type) {
            'announcement' => '/announcements/' . $post->slug,
            'blog'         => '/blog/' . $post->slug,
            'kb'           => '/knowledgebase/' . $post->slug,
            default        => '/' . $post->slug,
        };
    }
}
