<?php

namespace Mtc\Plugins\BlockManager\Tests\Feature;

use Illuminate\Support\Str;
use Mtc\Modules\BlockRegistry\Models\BlockRegistry;
use Mtc\Plugins\BlockManager\Models\BlockManagerBlock;
use Tests\TestCase;

/**
 * Shipping a block with a styled container writes a per-block LESS file
 * (token references preserved, responsive @media) and wraps the container's
 * children in a scoped <div> in the generated Twig.
 */
class ShipContainerStyleTest extends TestCase
{
    private array $createdUuids = [];
    private array $shippedSlugs = [];

    protected function tearDown(): void
    {
        $twigDir = base_path('sites/default/templates/includes/page_blocks');
        $jsonDir = base_path('modules/BlockRegistry/blocks');
        $lessDir = base_path('sites/default/css/block_manager_blocks');

        foreach ($this->shippedSlugs as $slug) {
            @unlink($twigDir . "/{$slug}.twig");
            @unlink($jsonDir . "/{$slug}.json");
            @unlink($lessDir . "/{$slug}.less");
            BlockRegistry::where('slug', $slug)->delete();
        }
        if (!empty($this->createdUuids)) {
            BlockManagerBlock::whereIn('uuid', $this->createdUuids)->delete();
        }

        parent::tearDown();
    }

    public function test_ship_writes_per_block_less_with_tokens_and_media(): void
    {
        $block = $this->seedStyledContainerBlock();

        $this->postJson("/api/block-manager/{$block->id}/ship")->assertStatus(200);
        $this->shippedSlugs[] = $block->slug;

        $lessPath = base_path("sites/default/css/block_manager_blocks/{$block->slug}.less");
        $this->assertFileExists($lessPath, "Per-block LESS not written to {$lessPath}.");

        $less = (string) file_get_contents($lessPath);
        $this->assertStringContainsString('.bm-ci-ctr-1', $less, 'LESS must be scoped to the per-instance class.');
        $this->assertStringContainsString('display: flex;', $less);
        // token preserved (not resolved) for the LESS compiler
        $this->assertStringContainsString('background-color: @primary_color;', $less);
        // responsive cell → LESS media variable
        $this->assertStringContainsString('@media (max-width: @mobile_width)', $less);
        $this->assertStringContainsString('flex-direction: column;', $less);

        // Aggregator imports it.
        $agg = (string) file_get_contents(base_path('sites/default/css/block_manager_blocks.less'));
        $this->assertStringContainsString("{$block->slug}.less", $agg);
    }

    public function test_ship_twig_wraps_container_children_in_scoped_div(): void
    {
        $block = $this->seedStyledContainerBlock();

        $this->postJson("/api/block-manager/{$block->id}/ship")->assertStatus(200);
        $this->shippedSlugs[] = $block->slug;

        $twig = (string) file_get_contents(
            base_path("sites/default/templates/includes/page_blocks/{$block->slug}.twig")
        );

        $this->assertStringContainsString('<div class="bm-container bm-ci-ctr-1">', $twig);
        $this->assertStringContainsString('heading/variants/default.twig', $twig);
    }

    private function seedStyledContainerBlock(): BlockManagerBlock
    {
        $uuid = (string) Str::uuid();
        $this->createdUuids[] = $uuid;

        return BlockManagerBlock::create([
            'uuid'           => $uuid,
            'slug'           => 'ctr-style-ship-' . Str::random(8),
            'name'           => 'Container Style Ship Probe',
            'icon'           => 'fa-cube',
            'structure_json' => [
                'elements' => [
                    [
                        'instance_id'  => 'ctr-1',
                        'element_type' => 'container',
                        'variant'      => 'default',
                        'style_props'  => [
                            'base' => [
                                'default' => [
                                    'desktop' => [
                                        'layout'     => ['display' => ['raw' => 'flex'], 'gap' => ['raw' => '24px']],
                                        'background' => ['color' => ['token' => '@primary_color']],
                                    ],
                                    'mobile' => [
                                        'layout' => ['flex_direction' => ['raw' => 'column']],
                                    ],
                                ],
                            ],
                        ],
                        'children'     => [
                            ['instance_id' => 'h-1', 'element_type' => 'heading', 'variant' => 'default', 'field_name' => 'title'],
                        ],
                    ],
                ],
            ],
        ]);
    }
}
