<?php

namespace Mtc\Plugins\BlockManager\Tests\Unit;

use Mtc\Plugins\BlockManager\Services\BlockPreviewService;
use Tests\TestCase;

class BlockPreviewServiceTest extends TestCase
{
    private BlockPreviewService $service;

    protected function setUp(): void
    {
        parent::setUp();
        $this->service = app(BlockPreviewService::class);
    }

    public function test_renders_each_instance_wrapped_with_its_id(): void
    {
        $html = $this->service->render(['elements' => [
            ['instance_id' => 'el-1', 'element_type' => 'heading', 'variant' => 'default', 'field_name' => 'title'],
            ['instance_id' => 'el-2', 'element_type' => 'button',  'variant' => 'primary', 'field_name' => 'cta'],
        ]]);

        $this->assertStringContainsString('data-bm-instance="el-1"', $html);
        $this->assertStringContainsString('data-bm-instance="el-2"', $html);
    }

    public function test_renders_real_variant_markup_with_bem_classes(): void
    {
        $html = $this->service->render(['elements' => [
            ['instance_id' => 'el-1', 'element_type' => 'heading', 'variant' => 'default', 'field_name' => 'title'],
            ['instance_id' => 'el-2', 'element_type' => 'button',  'variant' => 'primary', 'field_name' => 'cta'],
        ]]);

        $this->assertStringContainsString('bm-heading--default', $html);
        $this->assertStringContainsString('bm-button--primary', $html);
    }

    public function test_fills_sample_content_so_partials_are_not_blank(): void
    {
        $html = $this->service->render(['elements' => [
            ['instance_id' => 'el-1', 'element_type' => 'button', 'variant' => 'primary', 'field_name' => 'cta'],
        ]]);

        // Button label sample text threads through the {{ label }} binding.
        $this->assertStringContainsString('Button label', $html);
    }

    public function test_honours_instance_default_value_over_sample(): void
    {
        $html = $this->service->render(['elements' => [
            [
                'instance_id'   => 'el-1',
                'element_type'  => 'heading',
                'variant'       => 'default',
                'field_name'    => 'title',
                'default_value' => ['text' => 'Winter Sale'],
            ],
        ]]);

        $this->assertStringContainsString('Winter Sale', $html);
    }

    public function test_unknown_element_type_renders_placeholder_not_throw(): void
    {
        $html = $this->service->render(['elements' => [
            ['instance_id' => 'el-1', 'element_type' => 'pizza', 'variant' => 'default'],
        ]]);

        $this->assertStringContainsString('data-bm-instance="el-1"', $html);
        $this->assertStringContainsString('Unknown element: pizza', $html);
    }

    public function test_empty_structure_renders_empty_state(): void
    {
        $html = $this->service->render(['elements' => []]);
        $this->assertStringContainsString('bm-pv-empty', $html);
    }
}
