<?php

/**
 * @file
 * MWRD theme preprocess functions.
 */
use Drupal\image\Entity\ImageStyle;
use Drupal\Component\Utility\Unicode;
use Drupal\paragraphs\ParagraphInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
/**
 * Colour presets (see spec section 9.2).
 */
function mwrd_theme_color_presets(): array {
  return [
    'navy'  => ['navy' => '#0B4A8F', 'navy_dark' => '#073366', 'navy_mid' => '#0F58A4', 'teal' => '#D35400', 'teal_hover' => '#B84700', 'light' => '#F4F7FB'],
    'red'   => ['navy' => '#7f1d1d', 'navy_dark' => '#5c1414', 'navy_mid' => '#991b1b', 'teal' => '#d97706', 'teal_hover' => '#b45f04', 'light' => '#FBF5F5'],
    'green' => ['navy' => '#16613a', 'navy_dark' => '#0f4528', 'navy_mid' => '#1b7647', 'teal' => '#c47a0c', 'teal_hover' => '#a2650a', 'light' => '#F3F9F5'],
    'blue'  => ['navy' => '#1e3a8a', 'navy_dark' => '#162b66', 'navy_mid' => '#2547a8', 'teal' => '#0891b2', 'teal_hover' => '#067490', 'light' => '#F3F6FC'],
  ];
}

/**
 * Implements hook_preprocess_html().
 *
 * Builds the :root CSS variables from theme settings so the admin can
 * switch colour themes without touching code.
 */
function mwrd_theme_preprocess_html(array &$variables): void {
  $presets = mwrd_theme_color_presets();
  $active = theme_get_setting('active_theme') ?: 'navy';

  if ($active === 'custom') {
    $colors = [
      'navy'       => theme_get_setting('custom_navy'),
      'navy_dark'  => theme_get_setting('custom_navy_dark'),
      'navy_mid'   => theme_get_setting('custom_navy_mid'),
      'teal'       => theme_get_setting('custom_teal'),
      'teal_hover' => theme_get_setting('custom_teal_hover'),
      'light'      => theme_get_setting('custom_light'),
    ];
  }
  else {
    $colors = $presets[$active] ?? $presets['navy'];
  }

  $css = ':root{';
  foreach ($colors as $key => $value) {
    // Only allow valid hex colours into the inline <style>.
    if (is_string($value) && preg_match('/^#[0-9a-fA-F]{3,8}$/', $value)) {
      $css .= '--theme-' . str_replace('_', '-', $key) . ':' . $value . ';';
    }
  }
  $css .= '}';

  $variables['theme_css_vars'] = $css;
  $variables['#cache']['tags'][] = 'config:mwrd_theme.settings';
}

/**
 * Implements hook_preprocess_page().
 */
function mwrd_theme_preprocess_page(array &$variables): void {
  $variables['site_name'] = \Drupal::config('system.site')->get('name');
  $variables['site_slogan'] = \Drupal::config('system.site')->get('slogan');
  $variables['logo'] = theme_get_setting('logo.url');
}

/**
 * Implements hook_theme_suggestions_page_alter().
 */
function mwrd_theme_theme_suggestions_page_alter(array &$suggestions, array $variables): void {
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $suggestions[] = 'page__front';
  }
}

/**
 * Implements hook_preprocess_links__language_block().
 *
 * Provides the current language and the URL of the *other* language so the
 * template can render a single toggle pill.
 */
function mwrd_theme_preprocess_links__language_block(array &$variables) {
  $current = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $variables['current_langcode'] = $current;
  $variables['other_langcode'] = NULL;
  $variables['other_href'] = NULL;

  foreach (($variables['links'] ?? []) as $item) {
    if (empty($item['link']['#url']) || empty($item['link']['#options']['language'])) {
      continue;
    }
    $language = $item['link']['#options']['language'];
    if ($language->getId() === $current) {
      continue;
    }
    $url = clone $item['link']['#url'];
    $url->setOption('language', $language);
    $variables['other_langcode'] = $language->getId();
    $variables['other_href'] = $url->toString();
    break;
  }
}

function mwrd_theme_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if (in_array($variables['menu_name'] ?? '', ['footer-navigation', 'footer-resources'], TRUE)) {
    $suggestions[] = 'menu__footer';
  }
}

function mwrd_theme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  $id = $variables['elements']['#plugin_id'] ?? '';
  if (str_starts_with($id, 'system_menu_block:footer-')) {
    $suggestions[] = 'block__footer_menu';
  }
}

/**
 * Clears the section's cache when events or gallery items change.
 */
function mwrd_theme_paragraph_view_alter(array &$build, ParagraphInterface $paragraph, EntityViewDisplayInterface $display) {
  if ($paragraph->bundle() === 'events_gallery') {
    $build['#cache']['tags'][] = 'node_list:event';
    $build['#cache']['tags'][] = 'node_list:gallery_item';
  }
}

/**
 * Provides events and gallery items to paragraph--events-gallery.html.twig.
 */
function mwrd_theme_preprocess_paragraph__events_gallery(array &$variables) {
  $paragraph = $variables['paragraph'];
  $storage = \Drupal::entityTypeManager()->getStorage('node');
  $repo = \Drupal::service('entity.repository');
  $formatter = \Drupal::service('date.formatter');
  $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();

  $event_total = max(1, (int) ($paragraph->get('field_event_count')->value ?: 3));
  $gallery_total = max(1, (int) ($paragraph->get('field_gallery_count')->value ?: 5));

  // Returns [url, alt] for the first image of a media entity.
  $media_image = function ($media, $style) use ($repo) {
    if (!$media) {
      return NULL;
    }
    $media = $repo->getTranslationFromContext($media);
    if (!$media->hasField('field_media_image') || $media->get('field_media_image')->isEmpty()) {
      return NULL;
    }
    $file = $media->get('field_media_image')->entity;
    if (!$file) {
      return NULL;
    }
    $uri = $file->getFileUri();
    $image_style = ImageStyle::load($style);
    $url = $image_style
      ? $image_style->buildUrl($uri)
      : \Drupal::service('file_url_generator')->generateString($uri);
    return ['url' => $url, 'alt' => $media->get('field_media_image')->alt];
  };

  // ---- Events: featured first, then upcoming by date.
  $ids = $storage->getQuery()
    ->accessCheck(TRUE)
    ->condition('type', 'event')
    ->condition('status', 1)
    ->condition('field_event_status', ['upcoming', 'live'], 'IN')
    ->sort('field_event_date', 'ASC')
    ->range(0, 50)
    ->execute();

  $nodes = $ids ? array_values($storage->loadMultiple($ids)) : [];
  $featured_index = NULL;
  foreach ($nodes as $k => $n) {
    if ($n->get('field_is_featured')->value) {
      $featured_index = $k;
      break;
    }
  }
  if ($featured_index !== NULL) {
    $featured = $nodes[$featured_index];
    unset($nodes[$featured_index]);
    array_unshift($nodes, $featured);
  }
  $nodes = array_slice(array_values($nodes), 0, $event_total);

  $events = [];
  foreach ($nodes as $node) {
    $node = $repo->getTranslationFromContext($node);
    $day = $month = $full = '';
    if (!$node->get('field_event_date')->isEmpty() && ($date = $node->get('field_event_date')->date)) {
      $ts = $date->getTimestamp();
      $is_date_only = $node->get('field_event_date')->getFieldDefinition()->getSetting('datetime_type') === 'date';
      $tz = $is_date_only ? 'UTC' : NULL;
      $day = $formatter->format($ts, 'custom', 'd', $tz, $langcode);
      $month = $formatter->format($ts, 'custom', 'M', $tz, $langcode);
      $full = $formatter->format($ts, 'custom', 'j M Y', $tz, $langcode);
    }
    $live_url = NULL;
    if (!$node->get('field_live_stream_url')->isEmpty()) {
      $live_url = $node->get('field_live_stream_url')->first()->getUrl()->toString();
    }
    $text = '';
    if ($node->hasField('field_body') && !$node->get('field_body')->isEmpty()) {
      $text = trim(strip_tags((string) $node->get('field_body')->value));
    }
    $events[] = [
      'title' => $node->label(),
      'url' => $node->toUrl()->toString(),
      'day' => $day,
      'month' => $month,
      'date' => $full,
      'time' => $node->get('field_event_time')->value,
      'venue' => $node->get('field_venue')->value,
      'summary' => Unicode::truncate($text, 180, TRUE, TRUE),
      'image' => $media_image($node->get('field_event_image')->entity, 'event_card'),
      'live' => (bool) $node->get('field_is_live_stream')->value,
      'live_url' => $live_url,
      'is_live_now' => $node->get('field_event_status')->value === 'live',
    ];
  }

  // ---- Gallery: featured photos, newest first.
  $gids = $storage->getQuery()
    ->accessCheck(TRUE)
    ->condition('type', 'gallery_item')
    ->condition('status', 1)
    ->condition('field_is_featured', 1)
    ->sort('field_event_date', 'DESC')
    ->range(0, $gallery_total)
    ->execute();

  $gallery = [];
  foreach ($gids ? $storage->loadMultiple($gids) : [] as $node) {
    $node = $repo->getTranslationFromContext($node);
    $thumb = $media_image($node->get('field_gallery_image')->entity, 'gallery_thumb');
    $large = $media_image($node->get('field_gallery_image')->entity, 'gallery_large');
    if (!$thumb) {
      continue;
    }
    $gallery[] = [
      'title' => $node->label(),
      'location' => $node->get('field_location')->value,
      'thumb' => $thumb['url'],
      'large' => $large ? $large['url'] : $thumb['url'],
      'alt' => $thumb['alt'] ?: $node->label(),
    ];
  }

  $variables['events'] = $events;
  $variables['gallery'] = $gallery;
}

function mwrd_theme_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $view = $form_state->get('view');
  if (!$view || $view->id() !== 'site_search') {
    return;
  }

  // Must match Views → exposed filter → "Filter identifier".
  $keys_id = 'title';
  $cat_id  = 'field_search_category_target_id';

  // In a block, Drupal moves the form's #attributes onto the block wrapper <div>.
  // So these classes style the outer frame; the <form> becomes a flex row via CSS.
  $form['#attributes']['class'] = ['mwrd-search','w-full','shadow-sm','rounded-lg','overflow-hidden','border','border-gray-300','bg-white','focus-within:ring-2','focus-within:ring-navy/20','focus-within:border-navy'];
  $form['#attributes']['role'] = 'search';

  if (isset($form[$keys_id])) {
    $form[$keys_id]['#title_display'] = 'invisible';
    $form[$keys_id]['#weight'] = -30;
    $form[$keys_id]['#wrapper_attributes']['class'] = ['flex-grow', 'min-w-0'];
    $form[$keys_id]['#attributes']['placeholder'] = t('Search Tenders, Projects, Reservoir storage, GRs...');
    $form[$keys_id]['#attributes']['autocomplete'] = 'off';
    $form[$keys_id]['#attributes']['aria-label'] = t('Search');
    $form[$keys_id]['#attributes']['data-search-input'] = '';
    $form[$keys_id]['#attributes']['class'] = ['w-full','h-full','px-4','py-2','bg-gray-50','text-sm','outline-none','border-0'];
  }

  $form['voice'] = [
    '#type' => 'html_tag',
    '#tag' => 'button',
    '#weight' => -20,
    '#attributes' => [
      'type' => 'button',
      'data-voice-trigger' => '',
      'data-unsupported' => t('Voice search is not supported in this browser.'),
      'aria-label' => t('Search by voice'),
      'aria-pressed' => 'false',
      'class' => ['flex','items-center','px-3','bg-gray-50','text-gray-500','hover:text-navy','cursor-pointer','border-0'],
    ],
    '#value' => Markup::create('<span class="material-symbols-outlined text-xl">mic</span>'),
  ];

  if (isset($form[$cat_id])) {
    $form[$cat_id]['#title_display'] = 'invisible';
    $form[$cat_id]['#weight'] = -10;
    $form[$cat_id]['#options']['All'] = t('All Categories');
    $form[$cat_id]['#wrapper_attributes']['class'] = ['hidden','md:flex','shrink-0'];
    $form[$cat_id]['#attributes']['aria-label'] = t('Search category');
    $form[$cat_id]['#attributes']['class'] = ['h-full','bg-gray-100','border-0','border-l','border-gray-200','text-xs','font-semibold','text-gray-600','pl-4','pr-8','cursor-pointer'];
  }

  $form['actions']['#attributes']['class'] = ['shrink-0','flex'];
  $form['actions']['submit']['#value'] = t('Search');
  $form['actions']['submit']['#attributes']['class'] = ['bg-navy','hover:bg-navy-mid','text-white','px-5','text-sm','font-bold','transition-colors','cursor-pointer','border-0'];
}