<?php

// Config
use YOOtheme\Builder;
use function YOOtheme\app;

$mobile = '~theme.mobile';
$header = '~theme.header';
$dialog = '~theme.dialog';
$navbar = '~theme.navbar';

// Menu ID
$attrs['id'] = $config('~menu.tag_id');

$type = $config('~menu.type', '');
$position = $config('~menu.position', '');

$hasHeaderParent = fn($items) =>
    array_any($items, fn($item) =>
        $item->type == 'heading' &&
        !empty($item->children) &&
        in_array($item->url ?? null, ['#', ''], true)
    );

// Set `nav` menu_type to default in header positions
if ($type == 'nav' && preg_match('/^(toolbar-(left|right)|logo(-mobile)?|navbar(-split|-push|-mobile)?|header(-split|-mobile)?)$/', $position)) {
    $type = '';
}

// Use Scrollspy Nav component
$scrollspyNav = true;

if (in_array($type, ['iconnav', 'subnav', 'nav'])) {

    // Type is already set

// Default on Navbar
} elseif (in_array($position, ['navbar', 'navbar-split', 'navbar-push', 'navbar-mobile'])) {

    $type = 'navbar';
    $scrollspyNav = $config(($position === 'navbar-mobile' ? $mobile . '.navbar' : $navbar). '.sticky');

    if (in_array($position, ['navbar', 'navbar-split', 'navbar-push']) && in_array($config("$header.layout"), ['stacked-center-split-a', 'stacked-center-split-b'])) {

        $isSplitMenu = true;

        // Split Auto
        $index = $config("$header.split_index") ?: ceil(count($items) / 2);

        if ($position == 'navbar-split') {
            $items = array_slice($items, 0, $index);
        } else {
            $scrollspyNav = false;
            $items = array_slice($items, $index);
        }
    }

// Default on Header
} elseif (in_array($position, ['header', 'header-split', 'header-mobile'])) {

    if (in_array($position, ['header', 'header-split']) && str_starts_with($config("$header.layout"), 'stacked')) {

        $type = 'subnav';
        $scrollspyNav = false;

    // Render in navbar
    } else {

        $type = 'navbar';
        $scrollspyNav = $config(($position === 'header-mobile' ? $mobile . '.navbar' : $navbar). '.sticky');

    }

// Default on Toolbar and Logo
} elseif (in_array($position, ['toolbar-left', 'toolbar-right', 'logo', 'logo-mobile'])) {

    $type = 'subnav';
    $scrollspyNav = false;

// Default on Sidebar, Top, Bottom, Builder 1-6 and Dialog ('dialog', 'dialog-push', 'dialog-mobile', 'dialog-mobile-push')
} else {

    $type = 'nav';

}

// Navbar
if ($type == 'navbar') {

    $attrs['class'][] = 'uk-navbar-nav';

}

// Subav
if ($type == 'subnav') {

    $attrs['class'][] = 'uk-subnav';
    $attrs['class'][] =  $config('~menu.divider') ? 'uk-subnav-divider' : '';

}

// Iconnav
if ($type == 'iconnav') {

    $attrs['class'][] = 'uk-iconnav';

}

// Nav
if ($type == 'nav') {

    $attrs['class'][] = 'uk-nav';
    $attrs['class'][] = "uk-nav-{$config('~menu.style')}";
    $attrs['class'][] = $config('~menu.style') == 'primary' ? "uk-nav-{$config('~menu.size')}" : '';
    $attrs['class'][] = $config('~menu.divider') ? 'uk-nav-divider' : '';

    // Accordion menu
    if ($hasHeaderParent($items)) {
        $config->set('~menu.accordion', true);
        $attrs['class'][] = 'uk-nav-accordion';
        $attrs['uk-nav'] = 'targets: > .js-accordion';
    }

}

// Override alignment
if ((in_array($position, ['dialog', 'dialog-push']) && $config("$dialog.text_center")) ||
    (in_array($position, ['dialog-mobile', 'dialog-mobile-push']) && $config("$mobile.dialog.text_center"))) {

    $config->set('~menu.text_align', 'center');

}

// Alignment
if ($config('~menu.text_align') && $config('~menu.text_align') != 'justify') {
    if (in_array($type, ['iconnav', 'subnav'])) {
        $attrs['class'][] = 'uk-flex-' . $config('~menu.text_align') . ($config('~menu.text_align_breakpoint') ? '@' . $config('~menu.text_align_breakpoint') : '');
        $attrs['class'][] = 'uk-flex-' . $config('~menu.text_align_fallback');
    } elseif ($type == 'nav' && $config('~menu.text_align') == 'center') {
        $attrs['class'][] = 'uk-nav-center';
    }
}

// Builder
if ($type !== 'nav') {

    // Store menu config in case builder renders a menu module/widget
    $menuConfig = $config('~menu');

    $builder = app(Builder::class);
    foreach ($items as $item) {
        if ($content = $config("~theme.menu.items.{$item->id}.content")) {
            if ($config($recursionKey = "builderRecursion{$item->id}")) {
                continue;
            }

            $config->set($recursionKey, true);

            $item->builder = $builder->render(
                json_encode($content),
                ['prefix' => "menu-item-{$item->id}"]
            ) ?: null;

            $config->del($recursionKey);
        }
    }

    $menuConfig = $config->set('~menu', $menuConfig);
}

// Dropnav
if (in_array($type, ['subnav', 'iconnav'])) {
    $dropnav_attrs = [
        'boundary' => 'false', // Has to be a string
        'container' => $config("$navbar.sticky") && in_array($position, ['navbar', 'navbar-split']) ? '.tm-header > [uk-sticky]' : 'body',
    ];

    $attrs['uk-dropnav'] = json_encode(array_filter($dropnav_attrs));
}

// Scrollspy nav
if ($scrollspyNav && array_any($items, fn($item) => str_contains((string) $item->url, '#'))) {
    $config->set('~menu.scrollspyNav', true);
    $attrs['uk-scrollspy-nav'] = 'closest: li; scroll: true;';

    if ($type !== 'nav') {
        $attrs['uk-scrollspy-nav'] .= ' target: ' . (!empty($isSplitMenu) ? '!.uk-navbar .uk-navbar-nav ' : '') . '> * > a[href];';
    }
}

?>

<ul<?= $this->attrs($attrs) ?>>
    <?= $view("~theme/templates/menu/{$type}", ['items' => $items, 'level' => 1]) ?>
</ul>
