<?php

/**
 * @file
 * preprocess.php
 *
 * Define all the preprocess HOOKs.
 */

use Drupal\Component\Utility\Html;

/**
 * Implements hook_preprocess().
 */
function naomi_2025_preprocess(array &$variables) {
  // Get currently active user and roles.
  $account = \Drupal::currentUser();

  $variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
  $variables['user_roles'] = implode(', ', $account->getRoles());
}

/**
 * Implements hook_preprocess_html().
 */
function naomi_2025_preprocess_html(array &$variables) {
  $cookies = \Drupal::requestStack()->getCurrentRequest()->cookies;

  $variables['html_attributes']['data-site-mode'] = $cookies->get('USER_SITE_MODE') ?? $cookies->get('SYSTEM_SITE_MODE') ?? 'at-work';

  // Add the new class names to the array of classes.
  $variables['attributes']['class'][] = 'site-page';
  $variables['attributes']['data-roles'] = $variables['user_roles'];

  /** @var Symfony\Component\Routing\Route $route */
  $route = \Drupal::routeMatch()->getRouteObject();
  $path = $route->getPath();

  if (str_starts_with($path, '/node')) {
    /** @var \Drupal\node\Entity\Node $node */
    $node = \Drupal::routeMatch()->getParameter('node');

    if (isset($variables['node_type'])) {
      $variables['attributes']['class'][] = Html::getClass('site-page--node-' . $variables['node_type']);
    }
  }

  if (isset($variables['is_front']) && $variables['is_front'] === TRUE) {
    $variables['attributes']['class'][] = 'site-page--is-front';
  }
}

/**
 * Implements hook_preprocess_region().
 */
function naomi_2025_preprocess_region(array &$variables) {
  $elements = $variables['elements'];

  if (isset($elements['#region'])) {
    $region = $elements['#region'];

    // Clear any Drupal classes.
    $variables['attributes']['class'] = [];
    $variables['attributes']['class'] = Html::getClass("region-$region");
  }
}

/**
 * Implements hook_preprocess_container().
 */
function naomi_2025_preprocess_container(array &$variables) {
  $element = $variables['element'];

  if (isset($element['#type'])) {
    if (in_array($element['#type'], ['actions', 'webform_actions'])) {
      // Clear any Drupal classes.
      $variables['attributes']['class'] = [];

      $variables['attributes']['class'][] = 'form__element';
      $variables['attributes']['class'][] = 'form__element--actions';
    }
  }
}
