<?php

declare(strict_types=1);

namespace Drupal\Tests\simple_interactive_maps\Functional;

use Drupal\simple_interactive_maps\Entity\InteractiveMap;
use Drupal\Tests\BrowserTestBase;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Regression guard for InteractiveMapForm's base_map select options grouping.
 *
 * Covers the label/map_category grouping, which had a redundant
 * array_key_exists() check removed since MapDefinitionPluginManager
 * definitions are now guaranteed to carry a map_category key.
 */
#[Group('simple_interactive_maps')]
#[RunTestsInSeparateProcesses]
final class InteractiveMapFormTest extends BrowserTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'field_group',
    'simple_interactive_maps',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $account = $this->drupalCreateUser(['administer interactive_map']);
    $this->drupalLogin($account);
  }

  /**
   * Tests that the add form creates a map with seeded regions.
   */
  public function testAddFormCreatesMapWithSeededRegions(): void {
    $this->drupalGet('/admin/structure/interactive_map/add');
    $this->assertSession()->statusCodeEquals(200);

    // The base_map select must offer the always-available plugin.
    $this->assertSession()->optionExists('base_map', 'us_states_territories');

    $this->submitForm([
      'label' => 'My Test Map',
      'id' => 'my_test_map',
      'base_map' => 'us_states_territories',
    ], 'Save');

    $this->assertSession()->pageTextContains('Created new example My Test Map.');

    $map = \Drupal::entityTypeManager()->getStorage('interactive_map')->loadUnchanged('my_test_map');
    $this->assertNotNull($map);
    \assert($map instanceof InteractiveMap);
    $this->assertSame('us_states_territories', $map->get('base_map'));

    // InteractiveMapForm::save() seeds every region the plugin provides.
    $regions = $map->getRegions();
    $this->assertNotEmpty($regions);
    $this->assertArrayHasKey('AL', $regions);
    $this->assertSame('none', $regions['AL']['action']['plugin_id']);
  }

  /**
   * Tests that the edit form disables the base_map select.
   */
  public function testEditFormDisablesTheBaseMapSelect(): void {
    $this->drupalGet('/admin/structure/interactive_map/add');
    $this->submitForm([
      'label' => 'My Test Map',
      'id' => 'my_test_map',
      'base_map' => 'us_states_territories',
    ], 'Save');

    $this->drupalGet('/admin/structure/interactive-map/my_test_map');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->fieldDisabled('base_map');
  }

}
