<?php

namespace Drupal\localgov_elections\EventSubscriber;

use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\localgov_core\Event\PageHeaderDisplayEvent;
use Drupal\node\NodeInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Sets the page header for election pages and view sub-pages.
 *
 * @package Drupal\localgov_elections\EventSubscriber
 */
class PageHeaderSubscriber implements EventSubscriberInterface {

  /**
   * PageHeaderSubscriber constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Routing\CurrentRouteMatch $currentRouteMatch
   *   The current route match.
   */
  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
    protected CurrentRouteMatch $currentRouteMatch,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [
      PageHeaderDisplayEvent::EVENT_NAME => ['setPageHeader', 0],
    ];
  }

  /**
   * Set page title, subtitle and lede.
   *
   * For election view sub-pages (map, results, candidates etc.), the title is
   * set to the view's own title and the subtitle to the election node name.
   */
  public function setPageHeader(PageHeaderDisplayEvent $event): void {

    // Handle election view sub-pages.
    $view = $event->getView();
    if ($view && (str_starts_with($view->id(), 'localgov_election') || str_starts_with($view->id(), 'localgov_electoral'))) {
      $node_id = $this->currentRouteMatch->getRawParameter('node');
      if (!$node_id) {
        return;
      }

      $election = $this->entityTypeManager->getStorage('node')->load($node_id);
      if (!$election instanceof NodeInterface || $election->bundle() !== 'localgov_election') {
        return;
      }

      $event->setTitle($view->getTitle());
      $event->setSubTitle($election->getTitle());
      $event->setCacheTags(Cache::mergeTags($view->storage->getCacheTags(), $election->getCacheTags()));
      return;
    }

    $node = $event->getEntity();
    if (!$node instanceof NodeInterface) {
      return;
    }

    // Handle the election summary page.
    if ($node->bundle() === 'localgov_election') {
      $event->setTitle('Results');
      $event->setSubTitle($node->getTitle());
      $event->setCacheTags($node->getCacheTags());
      return;
    }

    // Handle area vote pages — set subtitle to the parent election name.
    if ($node->bundle() === 'localgov_area_vote') {
      $election = $node->localgov_election->entity ?? NULL;
      if ($election instanceof NodeInterface) {
        $event->setSubTitle($election->getTitle());
        $event->setCacheTags(Cache::mergeTags($node->getCacheTags(), $election->getCacheTags()));
      }
    }
  }

}
