<?php

/**
 * @file
 * Functions to support theming modules in the Toc GA theme.
 */

use Drupal\nre_stations_entity_type\Entity\NreStationEckEntity;

/**
 * Preprocess card_blocks by machine name.
 * This is above the fold, so we are giving the images 'eager' not 'lazy' (default).
 */
function toc_ga_preprocess_card_block__front_banner_blocks(&$vars) {
  $vars['col_classes'] = 'col-md-8 mb-lg-0';
  $entities = $vars['element']['entities_raw'];
  $items = [];
  foreach ($entities as $entity) {
    /* @var \Drupal\eck\Entity\EckEntity $entity */
    $extras = $entity->__get('extras') ?? [];
    $extras['card_image_loading'] = 'eager';
    $entity->__set('extras', $extras);
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('card_block');
    $items[] = $view_builder->view($entity);
  }
  if (!empty($items) && ($vars['batch'] >= 1)) {
    $vars['items'] = $items;
    $vars['slides'] = array_chunk($items, $vars['batch']);
  }
}

/**
 * Preprocess for buy_tickets_header().
 *
 * For GA we are just adding the default tablet view port tabs state.
 *
 * @param array $vars
 *   Theme variables.
 */
function toc_ga_preprocess_buy_tickets_header(array &$vars) {
  $vars['tablet_tabs_closed'] = TRUE;
}

/**
 * Preprocess for nre_ldb_stations.
 *
 * Force Arrivals/Departures headings to use h2 in GA
 * unless overridden explicitly upstream.
 */
function toc_ga_preprocess_nre_ldb_stations(array &$vars) {
  if (empty($vars['ad_header_tag'])) {
    $vars['ad_header_tag'] = 'h2';
  }
  // Provide human-readable station name for templates using CRS code.
  $station_crs = $vars['element']['station'] ?? ($vars['station'] ?? NULL);
  if (!empty($station_crs) && empty($vars['station_name'])) {
    $station_entity = NreStationEckEntity::loadByCrs($station_crs);
    if ($station_entity) {
      $vars['station_name'] = $station_entity->getTitle();
      // Also set inside element for patterns expecting nested vars.
      $vars['element']['station_name'] = $vars['station_name'];
      // Set GA-specific titles for departures and arrivals if not provided.
      if (empty($vars['departure_title'])) {
        $vars['departure_title'] = 'Train departures from ' . $vars['station_name'];
      }
      if (empty($vars['arrival_title'])) {
        $vars['arrival_title'] = 'Train arrivals at ' . $vars['station_name'];
      }
      // Mirror into element for patterns reading from element.
      $vars['element']['departure_title'] = $vars['departure_title'];
      $vars['element']['arrival_title'] = $vars['arrival_title'];
    }
  }
}
