<?php
/**
 * Block Registry Admin Controller
 * Handles CRUD operations for block management
 */
namespace Mtc\Modules\BlockRegistry\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Mtc\Modules\BlockRegistry\Models\BlockRegistry;
use Mtc\Modules\BlockRegistry\Models\BlockRegistryCategory;
use Mtc\Modules\BlockRegistry\Models\BlockRegistryField;
use Mtc\Modules\BlockRegistry\Models\EntityBlock;
use Mtc\Modules\BlockRegistry\Services\BlockRegistryService;
use Mtc\Modules\BlockRegistry\Services\EntityBlockService;
use Mtc\Modules\BlockRegistry\Services\TemplateBlockService;
use Mtc\Modules\BlockRegistry\Services\ImageProcessingService;
use App\Services\ComponentScannerService;

class BlockRegistryController extends \App\Http\Controllers\Controller
{
    protected BlockRegistryService $registryService;
    protected TemplateBlockService $templateService;
    protected ComponentScannerService $componentScanner;

    public function __construct(
        BlockRegistryService $registryService,
        TemplateBlockService $templateService,
        ComponentScannerService $componentScanner
    ) {
        $this->registryService = $registryService;
        $this->templateService = $templateService;
        $this->componentScanner = $componentScanner;
    }

    /**
     * List all blocks
     */
    public function index()
    {
        $data = $this->registryService->getAllBlocks();
        $messages = $this->getFormMessages();

        return template('admin/block_registry/index.twig', [
            'title' => 'Block Registry',
            'blocks' => $data['blocks'],
            'categories' => $data['categories'],
            'messages' => $messages,
        ]);
    }

    /**
     * Create new block form
     */
    public function create()
    {
        $categories = BlockRegistryCategory::orderBy('name')->get();
        $templates = $this->templateService->getAllAvailableTemplates();
        $fieldTypes = BlockRegistryField::FIELD_TYPES;
        $subFieldTypes = BlockRegistryField::getSubFieldTypes();
        $componentTemplates = $this->getComponentTemplates();

        return template('admin/block_registry/edit.twig', [
            'title' => 'Create Block',
            'block' => null,
            'categories' => $categories,
            'templates' => $templates,
            'componentTemplates' => $componentTemplates,
            'fieldTypes' => $fieldTypes,
            'subFieldTypes' => $subFieldTypes,
            'messages' => [],
        ]);
    }

    /**
     * Edit existing block
     */
    public function edit(int $id)
    {
        $block = BlockRegistry::with(['fields.subFields', 'templateAssignments', 'category'])->findOrFail($id);
        $categories = BlockRegistryCategory::orderBy('name')->get();
        $templates = $this->templateService->getAllAvailableTemplates();
        $fieldTypes = BlockRegistryField::FIELD_TYPES;
        $subFieldTypes = BlockRegistryField::getSubFieldTypes();
        $componentTemplates = $this->getComponentTemplates();
        $stats = $this->registryService->getBlockStatistics($block);
        $messages = $this->getFormMessages();

        return template('admin/block_registry/edit.twig', [
            'title' => 'Edit Block: ' . $block->name,
            'block' => $block,
            'categories' => $categories,
            'templates' => $templates,
            'componentTemplates' => $componentTemplates,
            'fieldTypes' => $fieldTypes,
            'subFieldTypes' => $subFieldTypes,
            'stats' => $stats,
            'messages' => $messages,
        ]);
    }

    /**
     * Store new block
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:block_registry,slug',
            'description' => 'nullable|string',
            'category_id' => 'nullable|integer|exists:block_registry_categories,id',
            'icon' => 'nullable|string|max:100',
            'template' => 'nullable|string|max:255',
            'preview_image' => 'nullable|string|max:255',
            'is_active' => 'boolean',
        ]);

        // Parse fields from request
        $fields = $this->parseFieldsFromRequest($request);

        try {
            $block = $this->registryService->createBlock([
                'name' => $validated['name'],
                'slug' => $validated['slug'] ?? null,
                'description' => $validated['description'] ?? null,
                'category_id' => $validated['category_id'] ?? null,
                'icon' => $validated['icon'] ?? 'fa-cube',
                'template' => $validated['template'] ?? null,
                'preview_image' => $validated['preview_image'] ?? null,
                'is_active' => $validated['is_active'] ?? true,
                'fields' => $fields,
                'user_id' => $this->getCurrentUserId(),
            ]);

            // Handle template assignments
            $this->handleTemplateAssignments($block, $request);

            $this->flashSuccess('Block created successfully.');
            return redirect()->route('admin.blocks.edit', $block->id);

        } catch (\Exception $e) {
            $this->flashError($e->getMessage());
            return back()->withInput();
        }
    }

    /**
     * Update existing block
     */
    public function update(Request $request, int $id)
    {
        $block = BlockRegistry::findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:block_registry,slug,' . $id,
            'description' => 'nullable|string',
            'category_id' => 'nullable|integer|exists:block_registry_categories,id',
            'icon' => 'nullable|string|max:100',
            'template' => 'nullable|string|max:255',
            'preview_image' => 'nullable|string|max:255',
            'is_active' => 'boolean',
        ]);

        // Parse fields from request
        $fields = $this->parseFieldsFromRequest($request);

        try {
            $block = $this->registryService->updateBlock($block, [
                'name' => $validated['name'],
                'slug' => $validated['slug'] ?? $block->slug,
                'description' => $validated['description'] ?? null,
                'category_id' => $validated['category_id'] ?? null,
                'icon' => $validated['icon'] ?? $block->icon,
                'template' => $validated['template'] ?? null,
                'preview_image' => $validated['preview_image'] ?? null,
                'is_active' => $validated['is_active'] ?? true,
                'fields' => $fields,
            ], $this->getCurrentUserId());

            // Handle template assignments
            $this->handleTemplateAssignments($block, $request);

            $this->flashSuccess('Block updated successfully.');
            return redirect()->route('admin.blocks.edit', $block->id);

        } catch (\Exception $e) {
            $this->flashError($e->getMessage());
            return back()->withInput();
        }
    }

    /**
     * Delete block
     */
    public function destroy(int $id, Request $request)
    {
        $block = BlockRegistry::findOrFail($id);

        try {
            $this->registryService->deleteBlock($block);

            if ($request->ajax() || $request->wantsJson()) {
                return response()->json(['success' => true]);
            }

            $this->flashSuccess('Block deleted successfully.');
        } catch (\Exception $e) {
            if ($request->ajax() || $request->wantsJson()) {
                return response()->json(['success' => false, 'error' => $e->getMessage()], 422);
            }

            $this->flashError($e->getMessage());
        }

        return redirect()->route('admin.blocks.index');
    }

    /**
     * Duplicate block
     */
    public function duplicate(int $id)
    {
        $block = BlockRegistry::findOrFail($id);

        try {
            $newBlock = $this->registryService->duplicateBlock($block);
            $this->flashSuccess('Block duplicated successfully.');
            return redirect()->route('admin.blocks.edit', $newBlock->id);
        } catch (\Exception $e) {
            $this->flashError($e->getMessage());
            return back();
        }
    }

    /**
     * Edit entity block data
     */
    public function editData(int $id)
    {
        $entityBlock = EntityBlock::with(['block', 'block.fields.subFields', 'block.category', 'sourceBlock'])->findOrFail($id);

        // If this is a global reference, redirect to edit the source global block
        if ($entityBlock->isGlobalReference() && $entityBlock->sourceBlock && $entityBlock->sourceBlock->isGlobalBlock()) {
            return redirect()->route('admin.blocks.data.edit', $entityBlock->source_block_id);
        }

        $fieldTypes = BlockRegistryField::FIELD_TYPES;
        $messages = $this->getFormMessages();

        // Build back URL based on entity type
        $backUrl = $this->getBackUrlForEntity($entityBlock);

        // Pre-parse field data for the template
        $data = $entityBlock->data ?? [];
        $parsedData = [];
        foreach ($entityBlock->block->fields as $field) {
            $fieldName = $field->name;
            $value = $data[$fieldName] ?? '';

            // Parse JSON image data into url/alt/crop components
            if ($field->type === 'image' && is_string($value) && str_starts_with($value, '{')) {
                $imageData = json_decode($value, true);
                if (is_array($imageData)) {
                    $parsedData[$fieldName] = [
                        'url' => $imageData['url'] ?? '',
                        'alt' => $imageData['alt'] ?? '',
                        'crop' => $imageData['crop'] ?? [],
                        'processed' => $imageData['processed'] ?? [],
                        'srcset' => $imageData['srcset'] ?? '',
                    ];
                    continue;
                }
            }

            // Parse repeater JSON data
            if ($field->type === 'repeater' && is_string($value) && str_starts_with($value, '[')) {
                $repeaterData = json_decode($value, true);
                if (is_array($repeaterData)) {
                    $parsedData[$fieldName] = $repeaterData;
                    continue;
                }
            }

            // For non-image fields or legacy string values
            $parsedData[$fieldName] = $value;
        }

        $templateVars = [
            'title' => 'Edit Block Data: ' . $entityBlock->block->name,
            'entityBlock' => $entityBlock,
            'block' => $entityBlock->block,
            'fields' => $entityBlock->block->fields,
            'data' => $parsedData,
            'fieldTypes' => $fieldTypes,
            'backUrl' => $backUrl,
            'messages' => $messages,
        ];

        // Add global block context if editing a global block
        if ($entityBlock->isGlobalBlock()) {
            $templateVars['isGlobal'] = true;
            $templateVars['referenceCount'] = $entityBlock->references()->count();
        }

        return template('admin/block_registry/edit_data.twig', $templateVars);
    }

    /**
     * Update entity block data
     */
    public function updateData(Request $request, int $id)
    {
        $entityBlock = EntityBlock::with(['block', 'block.fields.subFields'])->findOrFail($id);
        $imageProcessor = app(ImageProcessingService::class);

        $cropWarnings = [];

        try {
            // Build data array from form fields
            $data = [];
            foreach ($entityBlock->block->fields as $field) {
                $fieldName = $field->name;
                // PHP converts spaces in form field names to underscores
                // So we need to check for both versions
                $formKeyOriginal = "field_{$fieldName}";
                $formKeySanitized = "field_" . str_replace(' ', '_', $fieldName);

                $value = $request->input($formKeyOriginal) ?? $request->input($formKeySanitized);

                // Handle different field types
                if ($field->type === 'checkbox') {
                    // Check both possible form keys for checkbox
                    $value = ($request->boolean($formKeyOriginal) || $request->boolean($formKeySanitized)) ? '1' : '0';
                } elseif ($field->type === 'image') {
                    // Process image with crop and generate srcset if crop is enabled
                    if (is_array($value) && !empty($value['url'])) {
                        // Check if this field has crop settings enabled
                        if ($imageProcessor->fieldHasCropEnabled($field)) {
                            $value = $imageProcessor->processImageField($entityBlock, $field, $value);
                            if (!empty($value['crop_rejected'])) {
                                $cropWarnings[] = ($field->label ?? $field->name) . ': ' . $value['crop_rejected_reason'];
                            }
                        }
                        $value = json_encode($value);
                    } elseif (is_array($value)) {
                        $value = json_encode($value);
                    }
                } elseif ($field->type === 'repeater') {
                    // Handle repeater data - comes in as nested array
                    if (is_array($value)) {
                        // Process images within repeater sub-fields
                        foreach ($field->subFields as $subField) {
                            if ($subField->type === 'image' && $imageProcessor->fieldHasCropEnabled($subField)) {
                                foreach ($value as $rowIndex => &$row) {
                                    if (isset($row[$subField->name]) && is_array($row[$subField->name]) && !empty($row[$subField->name]['url'])) {
                                        $row[$subField->name] = $imageProcessor->processImageField($entityBlock, $subField, $row[$subField->name], $rowIndex);
                                    }
                                }
                                unset($row); // break reference
                            }
                        }
                        // Re-index the array to ensure sequential keys (in case rows were deleted)
                        $value = array_values($value);
                        $value = json_encode($value);
                    } else {
                        $value = '[]';
                    }
                } elseif (is_array($value)) {
                    $value = json_encode($value);
                }

                $data[$fieldName] = $value ?? '';
            }

            $entityBlock->data = $data;

            // Handle status field
            $status = $request->input('status', $entityBlock->status ?? EntityBlock::STATUS_DRAFT);
            $entityBlock->status = $status;

            $entityBlock->save();

            $statusMessage = $entityBlock->isPublished() ? 'Block published.' : 'Block saved as draft.';
            if (!empty($cropWarnings)) {
                $statusMessage .= ' Warning: ' . implode(' ', $cropWarnings);
                $this->flashWarning($statusMessage);
            } else {
                $this->flashSuccess($statusMessage);
            }

            // Return to edit page
            return redirect()->route('admin.blocks.data.edit', $id);

        } catch (\Exception $e) {
            $this->flashError($e->getMessage());
            return back()->withInput();
        }
    }

    /**
     * Delete entity block
     */
    public function destroyData(int $id)
    {
        $entityBlock = EntityBlock::findOrFail($id);
        $backUrl = $this->getBackUrlForEntity($entityBlock);
        $imageProcessor = app(ImageProcessingService::class);

        try {
            // Clean up processed images before deleting
            $imageProcessor->deleteProcessedImages($entityBlock->id);

            $entityBlock->delete();
            $this->flashSuccess('Block removed successfully.');
        } catch (\Exception $e) {
            $this->flashError($e->getMessage());
        }

        return redirect($backUrl);
    }

    /**
     * Preview entity block with full frontend styles
     */
    public function previewData(int $id)
    {
        $entityBlock = EntityBlock::with(['block', 'block.fields'])->findOrFail($id);

        if (!$entityBlock->block->hasTemplate()) {
            return response('No template linked to this block.', 404);
        }

        try {
            // Render the block using EntityBlockService
            $entityBlockService = app(\Mtc\Modules\BlockRegistry\Services\EntityBlockService::class);
            $blockOutput = $entityBlockService->renderBlock($entityBlock);

            if ($blockOutput === null) {
                $blockOutput = '<div class="preview-error">Failed to render block preview.</div>';
            }

            // Generate full HTML page with frontend styles (like ComponentRendererService)
            $html = $this->renderBlockPreviewHtml($entityBlock, $blockOutput);

            return response($html, 200, [
                'Content-Type' => 'text/html; charset=UTF-8',
            ]);

        } catch (\Exception $e) {
            \Log::error('Block preview error: ' . $e->getMessage());
            return response('Preview error: ' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'), 500);
        }
    }

    /**
     * Preview a block definition (uses an existing instance with real data if available)
     */
    public function previewBlockDefinition(int $id)
    {
        $block = BlockRegistry::with('fields')->findOrFail($id);

        if (!$block->hasTemplate()) {
            return response('No template linked to this block.', 404);
        }

        try {
            // Try to find an existing entity block with real content for a better preview
            $entityBlock = EntityBlock::where('block_id', $block->id)
                ->whereNotNull('data')
                ->with(['block', 'block.fields'])
                ->first();

            if ($entityBlock) {
                $entityBlock->setRelation('block', $block);
            } else {
                // Fall back to empty defaults if no instances exist
                $entityBlock = new EntityBlock([
                    'block_id' => $block->id,
                    'entity_type' => 'preview',
                    'entity_id' => 0,
                    'data' => EntityBlock::createInitialData($block),
                ]);
                $entityBlock->setRelation('block', $block);
            }

            $entityBlockService = app(EntityBlockService::class);
            $blockOutput = $entityBlockService->renderBlock($entityBlock);

            if ($blockOutput === null) {
                $blockOutput = '<div class="preview-error">Failed to render block preview.</div>';
            }

            $html = $this->renderPreviewHtml('Block Preview: ' . $block->name, $blockOutput);

            return response($html, 200, [
                'Content-Type' => 'text/html; charset=UTF-8',
            ]);
        } catch (\Exception $e) {
            \Log::error('Block definition preview error: ' . $e->getMessage());
            return response('Preview error: ' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'), 500);
        }
    }

    /**
     * AJAX: Toggle entity block status (draft/published)
     */
    public function ajaxToggleStatus(Request $request)
    {
        if ($error = $this->requireAjaxRequest()) {
            return $error;
        }

        $id = (int) $request->input('id');
        $status = $request->input('status');

        if (!$id) {
            return response()->json(['error' => 'id is required'], 400);
        }

        if (!in_array($status, [EntityBlock::STATUS_DRAFT, EntityBlock::STATUS_PUBLISHED])) {
            return response()->json(['error' => 'Invalid status'], 400);
        }

        try {
            $entityBlock = EntityBlock::findOrFail($id);
            $entityBlock->status = $status;
            $entityBlock->save();

            return response()->json([
                'success' => true,
                'status' => $entityBlock->status,
                'message' => $entityBlock->isPublished() ? 'Block published.' : 'Block set to draft.',
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Failed to update status',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * AJAX: Toggle block definition active status
     */
    public function ajaxToggleActive(Request $request)
    {
        if ($error = $this->requireAjaxRequest()) {
            return $error;
        }

        $id = (int) $request->input('id');
        $isActive = (bool) $request->input('is_active');

        if (!$id) {
            return response()->json(['error' => 'id is required'], 400);
        }

        try {
            $block = BlockRegistry::findOrFail($id);
            $block->is_active = $isActive;
            $block->save();

            return response()->json([
                'success' => true,
                'is_active' => $block->is_active,
                'message' => $block->is_active ? 'Block activated.' : 'Block deactivated.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Failed to update status',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * AJAX: Reorder entity blocks
     */
    public function ajaxReorderBlocks(Request $request)
    {
        if ($error = $this->requireAjaxRequest()) {
            return $error;
        }

        $input = $request->json()->all();

        if (empty($input['blocks']) || !is_array($input['blocks'])) {
            return response()->json(['success' => false, 'error' => 'blocks array is required'], 400);
        }

        try {
            $blocks = collect($input['blocks'])->filter(fn($item) => isset($item['id'], $item['order']));

            if ($blocks->isEmpty()) {
                return response()->json(['success' => true, 'message' => 'No blocks to update', 'updated' => 0]);
            }

            $ids = $blocks->pluck('id')->map(fn($id) => (int) $id);
            $cases = $blocks->map(fn($item) => "WHEN id = " . (int) $item['id'] . " THEN " . (int) $item['order'])->implode(' ');

            EntityBlock::whereIn('id', $ids)->update([
                'order' => DB::raw("CASE {$cases} END"),
            ]);

            return response()->json([
                'success' => true,
                'message' => "Updated order for {$ids->count()} block(s)",
                'updated' => $ids->count(),
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Failed to update order',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Render full HTML preview page with frontend styles for a single block
     */
    protected function renderBlockPreviewHtml(EntityBlock $entityBlock, string $blockOutput): string
    {
        $blockName = $entityBlock->block->name;
        return $this->renderPreviewHtml('Block Preview: ' . $blockName, $blockOutput);
    }

    /**
     * Get back URL based on entity type
     */
    protected function getBackUrlForEntity(EntityBlock $entityBlock): string
    {
        switch ($entityBlock->entity_type) {
            case 'page':
                return '/cms/admin/content_manager/?page=' . $entityBlock->entity_id;
            case 'item':
                return '/modules/BlockRegistry/admin/products/blocks.php?id=' . $entityBlock->entity_id;
            case 'category':
                return '/modules/BlockRegistry/admin/categories/blocks.php?id=' . $entityBlock->entity_id;
            case 'global':
                return '/admin/blocks/global';
            default:
                return '/admin/blocks';
        }
    }

    /**
     * List all global blocks
     */
    public function globalIndex()
    {
        $entityBlockService = app(EntityBlockService::class);
        $globalBlocks = $entityBlockService->getGlobalBlocks();
        $messages = $this->getFormMessages();

        return template('admin/block_registry/global_index.twig', [
            'title' => 'Global Blocks',
            'globalBlocks' => $globalBlocks,
            'messages' => $messages,
        ]);
    }

    /**
     * Create global block form
     */
    public function globalCreate()
    {
        $blocks = BlockRegistry::where('is_active', true)
            ->with('category')
            ->orderBy('name')
            ->get();
        $categories = BlockRegistryCategory::orderBy('name')->get();

        return template('admin/block_registry/global_create.twig', [
            'title' => 'Create Global Block',
            'blocks' => $blocks,
            'categories' => $categories,
        ]);
    }

    /**
     * Store a new global block
     */
    public function globalStore(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'block_id' => 'required|integer|exists:block_registry,id',
        ]);

        try {
            $block = BlockRegistry::with('fields')->findOrFail($validated['block_id']);

            $entityBlock = EntityBlock::create([
                'entity_type' => 'global',
                'entity_id' => 0,
                'block_id' => $validated['block_id'],
                'name' => $validated['name'],
                'status' => EntityBlock::STATUS_DRAFT,
            ]);

            $this->flashSuccess('Global block created. Fill in the content below.');
            return redirect()->route('admin.blocks.data.edit', $entityBlock->id);

        } catch (\Exception $e) {
            $this->flashError($e->getMessage());
            return back()->withInput();
        }
    }

    /**
     * Delete a global block
     */
    public function globalDestroy(int $id)
    {
        $globalBlock = EntityBlock::global()->findOrFail($id);
        $referenceCount = $globalBlock->references()->count();

        try {
            // References will have source_block_id set to null by FK ON DELETE SET NULL
            $globalBlock->delete();

            $message = 'Global block deleted.';
            if ($referenceCount > 0) {
                $message .= " {$referenceCount} reference(s) have been unlinked.";
            }
            $this->flashSuccess($message);
        } catch (\Exception $e) {
            $this->flashError($e->getMessage());
        }

        return redirect()->route('admin.blocks.global.index');
    }

    /**
     * AJAX: Get available blocks for any entity type
     */
    public function ajaxGetAvailableBlocksForEntity(Request $request)
    {
        $entity_type = $request->input('entity_type');
        $entity_id = (int) $request->input('entity_id');

        if (!$entity_type || !$entity_id) {
            return response()->json(['error' => 'entity_type and entity_id are required'], 400);
        }
        if ($error = $this->validateEntityType($entity_type)) {
            return $error;
        }

        $search = trim($request->input('search', ''));
        $category_id = $request->input('category_id') ? (int) $request->input('category_id') : null;

        try {
            // Map entity type to virtual template name for whitelisting
            $templateMap = [
                'item' => 'shop_item',
                'category' => 'shop_category',
            ];
            $templateName = $templateMap[$entity_type] ?? null;

            // For pages, resolve the CMS template
            if ($entity_type === 'page' && $templateName === null) {
                try {
                    $page = \ContentManagerPanel::loadPage($entity_id, false);
                    $templateName = $page->template ?? null;
                } catch (\Exception $e) {
                    // Fall through to showing all blocks
                }
            }

            // Check for whitelisted blocks first
            $blocks = collect();
            if ($templateName) {
                $blocks = $this->templateService->getWhitelistedBlocks($templateName);
            }

            // If no blocks whitelisted, show all active blocks
            if ($blocks->isEmpty()) {
                $blocks = BlockRegistry::where('is_active', true)
                    ->with(['category', 'fields'])
                    ->orderBy('name')
                    ->get();
            }

            // Apply search filter
            if (!empty($search)) {
                $blocks = $blocks->filter(function ($block) use ($search) {
                    return stripos($block->name, $search) !== false ||
                           stripos($block->slug, $search) !== false ||
                           stripos($block->description, $search) !== false;
                });
            }

            // Apply category filter
            if ($category_id !== null) {
                $blocks = $blocks->filter(function ($block) use ($category_id) {
                    return $block->category_id === $category_id;
                });
            }

            $categories = BlockRegistryCategory::orderBy('order_index')->get();

            // Get published global blocks
            $globalBlocks = EntityBlock::global()
                ->where('status', EntityBlock::STATUS_PUBLISHED)
                ->with(['block', 'block.category'])
                ->ordered()
                ->get();

            return response()->json([
                'success' => true,
                'categories' => $categories->map(function ($cat) {
                    return [
                        'id' => $cat->id,
                        'name' => $cat->name,
                        'slug' => $cat->slug,
                        'icon' => $cat->icon,
                    ];
                })->values()->toArray(),
                'blocks' => $blocks->map(function ($block) {
                    return [
                        'id' => $block->id,
                        'name' => $block->name,
                        'slug' => $block->slug,
                        'description' => $block->description,
                        'icon' => $block->icon,
                        'category_id' => $block->category_id,
                        'category_name' => $block->category ? $block->category->name : null,
                        'field_count' => $block->fields ? $block->fields->count() : 0,
                        'has_template' => $block->hasTemplate(),
                    ];
                })->values()->toArray(),
                'global_blocks' => $globalBlocks->map(function ($gb) {
                    return [
                        'id' => $gb->id,
                        'name' => $gb->name,
                        'block_name' => $gb->block->name ?? 'Unknown',
                        'block_slug' => $gb->block->slug ?? '',
                        'icon' => $gb->block->icon ?? 'fa-cube',
                        'category_name' => $gb->block->category->name ?? null,
                        'category_id' => $gb->block->category_id ?? null,
                        'has_template' => $gb->block ? $gb->block->hasTemplate() : false,
                    ];
                })->values()->toArray(),
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Failed to load blocks',
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * AJAX: Add a block to any entity type (items, categories)
     */
    public function ajaxAddBlockToEntity(Request $request)
    {
        if ($error = $this->requireAjaxRequest()) {
            return $error;
        }

        $entity_type = $request->input('entity_type');
        $entity_id = (int) $request->input('entity_id');
        $block_id = (int) $request->input('block_id');

        if (!$entity_type || !$entity_id) {
            return response()->json(['error' => 'entity_type and entity_id are required'], 400);
        }
        if ($error = $this->validateEntityType($entity_type)) {
            return $error;
        }
        if (!$block_id) {
            return response()->json(['error' => 'block_id is required'], 400);
        }

        try {
            $block = BlockRegistry::with('fields')->find($block_id);
            if (!$block) {
                return response()->json(['error' => 'Block not found in registry'], 404);
            }

            $entityBlock = EntityBlock::create([
                'entity_type' => $entity_type,
                'entity_id' => $entity_id,
                'block_id' => $block_id,
                'status' => EntityBlock::STATUS_DRAFT,
            ]);

            return response()->json([
                'success' => true,
                'message' => "Block '{$block->name}' added successfully",
                'block' => [
                    'id' => $block->id,
                    'name' => $block->name,
                    'slug' => $block->slug,
                    'icon' => $block->icon,
                ],
                'entity_block_id' => $entityBlock->id,
                'edit_url' => '/admin/blocks/data/' . $entityBlock->id,
            ]);

        } catch (\Exception $e) {
            $response = ['error' => 'Failed to add block'];
            if (config('app.debug')) {
                $response['message'] = $e->getMessage();
            }
            return response()->json($response, 500);
        }
    }

    /**
     * AJAX: Add a global block reference to any entity type (items, categories)
     */
    public function ajaxAddGlobalBlockToEntity(Request $request)
    {
        if ($error = $this->requireAjaxRequest()) {
            return $error;
        }

        $entity_type = $request->input('entity_type');
        $entity_id = (int) $request->input('entity_id');
        $global_block_id = (int) $request->input('global_block_id');

        if (!$entity_type || !$entity_id) {
            return response()->json(['error' => 'entity_type and entity_id are required'], 400);
        }
        if ($error = $this->validateEntityType($entity_type)) {
            return $error;
        }
        if (!$global_block_id) {
            return response()->json(['error' => 'global_block_id is required'], 400);
        }

        try {
            $entityBlockService = app(EntityBlockService::class);
            $reference = $entityBlockService->addGlobalBlockReference($global_block_id, $entity_type, $entity_id);

            $globalBlock = EntityBlock::with('block')->find($global_block_id);
            $name = $globalBlock->name ?? 'Global block';

            return response()->json([
                'success' => true,
                'message' => "Global block '{$name}' added",
                'entity_block_id' => $reference->id,
            ]);

        } catch (\Exception $e) {
            $response = ['error' => 'Failed to add global block'];
            if (config('app.debug')) {
                $response['message'] = $e->getMessage();
            }
            return response()->json($response, 500);
        }
    }

    /**
     * AJAX: Return the entity blocks HTML section for any entity type
     */
    public function ajaxEntityBlocksHtmlForEntity(Request $request)
    {
        if ($error = $this->requireAjaxRequest()) {
            return $error;
        }

        $entity_type = $request->input('entity_type');
        $entity_id = (int) $request->input('entity_id');

        if (!$entity_type || !$entity_id) {
            return response('entity_type and entity_id are required', 400);
        }
        if (!in_array($entity_type, self::VALID_ENTITY_TYPES, true)) {
            return response('Invalid entity_type', 400);
        }

        if ($entity_type === 'page') {
            $page = \ContentManagerPanel::loadPage($entity_id, false);
            if (empty($page->id)) {
                return response('Page not found', 404);
            }
            $post = (array) $page;
            ob_start();
            include base_path('modules/BlockRegistry/admin/content_manager/templates/edit_page_entity_blocks.php');
            $html = ob_get_clean();
        } else {
            ob_start();
            include base_path('modules/BlockRegistry/admin/templates/entity_blocks.php');
            $html = ob_get_clean();
        }

        return response($html);
    }

    /**
     * Preview all blocks for any entity type
     */
    public function previewEntityBlocks(string $entityType, int $entityId)
    {
        $entityBlocks = EntityBlock::forEntity($entityType, $entityId)
            ->with(['block', 'block.fields'])
            ->ordered()
            ->get();

        if ($entityBlocks->isEmpty()) {
            return response('No blocks found for this ' . htmlspecialchars($entityType, ENT_QUOTES, 'UTF-8') . '.', 404);
        }

        $entityBlockService = app(\Mtc\Modules\BlockRegistry\Services\EntityBlockService::class);
        $blocksHtml = '';

        foreach ($entityBlocks as $entityBlock) {
            if (!$entityBlock->block || !$entityBlock->block->hasTemplate()) {
                continue;
            }

            try {
                $blockOutput = $entityBlockService->renderBlock($entityBlock);
            } catch (\Exception $e) {
                $blockOutput = null;
            }

            if ($blockOutput === null) {
                continue;
            }

            if ($entityBlock->isDraft()) {
                $blocksHtml .= '<div class="block-draft-overlay">'
                    . '<span class="block-draft-badge">DRAFT</span>'
                    . $blockOutput
                    . '</div>';
            } else {
                $blocksHtml .= $blockOutput;
            }
        }

        if (empty($blocksHtml)) {
            return response('No blocks with templates found.', 404);
        }

        $draftStyles = '        .block-draft-overlay {
            position: relative;
            opacity: 0.55;
            border: 2px dashed #6c757d;
        }
        .block-draft-badge {
            position: absolute;
            top: 8px;
            right: 12px;
            background: #6c757d;
            color: #fff;
            padding: 2px 10px;
            border-radius: 3px;
            font-size: 11px;
            font-family: -apple-system, BlinkMacSystemFont, sans-serif;
            z-index: 100;
            letter-spacing: 0.5px;
        }
';
        $title = ucfirst($entityType) . ' Blocks Preview (' . $entityType . ' ' . $entityId . ')';
        $html = $this->renderPreviewHtml($title, $blocksHtml, $draftStyles);

        return response($html, 200, [
            'Content-Type' => 'text/html; charset=UTF-8',
            'X-Robots-Tag' => 'noindex, nofollow',
        ]);
    }

    /**
     * Categories management
     */
    public function categories()
    {
        $categories = BlockRegistryCategory::withCount('blocks')->orderBy('order_index')->get();
        $messages = $this->getFormMessages();

        return template('admin/block_registry/categories.twig', [
            'title' => 'Block Categories',
            'categories' => $categories,
            'messages' => $messages,
        ]);
    }

    /**
     * Store/update category
     */
    public function categoryStore(Request $request, ?int $id = null)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'slug' => 'nullable|string|max:100',
            'icon' => 'nullable|string|max:50',
            'order_index' => 'nullable|integer',
        ]);

        try {
            if ($id) {
                $category = BlockRegistryCategory::findOrFail($id);
                $category->update($validated);
            } else {
                BlockRegistryCategory::create($validated);
            }

            $this->flashSuccess('Category saved.');
        } catch (\Exception $e) {
            $this->flashError($e->getMessage());
        }

        return back();
    }

    /**
     * Delete category
     */
    public function categoryDestroy(int $id)
    {
        $category = BlockRegistryCategory::findOrFail($id);

        // Move blocks to uncategorized before deleting
        BlockRegistry::where('category_id', $id)->update(['category_id' => null]);

        $category->delete();

        $this->flashSuccess('Category deleted.');
        return back();
    }

    /**
     * Parse fields from request
     */
    protected function parseFieldsFromRequest(Request $request): array
    {
        $fields = [];
        $fieldNames = $request->input('field_name', []);
        $fieldTypes = $request->input('field_type', []);
        $fieldLabels = $request->input('field_label', []);
        $fieldRequired = $request->input('field_required', []);
        $fieldCssClass = $request->input('field_css_class', []);
        $fieldSettings = $request->input('field_settings', []);
        $fieldOptions = $request->input('field_options', []);
        $fieldInfo = $request->input('field_info', []);

        // Repeater settings
        $repeaterMin = $request->input('field_repeater_min', []);
        $repeaterMax = $request->input('field_repeater_max', []);
        $repeaterText = $request->input('field_repeater_text', []);

        // Image settings
        $cropEnabled = $request->input('field_crop_enabled', []);
        $aspectRatio = $request->input('field_aspect_ratio', []);
        $customRatio = $request->input('field_custom_ratio', []);
        $srcsetSizes = $request->input('field_srcset_sizes', []);

        // Sub-fields for repeaters
        $subFieldNames = $request->input('subfield_name', []);
        $subFieldTypes = $request->input('subfield_type', []);
        $subFieldLabels = $request->input('subfield_label', []);
        $subFieldRequired = $request->input('subfield_required', []);
        $subFieldParentIndex = $request->input('subfield_parent_index', []);
        $subFieldCssClass = $request->input('subfield_css_class', []);
        $subFieldOptions = $request->input('subfield_options', []);
        $subFieldInfo = $request->input('subfield_info', []);
        $subFieldCropEnabled = $request->input('subfield_crop_enabled', []);
        $subFieldAspectRatio = $request->input('subfield_aspect_ratio', []);
        $subFieldCustomRatio = $request->input('subfield_custom_ratio', []);
        $subFieldSrcsetSizes = $request->input('subfield_srcset_sizes', []);

        foreach ($fieldNames as $index => $name) {
            if (empty($name)) continue;

            $fieldData = [
                'name' => $name,
                'label' => $fieldLabels[$index] ?? $name,
                'type' => $fieldTypes[$index] ?? 'text',
                'order_index' => $index,
                'required' => isset($fieldRequired[$index]),
                'css_class' => $fieldCssClass[$index] ?? null,
                'settings' => $fieldSettings[$index] ?? null,
                'options' => $fieldOptions[$index] ?? null,
                'info' => $fieldInfo[$index] ?? null,
                'sub_fields' => [],
            ];

            // Add repeater settings if this is a repeater field
            if ($fieldData['type'] === 'repeater') {
                $fieldData['repeater_min'] = (int) ($repeaterMin[$index] ?? 0);
                $fieldData['repeater_max'] = (int) ($repeaterMax[$index] ?? 100);
                $fieldData['repeater_text'] = $repeaterText[$index] ?? 'Add Row';

                // Collect sub-fields for this repeater
                foreach ($subFieldNames as $subIndex => $subName) {
                    if (empty($subName)) continue;
                    if (($subFieldParentIndex[$subIndex] ?? -1) != $index) continue;

                    $subFieldData = [
                        'name' => $subName,
                        'label' => $subFieldLabels[$subIndex] ?? $subName,
                        'type' => $subFieldTypes[$subIndex] ?? 'text',
                        'required' => isset($subFieldRequired[$subIndex]),
                        'css_class' => $subFieldCssClass[$subIndex] ?? null,
                        'options' => $subFieldOptions[$subIndex] ?? null,
                        'info' => $subFieldInfo[$subIndex] ?? null,
                    ];

                    // Build image settings for image sub-fields with crop enabled
                    if ($subFieldData['type'] === 'image' && ($subFieldCropEnabled[$subIndex] ?? '0') === '1') {
                        $subFieldData['settings'] = $this->buildImageSettingsJson(
                            $subFieldSrcsetSizes[$subIndex] ?? '',
                            $subFieldAspectRatio[$subIndex] ?? '',
                            $subFieldCustomRatio[$subIndex] ?? ''
                        );
                    }

                    $fieldData['sub_fields'][] = $subFieldData;
                }
            }

            // Add image settings if this is an image field with crop enabled
            if ($fieldData['type'] === 'image' && isset($cropEnabled[$index])) {
                $fieldData['settings'] = $this->buildImageSettingsJson(
                    $srcsetSizes[$index] ?? '',
                    $aspectRatio[$index] ?? '',
                    $customRatio[$index] ?? ''
                );
            }

            $fields[] = $fieldData;
        }

        return $fields;
    }

    /**
     * Handle template assignments
     */
    protected function handleTemplateAssignments(BlockRegistry $block, Request $request): void
    {
        $selectedTemplates = $request->input('templates', []);

        // Remove existing assignments
        $block->templateAssignments()->delete();

        // Create new assignments (always default so blocks auto-add to new pages)
        foreach ($selectedTemplates as $index => $templateName) {
            $this->templateService->assignBlockToTemplate(
                $block->id,
                $templateName,
                true,
                $index
            );
        }
    }

    /**
     * Get current user ID
     */
    protected function getCurrentUserId(): ?int
    {
        // Try to get from session
        if (isset($_SESSION['content_manager']['user_id'])) {
            return (int) $_SESSION['content_manager']['user_id'];
        }
        return null;
    }

    /**
     * Guard: require XMLHttpRequest header, return error response if missing
     */
    private const VALID_ENTITY_TYPES = ['page', 'item', 'category', 'global'];

    private function validateEntityType(?string $entityType): ?\Illuminate\Http\JsonResponse
    {
        if (!$entityType || !in_array($entityType, self::VALID_ENTITY_TYPES, true)) {
            return response()->json(['error' => 'Invalid entity_type'], 400);
        }
        return null;
    }

    private function requireAjaxRequest(): ?\Illuminate\Http\JsonResponse
    {
        if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
            return response()->json(['error' => 'Invalid request'], 403);
        }
        return null;
    }

    /**
     * Flash a success message to session
     */
    protected function flashSuccess(string $message): void
    {
        Session::flash('success_message', ['type' => 'success', 'content' => $message]);
    }

    /**
     * Flash an error message to session
     */
    protected function flashError(string $message): void
    {
        Session::flash('form_errors', ['type' => 'error', 'content' => $message]);
    }

    /**
     * Flash a warning message to session
     */
    protected function flashWarning(string $message): void
    {
        Session::flash('success_message', ['type' => 'warning', 'content' => $message]);
    }

    /**
     * Build image settings JSON from form input values
     */
    private function buildImageSettingsJson(string $rawSizes, string $rawRatio, string $customRatio): string
    {
        $sizes = [400, 800, 1200, 1600];
        if (!empty($rawSizes)) {
            $sizes = array_map('intval', array_filter(array_map('trim', explode(',', $rawSizes))));
            sort($sizes);
        }

        if ($rawRatio === 'custom' && !empty($customRatio)) {
            $rawRatio = $customRatio;
        } elseif ($rawRatio === 'custom') {
            $rawRatio = '';
        }

        return json_encode([
            'image_settings' => [
                'crop_enabled' => true,
                'aspect_ratio' => $rawRatio,
                'srcset_sizes' => $sizes,
                'quality' => 85,
            ]
        ]);
    }

    /**
     * Render a full HTML preview page with frontend Vite assets
     */
    protected function renderPreviewHtml(string $title, string $bodyContent, string $extraStyles = ''): string
    {
        $twig = app('twig');
        $jsUrl = '';
        $cssUrls = [];

        $viteFunction = $twig->getFunction('vite');
        $viteCssFunction = $twig->getFunction('vite_css');

        if ($viteFunction) {
            $jsUrl = $viteFunction->getCallable()('js/app.js');
        }
        if ($viteCssFunction) {
            $cssUrls = $viteCssFunction->getCallable()('js/app.js');
        }

        $cssLinks = '';
        foreach ($cssUrls as $url) {
            $cssLinks .= '    <link href="' . htmlspecialchars($url) . '" rel="stylesheet">' . "\n";
        }

        return '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . htmlspecialchars($title) . '</title>
' . $cssLinks . '    <style>
        body {
            margin: 0;
            padding: 0;
            background: #f8f9fa;
        }
        .preview-wrapper {
            background: white;
        }
        .preview-error {
            padding: 2rem;
            text-align: center;
            color: #dc3545;
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            margin: 1rem;
            border-radius: 4px;
        }
' . $extraStyles . '    </style>
</head>
<body>
<div id="vue_environment">
    <div class="preview-wrapper">
        ' . $bodyContent . '
    </div>
</div>
    <script src="' . htmlspecialchars($jsUrl) . '" type="module"></script>
</body>
</html>';
    }

    /**
     * Get form messages from session
     */
    protected function getFormMessages(): array
    {
        $messages = [];

        if ($success = Session::pull('success_message')) {
            $messages[] = $success;
        }

        if ($error = Session::pull('form_errors')) {
            $messages[] = $error;
        }

        return $messages;
    }

    /**
     * Get component templates grouped by category for the template dropdown
     */
    protected function getComponentTemplates(): array
    {
        try {
            $discovery = $this->componentScanner->discoverComponents();
            $components = $discovery['components'] ?? [];

            // Group by category (directory structure)
            $grouped = [];
            foreach ($components as $component) {
                $category = $component->category ?? 'Other';
                if (!isset($grouped[$category])) {
                    $grouped[$category] = [];
                }
                $grouped[$category][] = [
                    'path' => $component->path,
                    'name' => $component->name,
                    'description' => $component->description ?? '',
                ];
            }

            // Sort categories alphabetically
            ksort($grouped);

            return $grouped;
        } catch (\Exception $e) {
            \Log::error('Failed to load component templates: ' . $e->getMessage());
            return [];
        }
    }
}
