<?php
if (!defined('ABSPATH')) exit;

function juconnect_setup() {
  add_theme_support('title-tag');
  add_theme_support('post-thumbnails');
  add_theme_support('custom-logo', [
    'height' => 120,
    'width'  => 120,
    'flex-height' => true,
    'flex-width'  => true,
  ]);

  register_nav_menus([
    'primary' => __('Primary Navigation', 'juconnect'),
    'footer'  => __('Footer Navigation', 'juconnect'),
  ]);
}
add_action('after_setup_theme', 'juconnect_setup');

function juconnect_assets() {
  $ver = wp_get_theme()->get('Version');
  wp_enqueue_style('juconnect-style', get_stylesheet_uri(), [], $ver);
  wp_enqueue_script('juconnect-app', get_template_directory_uri().'/assets/js/app.js', [], $ver, true);
}
add_action('wp_enqueue_scripts', 'juconnect_assets');

/**
 * Render primary nav in strict styleguide markup:
 * - groups = top-level items
 * - links = children + optionally the parent itself
 */
function juconnect_render_sidenav_nav() {
  $locations = get_nav_menu_locations();
  if (!isset($locations['primary'])) return;

  $menu_obj = wp_get_nav_menu_object($locations['primary']);
  if (!$menu_obj) return;

  $items = wp_get_nav_menu_items($menu_obj->term_id);
  if (!$items) return;

  $by_parent = [];
  foreach ($items as $it) {
    $pid = (int)$it->menu_item_parent;
    if (!isset($by_parent[$pid])) $by_parent[$pid] = [];
    $by_parent[$pid][] = $it;
  }

  $top = $by_parent[0] ?? [];
  foreach ($top as $parent) {
    echo '<div class="navgroup">';
    echo '<div class="navgroup__title">'.esc_html($parent->title).'</div>';

    // Parent link as first item (optional but useful)
    if (!empty($parent->url) && $parent->url !== '#') {
      echo '<a class="navlink" href="'.esc_url($parent->url).'">'.esc_html('Übersicht').'</a>';
    }

    $children = $by_parent[(int)$parent->ID] ?? [];
    foreach ($children as $child) {
      echo '<a class="navlink" href="'.esc_url($child->url).'">'.esc_html($child->title).'</a>';
    }
    echo '</div>';
  }
}


// Add styleguide classes to WP menus
function juconnect_nav_link_attributes($atts, $item, $args, $depth){
  if (!empty($args->theme_location) && $args->theme_location === 'primary'){
    $existing = isset($atts['class']) ? $atts['class'].' ' : '';
    $atts['class'] = $existing . 'navlink';
  }
  return $atts;
}
add_filter('nav_menu_link_attributes', 'juconnect_nav_link_attributes', 10, 4);

function juconnect_nav_menu_submenu_class($classes, $args, $depth){
  if (!empty($args->theme_location) && $args->theme_location === 'primary'){
    $classes[] = 'topnav__submenu';
  }
  return $classes;
}
add_filter('nav_menu_submenu_css_class', 'juconnect_nav_menu_submenu_class', 10, 3);
