<?php
/**
 * Blog Over functions and definitions
 *
 * @package Blog_Over
 */

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

// Theme Constants
define('BLOG_OVER_VERSION', wp_get_theme(get_template())->get('Version'));
define('BLOG_OVER_DIR', get_template_directory());
define('BLOG_OVER_URI', get_template_directory_uri());

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * @global int $content_width
 */
function blog_over_content_width()
{
    $GLOBALS['content_width'] = apply_filters('blog_over_content_width', 1140);
}
add_action('after_setup_theme', 'blog_over_content_width', 0);


/**
 * Theme Setup
 */
function blog_over_setup()
{
    load_theme_textdomain('blog-over', BLOG_OVER_DIR . '/languages');

    add_theme_support('automatic-feed-links');
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('customize-selective-refresh-widgets');
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
        'script',
        'style',
    ));
    add_theme_support('custom-logo', array(
        'height' => 100,
        'width' => 300,
        'flex-width' => true,
        'flex-height' => true,
    ));

    // Block Editor Support
    add_theme_support('wp-block-styles');
    add_theme_support('align-wide');
    add_theme_support('responsive-embeds');
    add_theme_support('editor-styles');
    add_editor_style('assets/css/editor-style.css');

    // Standard Editor Settings for Premium Patterns
    add_theme_support('editor-color-palette', array(
        array(
            'name' => esc_html__('Primary', 'blog-over'),
            'slug' => 'primary',
            'color' => 'var(--blog-over-primary)',
        ),
        array(
            'name' => esc_html__('Secondary', 'blog-over'),
            'slug' => 'secondary',
            'color' => 'var(--blog-over-secondary)',
        ),
        array(
            'name' => esc_html__('Dark', 'blog-over'),
            'slug' => 'dark',
            'color' => '#111827',
        ),
        array(
            'name' => esc_html__('Light', 'blog-over'),
            'slug' => 'light',
            'color' => '#f9fafb',
        ),
        array(
            'name' => esc_html__('White', 'blog-over'),
            'slug' => 'white',
            'color' => '#ffffff',
        ),
    ));

    add_theme_support('editor-font-sizes', array(
        array(
            'name' => esc_html__('Small', 'blog-over'),
            'size' => 14,
            'slug' => 'small'
        ),
        array(
            'name' => esc_html__('Normal', 'blog-over'),
            'size' => 16,
            'slug' => 'normal'
        ),
        array(
            'name' => esc_html__('Large', 'blog-over'),
            'size' => 24,
            'slug' => 'large'
        ),
        array(
            'name' => esc_html__('Huge', 'blog-over'),
            'size' => 36,
            'slug' => 'huge'
        )
    ));

    // Custom Header
    add_theme_support('custom-header', apply_filters('blog_over_custom_header_args', array(
        'default-image' => '',
        'default-text-color' => '000000',
        'width' => 1920,
        'height' => 400,
        'flex-height' => true,
        'flex-width' => true,
        'wp-head-callback' => 'blog_over_header_style',
    )));

    // Custom Background
    add_theme_support('custom-background', apply_filters('blog_over_custom_background_args', array(
        'default-color' => 'ffffff',
        'default-image' => '',
    )));

    // Starter Content for fresh installations
    require_once BLOG_OVER_DIR . '/inc/starter-content.php';
    add_theme_support('starter-content', blog_over_get_starter_content());

    // Image sizes
    add_image_size('blog-over-slider', 1280, 720, true);
    add_image_size('blog-over-featured', 1024, 0, false);
    add_image_size('blog-over-medium', 720, 380, true);
    add_image_size('blog-landscape', 800, 600, true);
    add_image_size('blog-wide', 1200, 675, true);

    // Menus
    register_nav_menus(array(
        'blog-over-main-menu' => esc_html__('Primary Menu', 'blog-over'),
        'blog-over-footer-menu' => esc_html__('Footer Menu', 'blog-over'),
    ));
}
add_action('after_setup_theme', 'blog_over_setup');

/**
 * Custom header style output.
 */
function blog_over_header_style()
{
    $header_text_color = get_header_textcolor();
    if (get_theme_support('custom-header', 'default-text-color') === $header_text_color) {
        return;
    }
    ?>
    <style type="text/css">
        <?php if (!display_header_text()): ?>
            .site-title,
            .site-description,
            .blog-over-branding-text {
                position: absolute;
                clip: rect(1px, 1px, 1px, 1px);
            }

        <?php else: ?>
            .site-title a,
            .site-description {
                color: #<?php echo esc_attr($header_text_color); ?>;
            }

        <?php endif; ?>
    </style>
    <?php
}

/**
 * Register block styles.
 */
function blog_over_register_block_styles()
{
    register_block_style('core/button', array(
        'name' => 'blog-over-rounded',
        'label' => __('Rounded', 'blog-over'),
    ));
    register_block_style('core/button', array(
        'name' => 'blog-over-outline',
        'label' => __('Outline', 'blog-over'),
    ));
    register_block_style('core/group', array(
        'name' => 'blog-over-card',
        'label' => __('Card', 'blog-over'),
    ));
    register_block_style('core/list', array(
        'name' => 'checkmark',
        'label' => __('Checkmark', 'blog-over'),
    ));
}
add_action('init', 'blog_over_register_block_styles');

/**
 * Register block patterns.
 */
function blog_over_register_block_patterns()
{
    register_block_pattern_category('blog-over', array(
        'label' => __('Blog Over', 'blog-over'),
    ));
}
add_action('init', 'blog_over_register_block_patterns');

/**
 * Output dark mode FOUC prevention script in <head> via wp_head.
 * Must run early (priority 1) to prevent flash of light content on dark mode.
 */
function blog_over_dark_mode_fouc_script()
{
    $admin_default = get_theme_mod('blog_over_theme_skin', 'light');
    ?>
    <script id="blog-over-dark-mode-fouc">
        (function () {
            var s = 'blog_over_user_skin_preference';
            var u = localStorage.getItem(s);
            var d = <?php echo wp_json_encode($admin_default); ?>;
            var a = (u === 'dark' || u === 'light') ? u : d;
            if (a === 'dark') { document.documentElement.classList.add('blog-over-dark-mode'); }
        })();
    </script>
    <?php
}
add_action('wp_head', 'blog_over_dark_mode_fouc_script', 1);

/**
 * Output basic SEO meta tags (meta description + Open Graph) as fallback.
 * Only outputs if no major SEO plugin is detected (Yoast, Rank Math, AIOSEO).
 *
 * @since 0.0.8
 */
function blog_over_seo_meta_tags()
{
    // Don't interfere if a major SEO plugin is handling meta tags
    if (
        defined('WPSEO_VERSION') ||           // Yoast SEO
        defined('RANK_MATH_VERSION') ||        // Rank Math
        defined('AIOSEO_VERSION') ||           // All in One SEO
        class_exists('The_SEO_Framework\\Load') // SEO Framework
    ) {
        return;
    }

    $description = '';
    $og_title = '';
    $og_image = '';
    $og_type = 'website';

    if (is_singular()) {
        // Single post/page
        $post = get_queried_object();
        if ($post) {
            $og_title = get_the_title($post);
            $og_type = is_single() ? 'article' : 'website';

            // Meta description: use excerpt, or generate from content
            if (has_excerpt($post)) {
                $description = get_the_excerpt($post);
            } else {
                $description = wp_trim_words(wp_strip_all_tags($post->post_content), 30, '…');
            }

            // Open Graph image from featured image
            if (has_post_thumbnail($post)) {
                $og_image = get_the_post_thumbnail_url($post, 'full');
            }
        }
    } elseif (is_home() || is_front_page()) {
        $og_title = get_bloginfo('name');
        $description = get_bloginfo('description');
    } elseif (is_category()) {
        $og_title = single_cat_title('', false);
        $description = category_description();
    } elseif (is_tag()) {
        $og_title = single_tag_title('', false);
        $description = tag_description();
    } elseif (is_author()) {
        $author = get_queried_object();
        if ($author) {
            $og_title = $author->display_name;
            $description = get_the_author_meta('description', $author->ID);
        }
    } elseif (is_archive()) {
        $og_title = get_the_archive_title();
        $description = get_the_archive_description();
    } elseif (is_search()) {
        $og_title = sprintf(
            /* translators: %s: search query */
            esc_html__('Search Results for: %s', 'blog-over'),
            get_search_query()
        );
    }

    // Clean up description
    $description = wp_strip_all_tags($description);
    $description = preg_replace('/\s+/', ' ', $description);
    $description = trim($description);
    if (mb_strlen($description) > 160) {
        $description = mb_substr($description, 0, 157) . '…';
    }

    // Output meta description
    if ($description) {
        echo '<meta name="description" content="' . esc_attr($description) . '">' . "\n";
    }

    // Output Open Graph tags
    if ($og_title) {
        echo '<meta property="og:title" content="' . esc_attr($og_title) . '">' . "\n";
    }
    if ($description) {
        echo '<meta property="og:description" content="' . esc_attr($description) . '">' . "\n";
    }
    echo '<meta property="og:type" content="' . esc_attr($og_type) . '">' . "\n";
    echo '<meta property="og:url" content="' . esc_url(home_url(add_query_arg(array(), ''))) . '">' . "\n";
    echo '<meta property="og:site_name" content="' . esc_attr(get_bloginfo('name')) . '">' . "\n";
    if ($og_image) {
        echo '<meta property="og:image" content="' . esc_url($og_image) . '">' . "\n";
    }

    // Twitter Card
    echo '<meta name="twitter:card" content="' . ($og_image ? 'summary_large_image' : 'summary') . '">' . "\n";
}
add_action('wp_head', 'blog_over_seo_meta_tags', 5);


/**
 * Output categories of the current post (up to limit)
 * Categories are linked to their respective archive pages
 * 
 * @param int $limit Maximum number of categories to show (default 3)
 */
function blog_over_first_category($limit = 3)
{
    $categories = get_the_category();
    if (!empty($categories)) {
        $count = 0;
        foreach ($categories as $category) {
            if ($count >= $limit)
                break;
            $cat_link = get_category_link($category->term_id);
            echo '<a href="' . esc_url($cat_link) . '" class="blog-over-cat-item">' . esc_html($category->name) . '</a>';
            $count++;
        }
    }
}




/**
 * Register Widget Areas
 */
function blog_over_widgets_init()
{
    register_sidebar(array(
        'name' => esc_html__('Sidebar', 'blog-over'),
        'id' => 'sidebar-1',
        'description' => esc_html__('Add widgets here.', 'blog-over'),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget' => '</section>',
        'before_title' => '<h2 class="widget-title">',
        'after_title' => '</h2>',
    ));

    // Footer Widget Areas (always register all 4 for widget persistence).
    for ($i = 1; $i <= 4; $i++) {
        register_sidebar(
            array(
                'name' => sprintf(
                    /* translators: %d: Footer widget area number. */
                    esc_html__('Footer %d', 'blog-over'),
                    $i
                ),
                'id' => 'footer-' . $i,
                'description' => sprintf(
                    /* translators: %d: Footer widget area number. */
                    esc_html__('Footer widget area %d.', 'blog-over'),
                    $i
                ),
                'before_widget' => '<div id="%1$s" class="widget %2$s">',
                'after_widget' => '</div>',
                'before_title' => '<h3 class="widget-title">',
                'after_title' => '</h3>',
            )
        );
    }

    // Custom Widgets
    register_widget('Blog_Over_Author_Widget');
}
add_action('widgets_init', 'blog_over_widgets_init');

/**
 * Enqueue Scripts & Styles
 */
function blog_over_scripts()
{
    // Color Variables (load first - CSS custom properties for light/dark mode)
    wp_enqueue_style('blog-over-color-variables', BLOG_OVER_URI . '/assets/css/color-variables.css', array(), BLOG_OVER_VERSION);

    // Main stylesheet
    wp_enqueue_style('blog-over-style', get_stylesheet_uri(), array('blog-over-color-variables'), BLOG_OVER_VERSION);

    // Dark Mode stylesheet (loads after main style for proper cascading)
    wp_enqueue_style('blog-over-dark-mode', BLOG_OVER_URI . '/assets/css/dark-mode.css', array('blog-over-style'), BLOG_OVER_VERSION);

    // Menu stylesheet
    wp_enqueue_style('blog-over-menu-style', BLOG_OVER_URI . '/assets/css/menu.css', array('blog-over-dark-mode'), BLOG_OVER_VERSION);

    // Google Fonts - Inter (loaded locally for WordPress.org compliance)
    // Note: For WordPress.org, we'll use system fonts or bundle fonts locally
    // Users can add Google Fonts via child theme or plugin if needed
    wp_enqueue_style('blog-over-google-fonts', BLOG_OVER_URI . '/assets/fonts/inter/inter.css', array(), BLOG_OVER_VERSION);

    // Font Awesome (bundled with Kirki for WordPress.org compliance)
    wp_enqueue_style('font-awesome', BLOG_OVER_URI . '/assets/kirki/kirki-packages/control-iconpicker/dist/fontawesome/css/all.min.css', array(), '6.4.0');

    // Loading Screen (only when enabled)
    if (get_theme_mod('blog_over_loading_screen_enable', true)) {
        wp_enqueue_style('blog-over-loading-screen', BLOG_OVER_URI . '/assets/css/loading-screen.css', array(), BLOG_OVER_VERSION);
    }

    // Menu JavaScript
    wp_enqueue_script('blog-over-menu-js', BLOG_OVER_URI . '/assets/js/menu.js', array(), BLOG_OVER_VERSION, true);

    // Theme Functions JavaScript
    wp_enqueue_script('blog-over-theme-functions', BLOG_OVER_URI . '/assets/js/theme-functions.js', array(), BLOG_OVER_VERSION, true);
    if (is_singular() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }

    // Announcement Bar Assets
    if (get_theme_mod('blog_over_announcement_show', false) || is_customize_preview()) {
        wp_enqueue_style('blog-over-announcement-style', BLOG_OVER_URI . '/assets/css/announcement.css', array(), BLOG_OVER_VERSION);
        wp_enqueue_script('blog-over-announcement-js', BLOG_OVER_URI . '/assets/js/announcement.js', array('jquery'), BLOG_OVER_VERSION, true);
    }

    // Ticker Assets
    if (get_theme_mod('blog_over_enable_ticker', false)) {
        wp_enqueue_style('blog-over-ticker-style', BLOG_OVER_URI . '/assets/css/ticker.css', array(), BLOG_OVER_VERSION);
        wp_enqueue_script('jquery-marquee', BLOG_OVER_URI . '/assets/js/jquery.marquee.js', array('jquery'), '1.6.0', true);
        wp_enqueue_script('blog-over-ticker-js', BLOG_OVER_URI . '/assets/js/ticker.js', array('jquery', 'jquery-marquee'), BLOG_OVER_VERSION, true);
    }

    // Hero Assets
    if (get_theme_mod('blog_over_enable_hero', false)) {
        wp_enqueue_style('blog-over-hero-style', BLOG_OVER_URI . '/assets/css/hero.css', array(), BLOG_OVER_VERSION);
    }

    // Featured Assets
    if (get_theme_mod('blog_over_enable_featured_links', false)) {
        wp_enqueue_style('blog-over-featured-style', BLOG_OVER_URI . '/assets/css/featured.css', array(), BLOG_OVER_VERSION);
    }

    // Feature Story Assets
    if (get_theme_mod('blog_over_feature_story_enable', false) || is_customize_preview()) {
        wp_enqueue_style('blog-over-feature-story-style', BLOG_OVER_URI . '/assets/css/feature-story.css', array('blog-over-style'), BLOG_OVER_VERSION);
    }

    // You Missed Assets
    if (get_theme_mod('blog_over_you_missed_show', false)) {
        wp_enqueue_style('blog-over-missed-style', BLOG_OVER_URI . '/assets/css/missed.css', array(), BLOG_OVER_VERSION);
    }

    // Modern Blog Layout Assets
    $load_modern_css = false;
    if (get_theme_mod('Blog_Over_style', 'default') === 'modern-cards') {
        $load_modern_css = true;
    }
    // Also load for Blog Grid / Blog Custom Layout template when modern style is selected
    if (is_page_template('template-blog-grid.php') || is_page_template('template-blog-custom.php')) {
        $blog_style = get_post_meta(get_the_ID(), '_blog_over_template_blog_style', true);
        if ($blog_style === 'modern-cards') {
            $load_modern_css = true;
        }
    }
    if ($load_modern_css) {
        wp_enqueue_style('blog-over-blog-modern-style', BLOG_OVER_URI . '/assets/css/blog-modern.css', array(), BLOG_OVER_VERSION);
    }

    // Editorial Layout Assets
    if (get_theme_mod('Blog_Over_style', 'default') === 'editorial') {
        wp_enqueue_style('blog-over-editorial-style', BLOG_OVER_URI . '/assets/css/blog-editorial.css', array(), BLOG_OVER_VERSION);
    }

    // Content Alignment — always load (applies to all blog styles)
    wp_enqueue_style('blog-over-alignment', BLOG_OVER_URI . '/assets/css/blog-alignment.css', array('blog-over-style'), BLOG_OVER_VERSION);

    // Tabbed Magazine Assets — load on front page OR in Customizer preview (for pencil icon)
    if ((is_front_page() || is_home() || is_customize_preview()) && get_theme_mod('blog_over_tabbed_magazine_enable', false)) {
        wp_enqueue_style('blog-over-tabbed-magazine-style', BLOG_OVER_URI . '/assets/css/tabbed-magazine.css', array(), BLOG_OVER_VERSION);
        wp_enqueue_script('blog-over-tabbed-magazine-js', BLOG_OVER_URI . '/assets/js/tabbed-magazine.js', array(), BLOG_OVER_VERSION, true);
    }

    // Advertisement Banner Assets
    if (get_theme_mod('blog_over_ad_banner_enable', false) || is_customize_preview()) {
        wp_enqueue_style('blog-over-advertisement-style', BLOG_OVER_URI . '/assets/css/advertisement.css', array(), BLOG_OVER_VERSION);
    }

    // Trending Posts Assets
    if (get_theme_mod('blog_over_trending_enable', false) || is_customize_preview()) {
        wp_enqueue_style('blog-over-trending-style', BLOG_OVER_URI . '/assets/css/trending.css', array(), BLOG_OVER_VERSION);
    }

    // Newsletter / CTA Section Assets
    if (get_theme_mod('blog_over_newsletter_enable', false) || is_customize_preview()) {
        wp_enqueue_style('blog-over-newsletter-style', BLOG_OVER_URI . '/assets/css/newsletter.css', array(), BLOG_OVER_VERSION);
    }

    // Category Showcase Assets
    if (get_theme_mod('blog_over_catshowcase_enable', false) || is_customize_preview()) {
        wp_enqueue_style('blog-over-catshowcase-style', BLOG_OVER_URI . '/assets/css/category-showcase.css', array(), BLOG_OVER_VERSION);
    }

}
add_action('wp_enqueue_scripts', 'blog_over_scripts');

/**
 * Enqueue FontAwesome CSS in Customizer for Icon Picker
 */
function blog_over_customizer_scripts()
{
    // Enqueue Customizer Controls CSS (for sortable, color pickers, etc.)
    wp_enqueue_style(
        'blog-over-customizer-controls',
        BLOG_OVER_URI . '/assets/css/customizer-controls.css',
        array(),
        BLOG_OVER_VERSION
    );

    // Enqueue FontAwesome for icon picker in customizer
    $fa_css = BLOG_OVER_DIR . '/assets/kirki/kirki-packages/control-iconpicker/dist/fontawesome/css/all.css';
    if (file_exists($fa_css)) {
        wp_enqueue_style(
            'fontawesome-iconpicker',
            BLOG_OVER_URI . '/assets/kirki/kirki-packages/control-iconpicker/dist/fontawesome/css/all.css',
            array(),
            BLOG_OVER_VERSION
        );
    }

    // Hero Slider Widget Visibility Script
    wp_enqueue_script(
        'blog-over-customizer-hero',
        BLOG_OVER_URI . '/assets/js/customizer-hero.js',
        array('jquery', 'customize-controls'),
        BLOG_OVER_VERSION,
        true
    );

    // Archive Redirect Controls Script (handles pencil redirect logic)
    wp_enqueue_script(
        'blog-over-customizer-archive-controls',
        BLOG_OVER_URI . '/assets/js/customizer-archive-controls.js',
        array('jquery', 'customize-controls'),
        BLOG_OVER_VERSION,
        true
    );

    // Breadcrumb Controls Script (handles dynamic pencil icon positioning)
    wp_enqueue_script(
        'blog-over-customizer-breadcrumb-controls',
        BLOG_OVER_URI . '/assets/js/customizer-breadcrumb-controls.js',
        array('jquery', 'customize-controls'),
        BLOG_OVER_VERSION,
        true
    );

    // Customizer Help Tooltips (Scoped)
    wp_enqueue_style(
        'blog-over-customizer-tooltips-css',
        BLOG_OVER_URI . '/assets/css/customizer-tooltips.css',
        array(),
        BLOG_OVER_VERSION
    );

    wp_enqueue_script(
        'blog-over-customizer-tooltips-js',
        BLOG_OVER_URI . '/assets/js/customizer-tooltips.js',
        array('jquery', 'customize-controls'),
        BLOG_OVER_VERSION,
        true
    );

    // Generic customizer UX helpers (tab-limit awareness, etc.)
    wp_enqueue_script(
        'bo-cx-helpers',
        BLOG_OVER_URI . '/assets/js/customize-helpers.js',
        array('jquery', 'customize-controls'),
        BLOG_OVER_VERSION,
        true
    );

    // Auto-scroll behavior for Customizer panels
    wp_enqueue_script(
        'blog-over-customizer-auto-scroll',
        BLOG_OVER_URI . '/assets/js/customizer-auto-scroll.js',
        array('jquery', 'customize-controls'),
        BLOG_OVER_VERSION,
        true
    );

    wp_localize_script('bo-cx-helpers', '_boCustomizeHelpers', array(
        'isPro' => (function_exists('blog_over_is_pro_active') && blog_over_is_pro_active()) ? true : false,
    ));
}
add_action('customize_controls_enqueue_scripts', 'blog_over_customizer_scripts');

/**
 * Enqueue scripts in Customizer Preview for archive redirect functionality
 */
function blog_over_customizer_preview_init()
{
    wp_enqueue_script(
        'blog-over-customizer-archive-preview',
        BLOG_OVER_URI . '/assets/js/customizer-archive-preview.js',
        array('jquery', 'customize-preview'),
        BLOG_OVER_VERSION,
        true
    );

    // Breadcrumb Preview Script (handles dynamic pencil icon positioning in preview)
    wp_enqueue_script(
        'blog-over-customizer-breadcrumb-preview',
        BLOG_OVER_URI . '/assets/js/customizer-breadcrumb-preview.js',
        array('jquery', 'customize-preview'),
        BLOG_OVER_VERSION,
        true
    );

    // Auto-scroll handler in preview window
    wp_enqueue_script(
        'blog-over-customizer-preview-scroll',
        BLOG_OVER_URI . '/assets/js/customizer-preview-scroll.js',
        array('jquery', 'customize-preview'),
        BLOG_OVER_VERSION,
        true
    );
}
add_action('customize_preview_init', 'blog_over_customizer_preview_init');

/**
 * Enqueue CSS in Customizer Preview for Edit Shortcuts positioning
 */
function blog_over_customizer_preview_css()
{
    wp_add_inline_style('blog-over-style', '
        /* ======================================== 
           Customizer Edit Shortcuts (Pencil Icons)
           Position them near specific content elements
           ======================================== */
        
        /* Base positioning for all edit shortcuts */
        .customize-partial-edit-shortcut {
            z-index: 999 !important;
        }
        
        /* Ticker Section - near ticker-title label */
        .ticker-title .customize-partial-edit-shortcut {
            position: absolute !important;
            right: 10px !important;
            top: 50% !important;
            transform: translateY(-50%) !important;
            left: auto !important;
        }
        
        /* Hero Section - near wrapper content */
        .blog-over-hero-wrapper .customize-partial-edit-shortcut {
            position: absolute !important;
            left: 20px !important;
            top: 20px !important;
            right: auto !important;
        }
        
        /* Featured Links Section - near grid content */
        .blog-over-featured-grid .customize-partial-edit-shortcut {
            position: absolute !important;
            left: 20px !important;
            top: 20px !important;
            right: auto !important;
        }
        
        /* Make parent containers position relative */
        .ticker-title,
        .blog-over-hero-wrapper,
        .blog-over-featured-grid {
            position: relative !important;
        }
        
        /* Ensure pencil button is visible and styled nicely */
        .customize-partial-edit-shortcut button {
            background: linear-gradient(135deg, #0073aa, #005a87) !important;
            border-radius: 50% !important;
            box-shadow: 0 3px 12px rgba(0,0,0,0.4) !important;
            width: 32px !important;
            height: 32px !important;
            border: 2px solid #fff !important;
            transition: all 0.2s ease !important;
        }
        
        .customize-partial-edit-shortcut button:hover {
            background: linear-gradient(135deg, #005a87, #004165) !important;
            transform: scale(1.1) !important;
            box-shadow: 0 4px 16px rgba(0,0,0,0.5) !important;
        }
        
        /* Page Header Container - position pencil near centered content */
        .blog-over-page-header-container {
            position: relative !important;
        }
        .blog-over-page-header-container > .customize-partial-edit-shortcut,
        .customize-partial-edit-shortcut[data-customize-partial-id*="page_header"] {
            position: absolute !important;
            left: 50% !important;
            top: 20px !important;
            transform: translateX(-50%) !important;
            right: auto !important;
        }
        
        /* Page Header Wrapper - for edit shortcuts inside */
        .blog-over-page-header-wrapper {
            position: relative !important;
        }
        .blog-over-page-header-wrapper > .customize-partial-edit-shortcut {
            position: absolute !important;
            left: 50% !important;
            top: -15px !important;
            transform: translateX(-50%) !important;
        }
        
        /* Breadcrumb Container - position pencil centered above breadcrumb (when below header) */
        .blog-over-breadcrumb-container {
            position: relative !important;
        }
        .blog-over-breadcrumb-container > .customize-partial-edit-shortcut,
        .blog-over-breadcrumb-wrapper .customize-partial-edit-shortcut[data-customize-partial-id*="breadcrumb"] {
            position: absolute !important;
            left: 50% !important;
            top: 10px !important;
            transform: translateX(-50%) !important;
            right: auto !important;
        }
        
        /* Breadcrumb Wrapper - for edit shortcuts inside standalone breadcrumb */
        .blog-over-breadcrumb-wrapper {
            position: relative !important;
        }
        .blog-over-breadcrumb-wrapper > .customize-partial-edit-shortcut {
            position: absolute !important;
            left: 50% !important;
            top: -15px !important;
            transform: translateX(-50%) !important;
        }
        
        /* Breadcrumb inside Page Header - pencil icon centered above breadcrumb */
        .blog-over-page-header .blog-over-breadcrumb {
            position: relative !important;
        }
        .blog-over-page-header .blog-over-breadcrumb > .customize-partial-edit-shortcut {
            position: absolute !important;
            left: 50% !important;
            top: -25px !important;
            right: auto !important;
            transform: translateX(-50%) !important;
        }
        
        /* Breadcrumb nav element - position for pencil icon */
        .blog-over-breadcrumb {
            position: relative !important;
        }
        .blog-over-breadcrumb > .customize-partial-edit-shortcut {
            position: absolute !important;
            left: 50% !important;
            top: -20px !important;
            right: auto !important;
            transform: translateX(-50%) !important;
            z-index: 1000 !important;
        }
        
        /* Section edit shortcut for breadcrumb section - z-index fix */
        .blog-over-page-header .blog-over-breadcrumb > .customize-partial-edit-shortcut-button,
        .blog-over-breadcrumb-wrapper .blog-over-breadcrumb > .customize-partial-edit-shortcut-button {
            z-index: 1000 !important;
        }
        
        /* Ensure pencil icons on page title and breadcrumb text are inline */
        .blog-over-page-title {
            position: relative !important;
        }
        
        /* Highlight effect when breadcrumb section is focused */
        .blog-over-customizer-highlight {
            outline: 3px solid #0073aa !important;
            outline-offset: 5px !important;
            transition: outline 0.3s ease !important;
        }
        
        /* Hide empty breadcrumb container when breadcrumb is in page header */
        body.blog-over-breadcrumb-in-header .blog-over-breadcrumb-container:empty,
        body.blog-over-breadcrumb-in-header .blog-over-breadcrumb-container:not(:has(.blog-over-breadcrumb)) {
            display: none !important;
        }
        
        /* Author Box - position pencil near author avatar */
        .blog-over-author-box {
            position: relative !important;
        }
        .blog-over-author-box > .customize-partial-edit-shortcut {
            position: absolute !important;
            left: 20px !important;
            top: 20px !important;
            right: auto !important;
            z-index: 100 !important;
        }
        
        /* Post Navigation - position pencil near navigation */
        .blog-over-post-navigation {
            position: relative !important;
        }
        .blog-over-post-navigation > .customize-partial-edit-shortcut {
            position: absolute !important;
            left: 50% !important;
            top: 10px !important;
            transform: translateX(-50%) !important;
            right: auto !important;
            z-index: 100 !important;
        }
    ');
}
add_action('wp_enqueue_scripts', 'blog_over_customizer_preview_css', 100);

/**
 * Required Includes
 */
// Custom Controls
require_once BLOG_OVER_DIR . '/inc/controls/class-blog-over-toggle-control.php';
require_once BLOG_OVER_DIR . '/inc/controls/class-blog-over-radio-image-control.php';
require_once BLOG_OVER_DIR . '/inc/controls/class-blog-over-alpha-color-control.php';
require_once BLOG_OVER_DIR . '/inc/controls/class-blog-over-section-title-control.php';

// Pro Filter Choices (must load before Kirki customizer)
require_once BLOG_OVER_DIR . '/inc/pro-filters.php';

// Kirki Framework
require_once BLOG_OVER_DIR . '/assets/kirki/kirki.php';

// Core Theme Files
require_once BLOG_OVER_DIR . '/inc/class-blog-over-nav-walker.php';

// Defer Kirki customizer registration to after_setup_theme so that
// all the esc_html__() calls happen after WordPress has set up the
// text-domain (avoids the _load_textdomain_just_in_time notice on WP 6.7+).
function blog_over_load_kirki_customizer()
{
    require_once BLOG_OVER_DIR . '/inc/customizer-kirki.php';
    require_once BLOG_OVER_DIR . '/inc/customizer-pro-placeholders.php';
}
add_action('after_setup_theme', 'blog_over_load_kirki_customizer', 20);

require_once BLOG_OVER_DIR . '/inc/hooks.php';
require_once BLOG_OVER_DIR . '/inc/template-functions.php';
require_once BLOG_OVER_DIR . '/inc/template-meta.php';

// Custom Widgets
require_once BLOG_OVER_DIR . '/inc/widgets/class-blog-over-author-widget.php';
require_once BLOG_OVER_DIR . '/inc/widgets/class-blog-over-popular-posts-widget.php';

// Admin Dashboard & Theme Welcome
require_once BLOG_OVER_DIR . '/inc/admin/class-blog-over-admin.php';

// Demo Import Configuration
require_once BLOG_OVER_DIR . '/inc/demo-config.php';


/**
 * Add body classes based on layout settings
 */
function blog_over_body_classes($classes)
{
    // Add theme skin class (default skin on page load)
    $skin = get_theme_mod('blog_over_theme_skin', 'light');
    $classes[] = 'blog-over-skin-' . $skin;

    // Add blog-over-dark-mode class when theme skin is set to dark
    if ($skin === 'dark') {
        $classes[] = 'blog-over-dark-mode';
    }

    if (is_home() || is_archive()) {
        $layout = get_theme_mod('Blog_Over_layout', 'right-sidebar');
        $classes[] = 'blog-over-layout-' . $layout;
    }

    // Add single layout class
    if (is_single()) {
        $layout = get_theme_mod('blog_over_single_layout', 'single-right');
        $classes[] = 'blog-over-layout-' . $layout;
    }

    // Add page layout class
    if (is_page()) {
        $layout = get_theme_mod('blog_over_page_layout', 'page-right');
        $classes[] = 'blog-over-layout-' . $layout;

        // Add page content width class
        $page_content_width = get_theme_mod('blog_over_page_content_width', 'boxed');
        $classes[] = 'blog-over-page-width-' . $page_content_width;
    }

    // Add widget style class
    $widget_style = get_theme_mod('blog_over_widget_style', 'default');
    if ($widget_style && $widget_style !== 'default') {
        $classes[] = 'blog-over-widget-style-' . $widget_style;
    }

    // Add widget title style class
    $widget_title_style = get_theme_mod('blog_over_widget_title_style', 'default');
    $classes[] = 'blog-over-widget-title-' . $widget_title_style;

    // Add content alignment class (applies to all blog layouts)
    $alignment = get_theme_mod('blog_over_content_alignment', 'left');
    $allowed_alignments = array('left', 'center', 'right');
    if (in_array($alignment, $allowed_alignments, true)) {
        $classes[] = 'bo-content-align-' . $alignment;
    }

    // Add masonry grid class (only when modern-cards + masonry mode)
    $blog_style = get_theme_mod('Blog_Over_style', 'default');
    $grid_mode = get_theme_mod('blog_over_grid_layout_mode', 'default');
    if ($blog_style === 'modern-cards' && $grid_mode === 'masonry') {
        $classes[] = 'bo-grid-masonry';
    }

    // Add auto-height image class for Default blog style
    // Also check archive override: if archive uses default style, auto-height should apply
    $effective_style = $blog_style;
    if (is_archive() && get_theme_mod('blog_over_archive_override', false)) {
        $effective_style = get_theme_mod('blog_over_archive_style', 'default');
    }
    if ($effective_style === 'default' && get_theme_mod('blog_over_default_image_auto_height', 'off') === 'on') {
        $classes[] = 'blog-over-auto-height-image';
    }

    return $classes;
}
add_filter('body_class', 'blog_over_body_classes');

/**
 * Custom Excerpt Length based on Customizer setting
 * Supports archive override via blog_over_get_excerpt_length()
 * Priority set to 999 to ensure it overrides WordPress default and other plugins
 */
function blog_over_custom_excerpt_length($length)
{
    // Only apply on frontend, not in admin
    if (is_admin()) {
        return $length;
    }
    // Use the archive-aware excerpt length function
    return (int) blog_over_get_excerpt_length();
}
add_filter('excerpt_length', 'blog_over_custom_excerpt_length', 999);

/**
 * Custom Excerpt More text
 */
function blog_over_excerpt_more($more)
{
    return '...';
}
add_filter('excerpt_more', 'blog_over_excerpt_more');

/**
 * Trim excerpt to specified length (works for both auto and manual excerpts)
 * Supports archive override via blog_over_get_excerpt_length()
 * This ensures the excerpt respects the Customizer setting even for manual excerpts
 */
function blog_over_trim_excerpt($excerpt)
{
    // Only apply on frontend, not in admin
    if (is_admin()) {
        return $excerpt;
    }

    // Get the configured excerpt length (archive-aware)
    $excerpt_length = (int) blog_over_get_excerpt_length();

    // Strip tags and trim
    $excerpt_text = wp_strip_all_tags($excerpt);

    // Count words
    $words = explode(' ', $excerpt_text);

    // If excerpt is longer than limit, trim it
    if (count($words) > $excerpt_length) {
        $excerpt = implode(' ', array_slice($words, 0, $excerpt_length)) . '...';
        // Wrap in paragraph tag if it was stripped
        $excerpt = '<p>' . $excerpt . '</p>';
    }

    return $excerpt;
}
add_filter('get_the_excerpt', 'blog_over_trim_excerpt', 999);
