<?php
/**
 * Template Functions for Blog Over
 *
 * @package Blog_Over
 */

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

/**
 * Display Site Branding (Logo / Title / Both)
 *
 * Uses WordPress native "Display Site Title and Tagline" setting:
 *   - Title ON  + Logo exists  → Combined branding (stacked or inline layout)
 *   - Title ON  + No logo      → Title + tagline only
 *   - Title OFF + Logo exists  → Logo only
 *   - Title OFF + No logo      → Site title as minimal fallback (accessibility)
 *
 * @since 0.0.1
 * @since 0.0.9 Switched from custom toggle to WordPress native display_header_text().
 */
function blog_over_site_branding()
{
    $show_title = display_header_text();
    $has_logo   = has_custom_logo();
    $layout     = get_theme_mod('blog_over_logo_title_layout', 'stacked');

    if ($show_title && $has_logo) {
        // Combined branding: Logo + Title (stacked or inline)
        $layout_class = 'blog-over-branding-' . sanitize_html_class($layout);
        ?>
        <div class="blog-over-branding-combined <?php echo esc_attr($layout_class); ?>">
            <div class="blog-over-branding-logo">
                <?php the_custom_logo(); ?>
            </div>
            <div class="blog-over-branding-text">
                <?php if (is_front_page() || is_home()) : ?>
                    <h1 class="site-title"><a href="<?php echo esc_url(home_url('/')); ?>" rel="home"><?php bloginfo('name'); ?></a></h1>
                <?php else : ?>
                    <p class="site-title"><a href="<?php echo esc_url(home_url('/')); ?>" rel="home"><?php bloginfo('name'); ?></a></p>
                <?php endif;

                $description = get_bloginfo('description', 'display');
                if ($description || is_customize_preview()) :
                    ?>
                    <p class="site-description"><?php echo esc_html($description); ?></p>
                <?php endif; ?>
            </div>
        </div>
        <?php
    } elseif ($has_logo && !$show_title) {
        // Logo only — title is hidden
        the_custom_logo();
    } else {
        // Title + tagline only (no logo, or fallback)
        if (is_front_page() || is_home()) : ?>
            <h1 class="site-title"><a href="<?php echo esc_url(home_url('/')); ?>" rel="home"><?php bloginfo('name'); ?></a></h1>
        <?php else : ?>
            <p class="site-title"><a href="<?php echo esc_url(home_url('/')); ?>" rel="home"><?php bloginfo('name'); ?></a></p>
        <?php endif;

        $description = get_bloginfo('description', 'display');
        if ($description || is_customize_preview()) :
            ?>
            <p class="site-description"><?php echo esc_html($description); ?></p>
        <?php endif;
    }
}

/**
 * Active callback for the Branding Layout radio-buttonset.
 * Only show when WordPress "Display Site Title and Tagline" is ON
 * AND a custom logo is uploaded.
 *
 * @since 0.0.9
 * @return bool
 */
function blog_over_branding_layout_active()
{
    return display_header_text() && has_custom_logo();
}

/**
 * Render the Dark/Light Mode Toggle Button
 *
 * Outputs the appropriate toggle HTML based on the
 * 'blog_over_toggle_style' Customizer setting.
 *
 * Styles:
 *  - 'icon'    : Classic icon button (original design)
 *  - 'pill'    : Modern pill/slider toggle with sun/moon (default for new installs)
 *  - 'labeled' : Pill toggle with Light/Dark text labels
 *
 * All styles use the .blog-over-theme-toggle class so existing
 * JS event listeners continue to work without modification.
 *
 * @since 0.0.9
 */
function blog_over_render_theme_toggle()
{
    $style = get_theme_mod('blog_over_toggle_style', 'icon');

    echo '<div class="blog-over-theme-toggle-wrapper">';

    switch ($style) {
        case 'pill':
            ?>
            <button class="blog-over-theme-toggle blog-over-toggle-pill"
                    aria-label="<?php esc_attr_e('Toggle dark mode', 'blog-over'); ?>"
                    aria-pressed="false">
                <span class="blog-over-toggle-track">
                    <span class="blog-over-toggle-thumb">
                        <i class="fas fa-sun" aria-hidden="true"></i>
                        <i class="fas fa-moon" aria-hidden="true"></i>
                    </span>
                </span>
            </button>
            <?php
            break;

        case 'labeled':
            ?>
            <button class="blog-over-theme-toggle blog-over-toggle-labeled"
                    aria-label="<?php esc_attr_e('Toggle dark mode', 'blog-over'); ?>"
                    aria-pressed="false">
                <span class="blog-over-toggle-track">
                    <span class="blog-over-toggle-label blog-over-toggle-label-light">
                        <i class="fas fa-sun" aria-hidden="true"></i>
                        <?php esc_html_e('Light', 'blog-over'); ?>
                    </span>
                    <span class="blog-over-toggle-label blog-over-toggle-label-dark">
                        <i class="fas fa-moon" aria-hidden="true"></i>
                        <?php esc_html_e('Dark', 'blog-over'); ?>
                    </span>
                    <span class="blog-over-toggle-thumb"></span>
                </span>
            </button>
            <?php
            break;

        case 'icon':
        default:
            ?>
            <button class="blog-over-theme-toggle blog-over-toggle-icon"
                    aria-label="<?php esc_attr_e('Toggle dark mode', 'blog-over'); ?>"
                    aria-pressed="false">
                <i class="fas fa-moon"></i>
            </button>
            <?php
            break;
    }

    echo '</div>';
}


/**
 * Display Primary Menu with Custom Walker
 */
function blog_over_primary_menu()
{
    wp_nav_menu(array(
        'theme_location' => 'blog-over-main-menu',
        'menu_id' => 'primary-menu',
        'menu_class' => 'blog-over-primary-menu',
        'container' => false,
        'walker' => new Blog_Over_Nav_Walker(),
        'fallback_cb' => 'blog_over_menu_fallback',
    ));
}

/**
 * Menu Fallback
 */
function blog_over_menu_fallback()
{
    echo '<ul class="blog-over-primary-menu"><li><a href="' . esc_url(admin_url('nav-menus.php')) . '">' . esc_html__('Add a Menu', 'blog-over') . '</a></li></ul>';
}

/**
 * Display Mobile Menu Toggle Button
 */
function blog_over_mobile_toggle()
{
    ?>
    <button class="blog-over-mobile-toggle" aria-controls="blog-over-mobile-menu" aria-expanded="false"
        aria-label="<?php esc_attr_e('Open menu', 'blog-over'); ?>">
        <span class="bar"></span>
        <span class="bar"></span>
        <span class="bar"></span>
        <span class="blog-over-sr-only"><?php esc_html_e('Menu', 'blog-over'); ?></span>
    </button>
    <?php
}

/**
 * Split Menu for Layout 3
 * Displays first half of menu items on one side, second half on the other
 * Now with FULL support for unlimited nested submenus (3-4+ levels)
 */
function blog_over_split_menu($position = 'left')
{
    $menu_locations = get_nav_menu_locations();

    if (!isset($menu_locations['blog-over-main-menu'])) {
        return;
    }

    $menu_id = $menu_locations['blog-over-main-menu'];
    $menu_items = wp_get_nav_menu_items($menu_id);

    if (!$menu_items) {
        return;
    }

    // Get only top-level items
    $top_items = array_filter($menu_items, function ($item) {
        return $item->menu_item_parent == 0;
    });

    $top_items = array_values($top_items);
    $total = count($top_items);
    $half = ceil($total / 2);

    if ('left' === $position) {
        $items_to_show = array_slice($top_items, 0, $half);
    } else {
        $items_to_show = array_slice($top_items, $half);
    }

    if (empty($items_to_show)) {
        return;
    }

    echo '<ul class="blog-over-primary-menu">';

    foreach ($items_to_show as $item) {
        blog_over_render_split_menu_item($item, $menu_items);
    }

    echo '</ul>';
}

/**
 * Recursively render a menu item and its children (unlimited depth)
 * 
 * @param object $item Current menu item
 * @param array $all_items All menu items array
 * @param int $depth Current depth level (0 = top level)
 */
function blog_over_render_split_menu_item($item, $all_items, $depth = 0)
{
    $classes = implode(' ', $item->classes);
    $classes .= ' blog-over-menu-item';

    if ($depth === 0) {
        $classes .= ' blog-over-menu-item-top';
    } else {
        $classes .= ' blog-over-menu-item-child';
    }

    // Check if has children
    $children = array();
    foreach ($all_items as $potential_child) {
        if ($potential_child->menu_item_parent == $item->ID) {
            $children[] = $potential_child;
        }
    }

    $has_children = !empty($children);

    if ($has_children) {
        $classes .= ' blog-over-has-dropdown';
    }

    echo '<li class="' . esc_attr($classes) . '">';
    echo '<a href="' . esc_url($item->url) . '" class="blog-over-menu-link">' . esc_html($item->title) . '</a>';

    if ($has_children) {
        echo '<button class="blog-over-dropdown-toggle" aria-label="' . esc_attr__('Expand child menu', 'blog-over') . '" aria-expanded="false"><span class="blog-over-dropdown-icon"></span></button>';
        echo '<ul class="blog-over-sub-menu blog-over-dropdown" aria-hidden="true">';

        // Recursively render each child (this enables unlimited levels!)
        foreach ($children as $child) {
            blog_over_render_split_menu_item($child, $all_items, $depth + 1);
        }

        echo '</ul>';
    }

    echo '</li>';
}

/**
 * Check if page header should be displayed
 * 
 * @return bool True if page header should be displayed
 */
function blog_over_has_page_header()
{
    // Check if page header is enabled globally
    $enabled = get_theme_mod('blog_over_page_header_enable', true);
    if (!$enabled) {
        return false;
    }

    // Get pages where Page Header should be shown
    $show_on = get_theme_mod('blog_over_page_header_show_on', array('single', 'page', 'archive', 'search', '404'));
    if (!is_array($show_on)) {
        $show_on = array();
    }

    // Check current page type against the show_on array
    // Homepage (static front page)
    if (is_front_page() && !is_home()) {
        return in_array('home', $show_on);
    }

    // Blog Posts Page (posts page set in Settings > Reading)
    if (is_home()) {
        return in_array('posts_page', $show_on);
    }

    // Single Posts
    if (is_single()) {
        return in_array('single', $show_on);
    }

    // Pages (but not front page)
    if (is_page() && !is_front_page()) {
        return in_array('page', $show_on);
    }

    // Archives (Category, Tag, Author, Date)
    if (is_archive() || is_category() || is_tag() || is_author() || is_date()) {
        return in_array('archive', $show_on);
    }

    // Search Results
    if (is_search()) {
        return in_array('search', $show_on);
    }

    // 404 Page
    if (is_404()) {
        return in_array('404', $show_on);
    }

    return false;
}

/**
 * Get the page title for page header
 * 
 * @return string The page title
 */
function blog_over_get_page_title()
{
    $title = '';

    if (is_home() && !is_front_page()) {
        $title = single_post_title('', false);
        if (!$title) {
            $title = esc_html__('Blog', 'blog-over');
        }
    } elseif (is_single()) {
        $title = get_the_title();
    } elseif (is_page()) {
        $title = get_the_title();
    } elseif (is_category()) {
        $title = single_cat_title('', false);
    } elseif (is_tag()) {
        $title = single_tag_title('', false);
    } elseif (is_author()) {
        $title = get_the_author();
    } elseif (is_search()) {
        /* translators: %s: search query */
        $title = sprintf(esc_html__('Search Results for: %s', 'blog-over'), get_search_query());
    } elseif (is_404()) {
        $title = esc_html__('Page Not Found', 'blog-over');
    } elseif (is_archive()) {
        $title = get_the_archive_title();
    }

    return apply_filters('blog_over_page_title', $title);
}

/**
 * Display Page Header with Title and optional Breadcrumb
 */
function blog_over_page_header()
{
    // Check if page header is enabled
    if (!blog_over_has_page_header()) {
        return;
    }

    $alignment = get_theme_mod('blog_over_page_header_alignment', 'center');
    $breadcrumb_position = get_theme_mod('blog_over_breadcrumb_position', 'below-header');
    $bg_image = get_theme_mod('blog_over_page_header_bg_image', '');
    $bg_color = get_theme_mod('blog_over_page_header_bg_color', '');
    $theme_skin = get_theme_mod('blog_over_theme_skin', 'light');
    $use_featured = get_theme_mod('blog_over_page_header_use_featured', false);
    $show_title = get_theme_mod('blog_over_page_header_show_title', true);

    // For single posts, check title position setting
    if (is_single()) {
        $title_position = get_theme_mod('blog_over_single_title_position', 'in-page-header');
        if ($title_position === 'in-content') {
            $show_title = false; // Title will be shown in content area instead
        }
    }

    // Check if we have breadcrumb to show
    $show_breadcrumb_in_header = ($breadcrumb_position === 'in-page-header' && blog_over_has_breadcrumbs());

    // If no title and no breadcrumb, don't render the header
    if (!$show_title && !$show_breadcrumb_in_header) {
        return;
    }

    // Build inline styles
    $style_parts = array();
    $has_bg_image = false;
    $using_featured = false;

    // Background Priority Logic: 1. Custom Image > 2. Featured Image > 3. Custom Color > 4. Skin Default
    if ($bg_image) {
        // [1] Custom background image takes top priority
        $style_parts[] = 'background-image: url(' . esc_url($bg_image) . ')';
        $has_bg_image = true;
    } elseif ($use_featured && (is_single() || is_page())) {
        // [2] Featured image if enabled and custom image is not set
        $post_id = get_queried_object_id();
        if (has_post_thumbnail($post_id)) {
            $featured_img_url = get_the_post_thumbnail_url($post_id, 'full');
            if ($featured_img_url) {
                $style_parts[] = 'background-image: url(' . esc_url($featured_img_url) . ')';
                $has_bg_image = true;
                $using_featured = true;

                // Set global flag to avoid double display in content
                global $blog_over_featured_used_as_header_bg;
                $blog_over_featured_used_as_header_bg = true;
            }
        }
    }

    // Background color (only if explicitly set in Customizer)
    if (!empty($bg_color)) {
        $style_parts[] = 'background-color: ' . esc_attr($bg_color);
    }
    // If no image and no custom color, background will be transparent (default)

    $style = !empty($style_parts) ? implode('; ', $style_parts) . ';' : '';

    $classes = 'blog-over-page-header';
    $classes .= ' blog-over-page-header-align-' . esc_attr($alignment);
    if ($has_bg_image) {
        $classes .= ' blog-over-page-header-has-bg';
        if ($using_featured) {
            $classes .= ' blog-over-page-header-using-featured';
        }
    }

    $title = blog_over_get_page_title();
    $title_color = get_theme_mod('blog_over_page_header_text_color', '');

    echo '<div class="' . esc_attr($classes) . '"' . ($style ? ' style="' . esc_attr($style) . '"' : '') . '>';
    echo '<div class="blog-over-container">';
    echo '<div class="blog-over-page-header-wrapper">';

    // For single posts with title in page header, show category and meta too
    $show_single_meta_in_header = false;
    if (is_single()) {
        $title_position = get_theme_mod('blog_over_single_title_position', 'in-page-header');
        if ($title_position === 'in-page-header') {
            $show_single_meta_in_header = true;
        }
    }

    // Category badges for single posts (before title)
    if ($show_single_meta_in_header && $show_title) {
        $elements = get_theme_mod('blog_over_single_elements', array('category', 'featured_image', 'tags', 'share', 'author_box', 'post_navigation', 'related_posts', 'comments'));
        if (in_array('category', $elements)) {
            $categories = get_the_category();
            if (!empty($categories)) {
                echo '<div class="blog-over-single-category">';
                foreach ($categories as $cat) {
                    echo '<a href="' . esc_url(get_category_link($cat->term_id)) . '">' . esc_html($cat->name) . '</a>';
                }
                echo '</div>';
            }
        }
    }

    // Page title (only if show_title is true and title exists)
    if ($show_title && !empty($title)) {
        $title_style = $title_color ? ' style="color: ' . esc_attr($title_color) . ';"' : '';
        echo '<h1 class="blog-over-page-title"' . $title_style . '>' . wp_kses_post($title) . '</h1>';
    }

    // Post meta for single posts (after title)
    if ($show_single_meta_in_header && $show_title) {
        $elements = get_theme_mod('blog_over_single_elements', array('category', 'featured_image', 'tags', 'share', 'author_box', 'post_navigation', 'related_posts', 'comments'));
        if (in_array('meta', $elements)) {
            $meta_elements = get_theme_mod('blog_over_single_meta_elements', array('author', 'date', 'comments'));
        if (!empty($meta_elements) || has_action('blog_over_after_single_header_meta')) {
            echo '<div class="blog-over-single-meta">';
            if (!empty($meta_elements)) {
                foreach ($meta_elements as $meta) {
                    switch ($meta) {
                        case 'author':
                            // Get author info from the current post
                            $post_obj = get_post();
                            if ($post_obj) {
                                $author_id = $post_obj->post_author;
                                $author_info = get_userdata($author_id);
                                $author_name = $author_info ? $author_info->display_name : '';
                                if (empty($author_name)) {
                                    $author_name = $author_info ? $author_info->user_login : __('Unknown', 'blog-over');
                                }
                                echo '<span class="blog-over-meta-author">';
                                echo '<img src="' . esc_url(get_avatar_url($author_id, array('size' => 32))) . '" alt="' . esc_attr($author_name) . '" class="blog-over-author-avatar-small">';
                                echo '<a href="' . esc_url(get_author_posts_url($author_id)) . '">' . esc_html($author_name) . '</a>';
                                echo '</span>';
                            }
                            break;
                        case 'date':
                            echo '<span class="blog-over-meta-date">';
                            echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg>';
                            echo '<a href="' . esc_url(get_permalink()) . '">' . esc_html(get_the_date()) . '</a>';
                            echo '</span>';
                            break;
                        case 'comments':
                            if (comments_open() || get_comments_number()) {
                                $comments_count = get_comments_number();
                                if ($comments_count > 0) {
                                    echo '<span class="blog-over-meta-comments">';
                                    echo '<a href="' . esc_url(get_comments_link()) . '">';
                                    /* translators: %s: comment count */
                                    echo sprintf(_n('%s Comment', '%s Comments', $comments_count, 'blog-over'), number_format_i18n($comments_count));
                                    echo '</a></span>';
                                }
                            }
                            break;
                        default:
                            do_action('blog_over_render_single_header_meta_item', $meta);
                            break;
                    }
                }
            }
            do_action('blog_over_after_single_header_meta');
            echo '</div>';
        }
        }
    }

    // Breadcrumb inside page header (if position is in-page-header)
    if ($show_breadcrumb_in_header) {
        blog_over_output_breadcrumb_trail();
    }

    echo '</div>'; // .blog-over-page-header-wrapper
    echo '</div>'; // .blog-over-container
    echo '</div>'; // .blog-over-page-header
}

/**
 * Output just the breadcrumb trail (without wrapper)
 */
function blog_over_output_breadcrumb_trail()
{
    $type = get_theme_mod('blog_over_breadcrumb_type', 'default');
    $alignment = get_theme_mod('blog_over_breadcrumb_alignment', 'left');
    $separator = blog_over_get_breadcrumb_separator();

    // Check for third-party breadcrumbs
    if ($type === 'navxt' && function_exists('bcn_display')) {
        echo '<nav class="blog-over-breadcrumb blog-over-breadcrumb-align-' . esc_attr($alignment) . '" aria-label="Breadcrumb"><div class="blog-over-breadcrumb-inner">';
        bcn_display();
        echo '</div></nav>';
        return;
    }

    if ($type === 'yoast' && function_exists('yoast_breadcrumb')) {
        yoast_breadcrumb('<nav class="blog-over-breadcrumb blog-over-breadcrumb-align-' . esc_attr($alignment) . '" aria-label="Breadcrumb"><div class="blog-over-breadcrumb-inner">', '</div></nav>');
        return;
    }

    if ($type === 'rankmath' && function_exists('rank_math_the_breadcrumbs')) {
        echo '<nav class="blog-over-breadcrumb blog-over-breadcrumb-align-' . esc_attr($alignment) . '" aria-label="Breadcrumb"><div class="blog-over-breadcrumb-inner">';
        rank_math_the_breadcrumbs();
        echo '</div></nav>';
        return;
    }

    // Default breadcrumb
    echo '<nav class="blog-over-breadcrumb blog-over-breadcrumb-align-' . esc_attr($alignment) . '" aria-label="Breadcrumb">';
    echo '<ol class="blog-over-breadcrumb-list" data-separator="' . esc_attr($separator) . '">';

    echo '<li class="blog-over-breadcrumb-item"><a href="' . esc_url(home_url('/')) . '">' . esc_html__('Home', 'blog-over') . '</a></li>';

    if (is_category() || is_single()) {
        $categories = get_the_category();
        if (!empty($categories)) {
            echo '<li class="blog-over-breadcrumb-item"><a href="' . esc_url(get_category_link($categories[0]->term_id)) . '">' . esc_html($categories[0]->name) . '</a></li>';
        }
    }

    if (is_single()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(get_the_title()) . '</li>';
    } elseif (is_page()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(get_the_title()) . '</li>';
    } elseif (is_category()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(single_cat_title('', false)) . '</li>';
    } elseif (is_tag()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(single_tag_title('', false)) . '</li>';
    } elseif (is_author()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(get_the_author()) . '</li>';
    } elseif (is_search()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html__('Search Results', 'blog-over') . '</li>';
    } elseif (is_404()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html__('404 Not Found', 'blog-over') . '</li>';
    } elseif (is_archive()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(get_the_archive_title()) . '</li>';
    }

    echo '</ol>';
    echo '</nav>';
}

/**
 * Check if breadcrumbs should be displayed on current page
 * 
 * @return bool True if breadcrumbs should be displayed
 */
function blog_over_has_breadcrumbs()
{
    // Check if breadcrumbs are enabled globally
    $enabled = get_theme_mod('blog_over_breadcrumb_enable', true);
    if (!$enabled) {
        return false;
    }

    // Check if disabled on specific page types
    $hide_on = get_theme_mod('blog_over_breadcrumb_hide_on', array());
    if (!is_array($hide_on)) {
        $hide_on = array();
    }

    // Check each condition
    if (in_array('home', $hide_on) && is_front_page()) {
        return false;
    }
    if (in_array('posts', $hide_on) && is_home()) {
        return false;
    }
    if (in_array('single', $hide_on) && is_single()) {
        return false;
    }
    if (in_array('page', $hide_on) && is_page() && !is_front_page()) {
        return false;
    }
    if (in_array('archive', $hide_on) && (is_archive() || is_category() || is_tag() || is_author() || is_date())) {
        return false;
    }
    if (in_array('search', $hide_on) && is_search()) {
        return false;
    }
    if (in_array('404', $hide_on) && is_404()) {
        return false;
    }

    // Don't show on front page by default
    if (is_front_page()) {
        return false;
    }

    return true;
}

/**
 * Check if breadcrumb container (below header) should be rendered
 * Returns false when breadcrumb is positioned inside page header
 * 
 * @return bool True if breadcrumb container should be rendered
 */
function blog_over_should_render_breadcrumb_container()
{
    // Check if breadcrumbs are enabled and should display
    if (!blog_over_has_breadcrumbs()) {
        return false;
    }

    // If position is in-page-header, don't render standalone container
    $position = get_theme_mod('blog_over_breadcrumb_position', 'below-header');
    if ($position === 'in-page-header') {
        return false;
    }

    return true;
}

/**
 * Get breadcrumb separator based on setting
 * 
 * @return string Separator character
 */
function blog_over_get_breadcrumb_separator()
{
    $separator = get_theme_mod('blog_over_breadcrumb_separator', 'chevron');

    switch ($separator) {
        case 'arrow':
            return '→';
        case 'slash':
            return '/';
        case 'pipe':
            return '|';
        case 'chevron':
        default:
            return '›';
    }
}

/**
 * Display Breadcrumb Navigation
 */
function blog_over_breadcrumb()
{
    // Check if breadcrumb should be displayed
    if (!blog_over_has_breadcrumbs()) {
        return;
    }

    // If position is in-page-header, breadcrumb is shown inside page header instead
    $position = get_theme_mod('blog_over_breadcrumb_position', 'below-header');
    if ($position === 'in-page-header') {
        return;
    }

    $type = get_theme_mod('blog_over_breadcrumb_type', 'default');
    $alignment = get_theme_mod('blog_over_breadcrumb_alignment', 'left');
    $bg_image = get_theme_mod('blog_over_breadcrumb_bg_image', '');
    $bg_color = get_theme_mod('blog_over_breadcrumb_bg_color', '');
    $theme_skin = get_theme_mod('blog_over_theme_skin', 'light');

    // Build inline styles for wrapper
    $style_parts = array();
    $has_bg_image = false;

    // Priority: Image > Custom Color > Theme Skin Default
    if ($bg_image) {
        $style_parts[] = 'background-image: url(' . esc_url($bg_image) . ')';
        $style_parts[] = 'background-size: cover';
        $style_parts[] = 'background-position: center';
        $has_bg_image = true;
    } else {
        // No image - apply background color
        if (!empty($bg_color)) {
            // Use custom color from customizer
            $style_parts[] = 'background-color: ' . esc_attr($bg_color);
        } else {
            // Use theme skin default
            $default_bg = ($theme_skin === 'dark') ? '#1e293b' : '#f1f5f9';
            $style_parts[] = 'background-color: ' . $default_bg;
        }
    }

    $style = !empty($style_parts) ? ' style="' . esc_attr(implode('; ', $style_parts)) . ';"' : '';
    $wrapper_class = 'blog-over-breadcrumb-wrapper' . ($has_bg_image ? ' blog-over-breadcrumb-has-bg' : '');

    // Start wrapper div with inline styles
    echo '<div class="' . esc_attr($wrapper_class) . '"' . $style . '>';
    echo '<div class="blog-over-container">';

    // Check for third-party breadcrumbs
    if ($type === 'navxt' && function_exists('bcn_display')) {
        echo '<nav class="blog-over-breadcrumb blog-over-breadcrumb-align-' . esc_attr($alignment) . '" aria-label="Breadcrumb"><div class="blog-over-breadcrumb-inner">';
        bcn_display();
        echo '</div></nav>';
        echo '</div></div>'; // Close container and wrapper
        return;
    }

    if ($type === 'yoast' && function_exists('yoast_breadcrumb')) {
        yoast_breadcrumb('<nav class="blog-over-breadcrumb blog-over-breadcrumb-align-' . esc_attr($alignment) . '" aria-label="Breadcrumb"><div class="blog-over-breadcrumb-inner">', '</div></nav>');
        echo '</div></div>'; // Close container and wrapper
        return;
    }

    if ($type === 'rankmath' && function_exists('rank_math_the_breadcrumbs')) {
        echo '<nav class="blog-over-breadcrumb blog-over-breadcrumb-align-' . esc_attr($alignment) . '" aria-label="Breadcrumb"><div class="blog-over-breadcrumb-inner">';
        rank_math_the_breadcrumbs();
        echo '</div></nav>';
        echo '</div></div>'; // Close container and wrapper
        return;
    }

    // Get separator
    $separator = blog_over_get_breadcrumb_separator();

    // Default breadcrumb
    echo '<nav class="blog-over-breadcrumb blog-over-breadcrumb-align-' . esc_attr($alignment) . '" aria-label="Breadcrumb">';
    echo '<ol class="blog-over-breadcrumb-list" data-separator="' . esc_attr($separator) . '">';

    echo '<li class="blog-over-breadcrumb-item"><a href="' . esc_url(home_url('/')) . '">' . esc_html__('Home', 'blog-over') . '</a></li>';

    if (is_category() || is_single()) {
        $categories = get_the_category();
        if (!empty($categories)) {
            echo '<li class="blog-over-breadcrumb-item"><a href="' . esc_url(get_category_link($categories[0]->term_id)) . '">' . esc_html($categories[0]->name) . '</a></li>';
        }
    }

    if (is_single()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(get_the_title()) . '</li>';
    } elseif (is_page()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(get_the_title()) . '</li>';
    } elseif (is_category()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(single_cat_title('', false)) . '</li>';
    } elseif (is_tag()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(single_tag_title('', false)) . '</li>';
    } elseif (is_author()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(get_the_author()) . '</li>';
    } elseif (is_search()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html__('Search Results', 'blog-over') . '</li>';
    } elseif (is_404()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html__('404 Not Found', 'blog-over') . '</li>';
    } elseif (is_archive()) {
        echo '<li class="blog-over-breadcrumb-item current">' . esc_html(get_the_archive_title()) . '</li>';
    }

    echo '</ol>';
    echo '</nav>';
    echo '</div></div>'; // Close container and wrapper
}

/**
 * Display Related Posts
 */
function blog_over_related_posts()
{
    // Check if enabled
    $enabled = get_theme_mod('blog_over_enable_related', true);
    if (!$enabled) {
        return;
    }

    $post_id = get_the_ID();

    // Get settings from Kirki customizer
    $title = get_theme_mod('blog_over_related_title', __('Related Posts', 'blog-over'));
    $count = get_theme_mod('blog_over_related_count', 3);
    $related_by = get_theme_mod('blog_over_related_by', 'category');
    $columns = get_theme_mod('blog_over_related_columns', '3');

    // Post Card Elements (sortable - includes thumbnail)
    $entry_elements = get_theme_mod('blog_over_related_entry_elements', array('thumbnail', 'meta', 'title', 'excerpt'));

    // Meta elements (sortable - includes comments)
    $meta_elements = get_theme_mod('blog_over_related_meta_elements', array('author', 'date', 'category'));

    // Excerpt length
    $excerpt_length = get_theme_mod('blog_over_related_excerpt_length', 12);

    // Build query args based on "related by" setting
    $args = array(
        'post__not_in' => array($post_id),
        'posts_per_page' => $count,
        'ignore_sticky_posts' => 1,
    );

    switch ($related_by) {
        case 'tag':
            $tags = get_the_tags($post_id);
            if (empty($tags)) {
                return;
            }
            $tag_ids = array();
            foreach ($tags as $tag) {
                $tag_ids[] = $tag->term_id;
            }
            $args['tag__in'] = $tag_ids;
            break;

        case 'random':
            $args['orderby'] = 'rand';
            break;

        case 'custom_category':
            $custom_cats = get_theme_mod('blog_over_related_custom_cats', array());
            if (empty($custom_cats)) {
                // Fallback to current post category if no custom categories selected
                $categories = get_the_category($post_id);
                if (empty($categories)) {
                    return;
                }
                $category_ids = array();
                foreach ($categories as $cat) {
                    $category_ids[] = $cat->term_id;
                }
                $args['category__in'] = $category_ids;
            } else {
                // Convert slug-based or ID-based selections to IDs for category__in.
                $category_ids = array();
                foreach ((array) $custom_cats as $cat_val) {
                    if (is_numeric($cat_val)) {
                        // Backward compatibility: old installs may still store numeric IDs.
                        $category_ids[] = intval($cat_val);
                    } else {
                        // Slug-based lookup (preferred).
                        $cat_obj = get_category_by_slug($cat_val);
                        if ($cat_obj) {
                            $category_ids[] = $cat_obj->term_id;
                        }
                    }
                }
                if (!empty($category_ids)) {
                    $args['category__in'] = $category_ids;
                }
            }
            break;

        case 'custom_tag':
            $custom_tags = get_theme_mod('blog_over_related_custom_tags', array());
            if (empty($custom_tags)) {
                // Fallback to current post tags if no custom tags selected
                $tags = get_the_tags($post_id);
                if (empty($tags)) {
                    return;
                }
                $tag_ids = array();
                foreach ($tags as $tag) {
                    $tag_ids[] = $tag->term_id;
                }
                $args['tag__in'] = $tag_ids;
            } else {
                $args['tag__in'] = array_map('intval', (array) $custom_tags);
            }
            break;

        case 'category':
        default:
            $categories = get_the_category($post_id);
            if (empty($categories)) {
                return;
            }
            $category_ids = array();
            foreach ($categories as $cat) {
                $category_ids[] = $cat->term_id;
            }
            $args['category__in'] = $category_ids;
            break;
    }

    $related = new WP_Query($args);

    if (!$related->have_posts()) {
        return;
    }
    ?>
    <div class="blog-over-related-posts">
        <h3 class="blog-over-related-title"><?php echo esc_html($title); ?></h3>
        <div class="blog-over-related-grid blog-over-cols-<?php echo esc_attr($columns); ?>">
            <?php
            while ($related->have_posts()):
                $related->the_post();

                // Check if we have any non-thumbnail elements
                $content_elements = array_filter($entry_elements, function ($el) {
                    return $el !== 'thumbnail';
                });
                ?>
                <article class="blog-over-related-item">
                    <?php
                    // Render post card elements in saved order
                    if (!empty($entry_elements) && is_array($entry_elements)):
                        $content_opened = false;

                        foreach ($entry_elements as $element):
                            // Open content div before first non-thumbnail element
                            if ($element !== 'thumbnail' && !$content_opened):
                                echo '<div class="blog-over-related-content">';
                                $content_opened = true;
                            endif;

                            switch ($element):
                                case 'thumbnail':
                                    if (has_post_thumbnail()):
                                        ?>
                                        <div class="blog-over-related-thumbnail">
                                            <a href="<?php the_permalink(); ?>">
                                                <?php the_post_thumbnail('blog-over-medium'); ?>
                                            </a>
                                        </div>
                                        <?php
                                    endif;
                                    break;

                                case 'meta':
                                    // Render meta elements with icons
                                    if (!empty($meta_elements) && is_array($meta_elements)):
                                        echo '<div class="blog-over-meta-info">';
                                        foreach ($meta_elements as $meta):
                                            switch ($meta):
                                                case 'author':
                                                    ?>
                                                    <span class="blog-over-meta-author">
                                                        <i class="far fa-user"></i>
                                                        <a
                                                            href="<?php echo esc_url(get_author_posts_url(get_the_author_meta('ID'))); ?>"><?php the_author(); ?></a>
                                                    </span>
                                                    <?php
                                                    break;

                                                case 'date':
                                                    ?>
                                                    <span class="blog-over-meta-date">
                                                        <i class="far fa-calendar"></i>
                                                        <a href="<?php the_permalink(); ?>">
                                                            <time datetime="<?php echo esc_attr(get_the_date('c')); ?>">
                                                                <?php echo esc_html(get_the_date()); ?>
                                                            </time>
                                                        </a>
                                                    </span>
                                                    <?php
                                                    break;

                                                case 'category':
                                                    $cats = get_the_category();
                                                    if (!empty($cats)):
                                                        ?>
                                                        <span class="blog-over-meta-category">
                                                            <i class="far fa-folder"></i>
                                                            <?php echo '<a href="' . esc_url(get_category_link($cats[0]->term_id)) . '">' . esc_html($cats[0]->name) . '</a>'; ?>
                                                        </span>
                                                        <?php
                                                    endif;
                                                    break;

                                                case 'comments':
                                                    if (comments_open() && get_comments_number() > 0):
                                                        ?>
                                                        <span class="blog-over-meta-comments">
                                                            <i class="far fa-comment"></i>
                                                            <?php comments_number('0', '1', '%'); ?>
                                                        </span>
                                                        <?php
                                                    endif;
                                                    break;
                                            endswitch;
                                        endforeach;
                                        echo '</div>';
                                    endif;
                                    break;

                                case 'title':
                                    ?>
                                    <h4 class="blog-over-related-post-title">
                                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                                    </h4>
                                    <?php
                                    break;

                                case 'excerpt':
                                    ?>
                                    <p class="blog-over-related-excerpt">
                                        <?php echo esc_html(wp_trim_words(get_the_excerpt(), $excerpt_length)); ?>
                                    </p>
                                    <?php
                                    break;
                            endswitch;
                        endforeach;

                        // Close content div if it was opened
                        if ($content_opened):
                            echo '</div>';
                        endif;
                    endif;
                    ?>
                </article>
                <?php
            endwhile;
            ?>
        </div>
    </div>
    <?php
    wp_reset_postdata();
}


/**
 * Display Share Buttons
 */
function blog_over_share_buttons()
{
    $url = urlencode(get_permalink());
    $title = urlencode(get_the_title());
    ?>
    <div class="blog-over-share-icons">
        <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo esc_attr($url); ?>" target="_blank"
            rel="noopener noreferrer" class="blog-over-share-facebook"
            aria-label="<?php esc_attr_e('Share on Facebook', 'blog-over'); ?>">
            <i class="fab fa-facebook-f"></i>
        </a>
        <a href="https://twitter.com/intent/tweet?url=<?php echo esc_attr($url); ?>&text=<?php echo esc_attr($title); ?>"
            target="_blank" rel="noopener noreferrer" class="blog-over-share-twitter"
            aria-label="<?php esc_attr_e('Share on Twitter', 'blog-over'); ?>">
            <i class="fab fa-x-twitter"></i>
        </a>
        <a href="https://www.linkedin.com/shareArticle?mini=true&url=<?php echo esc_attr($url); ?>&title=<?php echo esc_attr($title); ?>"
            target="_blank" rel="noopener noreferrer" class="blog-over-share-linkedin"
            aria-label="<?php esc_attr_e('Share on LinkedIn', 'blog-over'); ?>">
            <i class="fab fa-linkedin-in"></i>
        </a>
        <a href="https://pinterest.com/pin/create/button/?url=<?php echo esc_attr($url); ?>&description=<?php echo esc_attr($title); ?>"
            target="_blank" rel="noopener noreferrer" class="blog-over-share-pinterest"
            aria-label="<?php esc_attr_e('Share on Pinterest', 'blog-over'); ?>">
            <i class="fab fa-pinterest-p"></i>
        </a>
        <a href="mailto:?subject=<?php echo esc_attr($title); ?>&body=<?php echo esc_attr($url); ?>"
            class="blog-over-share-email" aria-label="<?php esc_attr_e('Share via Email', 'blog-over'); ?>">
            <i class="far fa-envelope"></i>
        </a>
    </div>
    <?php
}

/**
 * Custom Comment Callback
 */
function blog_over_comment_callback($comment, $args, $depth)
{
    $tag = ($args['style'] === 'div') ? 'div' : 'li';
    ?>
    <<?php echo esc_attr($tag); ?> id="comment-<?php comment_ID(); ?>" <?php comment_class('blog-over-comment'); ?>>
        <article class="blog-over-comment-body">
            <div class="blog-over-comment-avatar">
                <?php echo get_avatar($comment, 60); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- get_avatar() returns safe HTML ?>
            </div>
            <div class="blog-over-comment-content">
                <header class="blog-over-comment-meta">
                    <span class="blog-over-comment-author"><?php comment_author_link(); ?></span>
                    <span class="blog-over-comment-date">
                        <time datetime="<?php echo esc_attr(get_comment_date('c')); ?>">
                            <?php echo esc_html(get_comment_date()); ?>
                        </time>
                    </span>
                </header>

                <?php if ($comment->comment_approved == '0'): ?>
                    <p class="blog-over-comment-awaiting">
                        <?php esc_html_e('Your comment is awaiting moderation.', 'blog-over'); ?>
                    </p>
                <?php endif; ?>

                <div class="blog-over-comment-text">
                    <?php comment_text(); ?>
                </div>

                <footer class="blog-over-comment-actions">
                    <?php
                    comment_reply_link(array_merge($args, array(
                        'reply_text' => esc_html__('Reply', 'blog-over'),
                        'depth' => $depth,
                        'max_depth' => $args['max_depth'],
                    )));

                    edit_comment_link('<i class="fas fa-edit"></i> ' . esc_html__('Edit', 'blog-over'));
                    ?>
                </footer>
            </div>
        </article>
        <?php
}



/**
 * Display Footer Social Icons
 */
function blog_over_footer_social_icons()
{
    $social_links = array(
        'facebook' => array(
            'url' => get_theme_mod('blog_over_social_facebook', ''),
            'icon' => 'fab fa-facebook-f',
            'label' => __('Facebook', 'blog-over'),
        ),
        'twitter' => array(
            'url' => get_theme_mod('blog_over_social_twitter', ''),
            'icon' => 'fab fa-x-twitter',
            'label' => __('Twitter', 'blog-over'),
        ),
        'instagram' => array(
            'url' => get_theme_mod('blog_over_social_instagram', ''),
            'icon' => 'fab fa-instagram',
            'label' => __('Instagram', 'blog-over'),
        ),
        'youtube' => array(
            'url' => get_theme_mod('blog_over_social_youtube', ''),
            'icon' => 'fab fa-youtube',
            'label' => __('YouTube', 'blog-over'),
        ),
        'linkedin' => array(
            'url' => get_theme_mod('blog_over_social_linkedin', ''),
            'icon' => 'fab fa-linkedin-in',
            'label' => __('LinkedIn', 'blog-over'),
        ),
        'pinterest' => array(
            'url' => get_theme_mod('blog_over_social_pinterest', ''),
            'icon' => 'fab fa-pinterest-p',
            'label' => __('Pinterest', 'blog-over'),
        ),
    );

    echo '<div class="blog-over-footer-social-icons">';
    foreach ($social_links as $platform => $data) {
        if (!empty($data['url'])) {
            echo '<a href="' . esc_url($data['url']) . '" target="_blank" rel="noopener noreferrer" class="blog-over-social-icon blog-over-social-' . esc_attr($platform) . '" aria-label="' . esc_attr($data['label']) . '">';
            echo '<i class="' . esc_attr($data['icon']) . '"></i>';
            echo '</a>';
        }
    }
    echo '</div>';
}

/**
 * Get Blog Entry Elements in saved order
 * Supports Archive Override - on archive pages with override enabled, uses archive settings
 * 
 * @param bool $enabled_only Return only visible elements (default true)
 * @return array Array of element keys in order
 */
function blog_over_get_blog_entry_elements($enabled_only = true)
{
    $default = array(
        'category',
        'header',
        'meta',
        'summary',
        'footer',
    );

    // Check for archive override
    $is_archive = is_archive() || is_category() || is_tag() || is_author() || is_date();
    $archive_override = get_theme_mod('blog_over_archive_override', false);

    if ($is_archive && $archive_override) {
        // Use archive-specific settings
        $elements = get_theme_mod('blog_over_archive_entry_elements', null);
    } else {
        // Use blog settings
        $elements = get_theme_mod('Blog_Over_entry_elements', null);
    }

    // If setting was never saved (null), use default
    // If setting is empty array (user unchecked all), return empty array
    if ($elements === null) {
        return $default;
    }

    // Ensure it's an array
    if (!is_array($elements)) {
        return $default;
    }

    return $elements;
}

/**
 * Get Blog Meta Elements in saved order
 * Supports Archive Override - on archive pages with override enabled, uses archive settings
 * 
 * @param bool $enabled_only Return only visible elements (default true)
 * @return array Array of meta element keys in order
 */
function blog_over_get_blog_meta_elements($enabled_only = true)
{
    $default = array(
        'author',
        'date',
        'comments',
    );

    // Check for archive override
    $is_archive = is_archive() || is_category() || is_tag() || is_author() || is_date();
    $archive_override = get_theme_mod('blog_over_archive_override', false);

    if ($is_archive && $archive_override) {
        // Use archive-specific settings
        $elements = get_theme_mod('blog_over_archive_entry_meta', null);
    } else {
        // Use blog settings
        $elements = get_theme_mod('Blog_Over_entry_meta', null);
    }

    // If setting was never saved (null), use default
    // If setting is empty array (user unchecked all), return empty array
    if ($elements === null) {
        return $default;
    }

    // Ensure it's an array
    if (!is_array($elements)) {
        return $default;
    }

    return $elements;
}

/**
 * Get Excerpt Length based on context
 * Supports Archive Override - on archive pages with override enabled, uses archive excerpt length
 * 
 * @return int Excerpt length in words
 */
function blog_over_get_excerpt_length()
{
    $default = 25;

    // Check for archive override
    $is_archive = is_archive() || is_category() || is_tag() || is_author() || is_date();
    $archive_override = get_theme_mod('blog_over_archive_override', false);

    if ($is_archive && $archive_override) {
        // Use archive-specific excerpt length
        return get_theme_mod('blog_over_archive_excerpt_length', $default);
    } else {
        // Use blog excerpt length
        return get_theme_mod('blog_over_excerpt_length', $default);
    }
}

/**
 * Check if a blog entry element is enabled
 * 
 * @param string $element Element key to check
 * @return bool True if element is enabled
 */
function blog_over_entry_element_enabled($element)
{
    $elements = blog_over_get_blog_entry_elements();
    return in_array($element, $elements, true);
}

/**
 * Check if a blog meta element is enabled
 * 
 * @param string $element Meta element key to check
 * @return bool True if element is enabled
 */
function blog_over_meta_element_enabled($element)
{
    $elements = blog_over_get_blog_meta_elements();
    return in_array($element, $elements, true);
}

/**
 * Render blog entry meta based on saved order
 */
function blog_over_render_entry_meta()
{
    $meta_elements = blog_over_get_blog_meta_elements();

    if (empty($meta_elements)) {
        return;
    }

    echo '<div class="blog-over-meta-info">';

    foreach ($meta_elements as $element) {
        switch ($element) {
            case 'author':
                ?>
                    <span class="blog-over-meta-author">
                        <i class="far fa-user"></i>
                        <?php the_author_posts_link(); ?>
                    </span>
                    <?php
                    break;

            case 'date':
                ?>
                    <span class="blog-over-meta-date">
                        <a href="<?php the_permalink(); ?>">
                            <time datetime="<?php echo esc_attr(get_the_date('c')); ?>">
                                <i class="far fa-calendar"></i>
                                <?php echo esc_html(get_the_date()); ?>
                            </time>
                        </a>
                    </span>
                    <?php
                    break;

            case 'category':
                $cats = get_the_category();
                if (!empty($cats)) {
                    ?>
                        <span class="blog-over-meta-category">
                            <i class="far fa-folder"></i>
                            <?php
                            $cat_links = array();
                            foreach ($cats as $cat) {
                                $cat_links[] = '<a href="' . esc_url(get_category_link($cat->term_id)) . '">' . esc_html($cat->name) . '</a>';
                            }
                            echo implode(', ', $cat_links);
                            ?>
                        </span>
                        <?php
                }
                break;

            case 'comments':
                // Only show comments meta if comments are open AND there are comments
                $comment_count = get_comments_number();
                if (comments_open() && $comment_count > 0) {
                    ?>
                        <span class="blog-over-meta-comments">
                            <i class="far fa-comment"></i>
                            <?php comments_number('0', '1', '%'); ?>
                        </span>
                        <?php
                }
                break;
        }
    }

    echo '</div>';
}

/**
 * Render single post element
 * Moved from content-single.php to prevent redeclaration errors
 *
 * @param string $element Element key to render
 * @param array $meta_elements Array of meta elements
 */
if (!function_exists('blog_over_render_single_element')) {
    function blog_over_render_single_element($element, $meta_elements)
    {
        switch ($element) {
            case 'category':
                ?>
                    <div class="blog-over-single-category">
                        <?php the_category(' '); ?>
                    </div>
                    <?php
                    break;

            case 'meta':
                if (!empty($meta_elements) || has_action('blog_over_after_single_meta')) {
                    ?>
                        <div class="blog-over-single-meta">
                            <?php if (!empty($meta_elements)) : ?>
                                <?php foreach ($meta_elements as $meta_item): ?>
                                    <?php blog_over_render_single_meta_item($meta_item); ?>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            <?php do_action('blog_over_after_single_meta'); ?>
                        </div>
                        <?php
                }
                break;

            case 'tags':
                if (has_tag()) {
                    ?>
                        <div class="blog-over-single-tags">
                            <span class="tags-label"><i class="fas fa-tags"></i> <?php esc_html_e('Tags:', 'blog-over'); ?></span>
                            <?php the_tags('', ' ', ''); ?>
                        </div>
                        <?php
                }
                break;

            case 'share':
                ?>
                    <div class="blog-over-share-buttons">
                        <span class="share-label"><?php esc_html_e('Share:', 'blog-over'); ?></span>
                        <?php blog_over_share_buttons(); ?>
                    </div>
                    <?php
                    break;

            case 'author_box':
                $author_style = get_theme_mod('blog_over_author_box_style', 'modern');
                $avatar_size = get_theme_mod('blog_over_author_avatar_size', 100);
                $show_bio = get_theme_mod('blog_over_author_show_bio', true);
                $show_posts_count = get_theme_mod('blog_over_author_show_posts_count', true);
                $show_view_all = get_theme_mod('blog_over_author_show_view_all', true);
                $author_id = get_the_author_meta('ID');
                $author_posts = count_user_posts($author_id);
                ?>
                    <div class="blog-over-author-box blog-over-author-style-<?php echo esc_attr($author_style); ?>"
                        data-customize-partial-id="blog_over_author_section">
                        <div class="blog-over-author-avatar"
                            style="width: <?php echo esc_attr($avatar_size); ?>px; height: <?php echo esc_attr($avatar_size); ?>px;">
                            <?php echo get_avatar($author_id, $avatar_size); ?>
                        </div>
                        <div class="blog-over-author-info">
                            <h4 class="blog-over-author-name">
                                <?php the_author_posts_link(); ?>
                            </h4>
                            <?php if ($show_posts_count): ?>
                                <span class="blog-over-author-posts-count">
                                    <i class="far fa-file-alt"></i>
                                    <?php printf(_n('%s Post', '%s Posts', $author_posts, 'blog-over'), number_format_i18n($author_posts)); ?>
                                </span>
                            <?php endif; ?>
                            <?php if ($show_bio && get_the_author_meta('description')): ?>
                                <p class="blog-over-author-bio">
                                    <?php the_author_meta('description'); ?>
                                </p>
                            <?php endif; ?>
                            <?php if ($show_view_all): ?>
                                <a href="<?php echo esc_url(get_author_posts_url($author_id)); ?>" class="blog-over-author-view-all">
                                    <?php esc_html_e('View All Posts', 'blog-over'); ?>
                                    <i class="fas fa-arrow-right"></i>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php
                    break;

            case 'post_nav':
                $nav_style = get_theme_mod('blog_over_postnav_style', 'cards');
                $show_thumb = get_theme_mod('blog_over_postnav_thumb', true);
                $show_title = get_theme_mod('blog_over_postnav_title', true);
                $same_cat = get_theme_mod('blog_over_postnav_same_cat', false);
                $prev_text = get_theme_mod('blog_over_postnav_prev_text', __('Previous', 'blog-over'));
                $next_text = get_theme_mod('blog_over_postnav_next_text', __('Next', 'blog-over'));

                // Simple style should not show thumbnails
                if ($nav_style === 'simple') {
                    $show_thumb = false;
                }

                $prev_post = get_previous_post($same_cat);
                $next_post = get_next_post($same_cat);

                if (!$prev_post && !$next_post) {
                    break;
                }
                ?>
                    <nav class="blog-over-post-navigation blog-over-postnav-<?php echo esc_attr($nav_style); ?>"
                        data-customize-partial-id="blog_over_postnav_section">
                        <?php if ($prev_post): ?>
                            <a href="<?php echo esc_url(get_permalink($prev_post)); ?>" class="blog-over-nav-prev">
                                <?php if ($show_thumb && has_post_thumbnail($prev_post)): ?>
                                    <div class="blog-over-nav-thumb">
                                        <?php echo get_the_post_thumbnail($prev_post, 'thumbnail'); ?>
                                    </div>
                                <?php endif; ?>
                                <div class="blog-over-nav-content">
                                    <span class="blog-over-nav-label">
                                        <i class="fas fa-chevron-left"></i>
                                        <?php echo esc_html($prev_text); ?>
                                    </span>
                                    <?php if ($show_title): ?>
                                        <span class="blog-over-nav-title"><?php echo esc_html(get_the_title($prev_post)); ?></span>
                                    <?php endif; ?>
                                </div>
                            </a>
                        <?php else: ?>
                            <div class="blog-over-nav-prev blog-over-nav-empty"></div>
                        <?php endif; ?>

                        <?php if ($next_post): ?>
                            <a href="<?php echo esc_url(get_permalink($next_post)); ?>" class="blog-over-nav-next">
                                <div class="blog-over-nav-content">
                                    <span class="blog-over-nav-label">
                                        <?php echo esc_html($next_text); ?>
                                        <i class="fas fa-chevron-right"></i>
                                    </span>
                                    <?php if ($show_title): ?>
                                        <span class="blog-over-nav-title"><?php echo esc_html(get_the_title($next_post)); ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php if ($show_thumb && has_post_thumbnail($next_post)): ?>
                                    <div class="blog-over-nav-thumb">
                                        <?php echo get_the_post_thumbnail($next_post, 'thumbnail'); ?>
                                    </div>
                                <?php endif; ?>
                            </a>
                        <?php else: ?>
                            <div class="blog-over-nav-next blog-over-nav-empty"></div>
                        <?php endif; ?>
                    </nav>
                    <?php
                    break;

            case 'comments':
                if (comments_open() || get_comments_number()) {
                    comments_template();
                }
                break;
        }
    }
}

/**
 * Render single meta item
 * Moved from content-single.php to prevent redeclaration errors
 *
 * @param string $meta_item Meta item key to render
 */
if (!function_exists('blog_over_render_single_meta_item')) {
    function blog_over_render_single_meta_item($meta_item)
    {
        switch ($meta_item) {
            case 'author':
                ?>
                    <span class="blog-over-meta-author">
                        <?php echo get_avatar(get_the_author_meta('ID'), 40); ?>
                        <span><?php the_author_posts_link(); ?></span>
                    </span>
                    <?php
                    break;

            case 'date':
                ?>
                    <span class="blog-over-meta-date">
                        <i class="far fa-calendar-alt"></i>
                        <a href="<?php the_permalink(); ?>">
                            <time datetime="<?php echo esc_attr(get_the_date('c')); ?>">
                                <?php echo esc_html(get_the_date()); ?>
                            </time>
                        </a>
                    </span>
                    <?php
                    break;

            case 'comments':
                if (comments_open() || get_comments_number()) {
                    ?>
                        <span class="blog-over-meta-comments">
                            <i class="far fa-comment"></i>
                            <a href="<?php echo esc_url(get_comments_link()); ?>">
                                <?php comments_number('0 Comments', '1 Comment', '% Comments'); ?>
                            </a>
                        </span>
                        <?php
                }
                break;

            case 'views':
                if (function_exists('blog_over_get_views_formatted')) {
                    $views = blog_over_get_views_formatted();
                    ?>
                        <span class="blog-over-meta-views">
                            <i class="far fa-eye" aria-hidden="true"></i>
                            <span><?php echo esc_html($views); ?></span>
                        </span>
                        <?php
                }
                break;

            case 'reading_time':
                if (function_exists('blog_over_get_reading_time')) {
                    $reading_time = blog_over_get_reading_time();
                    ?>
                        <span class="blog-over-meta-reading-time">
                            <i class="far fa-clock" aria-hidden="true"></i>
                            <span><?php echo esc_html($reading_time); ?></span>
                        </span>
                        <?php
                }
                break;

            default:
                do_action('blog_over_render_single_meta_item', $meta_item);
                break;
        }
    }
}

/**
 * Parse a video URL and return the corresponding embed URL.
 *
 * Supports YouTube (youtube.com, youtu.be) and Vimeo URLs.
 * Returns the embeddable URL or false for self-hosted / unrecognized URLs
 * (which should be rendered as a <video> tag instead).
 *
 * @param string $url The video URL to parse.
 * @return string|false Embed URL on success, false if self-hosted or unrecognized.
 */
function blog_over_parse_video_embed_url($url)
{
    if (empty($url)) {
        return false;
    }

    // YouTube: youtube.com/watch?v=ID, youtu.be/ID, youtube.com/embed/ID
    if (preg_match('/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w\-]+)/', $url, $matches)) {
        return 'https://www.youtube.com/embed/' . $matches[1] . '?autoplay=0&rel=0';
    }

    // Vimeo: vimeo.com/ID, player.vimeo.com/video/ID
    if (preg_match('/(?:vimeo\.com\/|player\.vimeo\.com\/video\/)(\d+)/', $url, $matches)) {
        return 'https://player.vimeo.com/video/' . $matches[1] . '?dnt=1';
    }

    // Self-hosted or unrecognized — caller should render as <video> tag
    return false;
}
/**
 * Render a single element for the Feature Story section.
 *
 * @param string $el The element key (category, title, meta, excerpt, button).
 */
function blog_over_render_feature_story_element($el)
{
    switch ($el) {
        case 'category':
            if (function_exists('blog_over_first_category')) {
                echo '<div class="blog-over-category-badge">';
                blog_over_first_category();
                echo '</div>';
            }
            break;

        case 'title':
            echo '<h3 class="blog-over-feature-title">';
            echo '<a href="' . esc_url(get_permalink()) . '">' . get_the_title() . '</a>';
            echo '</h3>';
            break;

        case 'meta':
            if (function_exists('blog_over_render_meta_list')) {
                echo '<div class="blog-over-feature-meta">';
                blog_over_render_meta_list(array('author', 'date', 'comments'));
                echo '</div>';
            }
            break;

        case 'excerpt':
            $excerpt = wp_trim_words(get_the_excerpt(), 25);
            if (!empty($excerpt)) {
                echo '<div class="blog-over-feature-excerpt">' . esc_html($excerpt) . '</div>';
            }
            break;

        case 'button':
            $btn_text = get_theme_mod('blog_over_feature_story_btn_text', __('Read Story', 'blog-over'));
            if (!empty($btn_text)) {
                echo '<div class="blog-over-feature-action">';
                echo '<a href="' . esc_url(get_permalink()) . '" class="blog-over-feature-button">' . esc_html($btn_text) . '</a>';
                echo '</div>';
            }
            break;
    }
}
