<?php
declare(strict_types=1);

if (!defined('ABSPATH')) { exit; }

/**
 * Nav Menu element renderer (shared).
 *
 * Phase 1, step 18.
 *
 * Pre-extraction this case was effectively BROKEN on the frontend:
 *
 *   - Frontend referenced `$displayContent` — a variable that doesn't
 *     exist in this scope (copy-paste artifact). The check
 *     `if (empty(trim(wp_strip_all_tags($displayContent)))) break;`
 *     always fired because $displayContent was null, so the case
 *     broke out before rendering anything. On standalone (where
 *     wp_strip_all_tags doesn't even exist) the whole block crashed.
 *   - Frontend's render path used wp_nav_menu — WordPress-only,
 *     can't work in standalone.
 *
 * Editor used a different approach: items array from settings, or
 * wp_get_nav_menu_items lookup when source='wp_menu'. This works
 * everywhere and is now canonical.
 *
 * Unification adopts the editor's approach. Frontend renders the
 * same items list (per source setting) using inline `<a>` tags.
 * The visible difference for live pages: nav_menu blocks that
 * previously rendered empty now actually render their items.
 *
 * Pre-extraction defaults that drifted (resolved to editor canonical):
 *   - gap: 24 (frontend) / 24 (editor) — matched
 *   - font_size: 15 (frontend) / 16 (editor) → 16
 *   - text_color: #1d2327 (both)
 *   - hover_color: #666666 (both)
 */
function impulse_element_render_nav_menu($el, array $settings, string $context): string {
    if (is_object($el)) $el = (array) $el;
    $isEditor = ($context === 'editor');

    $read = function (string $key, $default) use ($settings, $isEditor) {
        if ($isEditor && function_exists('impulse_get_responsive')) {
            return impulse_get_responsive($settings, $key, $default);
        }
        return $settings[$key] ?? $default;
    };

    // ── Visibility check (frontend only) ─────────────────────────
    if (!$isEditor && function_exists('impulse_check_visibility') && !impulse_check_visibility($settings)) {
        return '';
    }

    $source     = (string) ($settings['source']     ?? 'wp_menu');
    $menuSlug   = (string) ($settings['menu_slug']  ?? ($settings['menu_id'] ?? ''));
    $layout     = (string) ($settings['layout']     ?? 'horizontal');
    $align      = (string) ($settings['align']      ?? 'center');
    $gap        = intval($read('gap',       24));
    $fontSize   = intval($read('font_size', 16));
    $textColor  = (string) ($settings['text_color']  ?? '#1d2327');
    $hoverColor = (string) ($settings['hover_color'] ?? '#666666');

    $items = $settings['items'] ?? [];
    if (is_string($items)) $items = json_decode($items, true) ?: [];
    if (empty($items)) {
        $items = [
            ['label' => 'Home',    'url' => function_exists('home_url') ? home_url('/') : '/'],
            ['label' => 'About',   'url' => '/about'],
            ['label' => 'Contact', 'url' => '/contact'],
        ];
    }

    $justifyMap = ['left' => 'flex-start', 'center' => 'center', 'right' => 'flex-end'];
    $justify    = $justifyMap[$align] ?? 'center';
    $isVertical = ($layout === 'vertical');

    $containerStyle = 'display:flex;gap:' . $gap . 'px;';
    if ($isVertical) {
        $alignItems = $align === 'right' ? 'flex-end' : ($align === 'center' ? 'center' : 'flex-start');
        $containerStyle .= 'flex-direction:column;align-items:' . $alignItems . ';';
    } else {
        $containerStyle .= 'justify-content:' . $justify . ';';
    }

    // ── Animation + visibility classes (frontend only) ──────────
    $animAttrs = (!$isEditor && function_exists('impulse_get_animation_attrs'))
        ? impulse_get_animation_attrs($settings)
        : ['class' => '', 'style' => ''];
    $navClass = 'impulse-nav-menu';
    if (!empty($animAttrs['class'])) $navClass .= ' ' . $animAttrs['class'];
    if (!$isEditor && function_exists('impulse_get_visibility_classes')) {
        $vc = impulse_get_visibility_classes($settings);
        if ($vc !== '') $navClass .= ' ' . $vc;
    }
    $navStyleVal = !empty($animAttrs['style']) ? (string) $animAttrs['style'] : '';

    // ── Compose HTML ─────────────────────────────────────────────
    ob_start();

    // Editor: visibility badge.
    $visBadge = ($isEditor && function_exists('impulse_visibility_badge')) ? impulse_visibility_badge($settings) : '';
    if ($visBadge) echo '<div style="position:relative">' . wp_kses($visBadge, impulse_svg_allowed());

    // Inline CSS for link colors + hover.
    if (function_exists('wp_add_inline_style')) {
        wp_add_inline_style('instinctor-page-inline',
              '.impulse-nav-menu a{font-size:' . $fontSize . 'px;color:' . esc_attr($textColor) . ';text-decoration:none;transition:color 0.2s}'
            . '.impulse-nav-menu a:hover{color:' . esc_attr($hoverColor) . '}'
            . '.impulse-nav-menu li{list-style:none}'
        );
    }

    echo '<nav class="' . esc_attr($navClass) . '" style="' . esc_attr($containerStyle) . '"' . ($navStyleVal !== '' ? ' style="' . esc_attr($navStyleVal) . '"' : '') . '>';

    // Render items.
    $rendered = false;
    if ($source === 'wp_menu' && $menuSlug !== '' && function_exists('wp_get_nav_menu_items')) {
        $menuItems = wp_get_nav_menu_items($menuSlug);
        if (is_array($menuItems) && !empty($menuItems)) {
            foreach ($menuItems as $item) {
                if (intval($item->menu_item_parent ?? 0) !== 0) continue; // top-level only
                $url   = (string) ($item->url ?? '');
                $title = (string) ($item->title ?? '');
                echo '<a href="' . esc_url($url) . '">' . esc_html($title) . '</a>';
                $rendered = true;
            }
        } elseif ($isEditor) {
            echo '<span style="color:#999;font-style:italic">Menu is empty</span>';
            $rendered = true;
        }
    }

    // Fall back to settings items (or render them directly when source != wp_menu).
    if (!$rendered) {
        foreach ($items as $item) {
            $url   = (string) ($item['url']   ?? '#');
            $label = (string) ($item['label'] ?? 'Link');
            echo '<a href="' . esc_url($url) . '">' . esc_html($label) . '</a>';
        }
    }

    echo '</nav>';
    if ($visBadge) echo '</div>';

    return ob_get_clean();
}
