<?php

namespace Mtc\Plugins\BlockManager\Tests\Feature;

use Tests\TestCase;

class BlockPreviewApiTest extends TestCase
{
    public function test_preview_renders_structure_to_html_envelope(): void
    {
        $response = $this->postJson('/api/block-manager/preview', [
            'structure_json' => ['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'],
            ]],
        ]);

        $response->assertStatus(200);
        $response->assertJsonStructure(['data' => ['html', 'css_hrefs']]);

        $html = $response->json('data.html');
        $this->assertStringContainsString('data-bm-instance="el-1"', $html);
        $this->assertStringContainsString('bm-button--primary', $html);
    }

    public function test_preview_returns_app_css_href_for_the_canvas_iframe(): void
    {
        $hrefs = $this->postJson('/api/block-manager/preview', [
            'structure_json' => ['elements' => []],
        ])->json('data.css_hrefs');

        $this->assertIsArray($hrefs);
        $this->assertNotEmpty($hrefs, 'Preview must return the app CSS href so the canvas iframe can style components.');
        $this->assertStringContainsString('/public/build/', $hrefs[0]);
    }

    public function test_preview_tolerates_missing_structure(): void
    {
        $this->postJson('/api/block-manager/preview', [])->assertStatus(200);
    }
}
