<?php

defined( 'ABSPATH' ) || exit;
// Track block usage (first render only)
if ( function_exists( 'ezhp_track_block_usage' ) ) {
    ezhp_track_block_usage( 'weekly-horoscope', $attributes );
}
$ezhp_sign = sanitize_text_field( $attributes['sign'] ?? 'aries' );
$ezhp_language = sanitize_text_field( $attributes['language'] ?? 'en' );
$ezhp_api_key = sanitize_text_field( get_option( 'ezhp_horoscope_activation_guid', '' ) );
// Column layout (1, 2, or 3)
$ezhp_column_layout = intval( $attributes['columnLayout'] ?? 1 );
$ezhp_column_layout = max( 1, min( 3, $ezhp_column_layout ) );
// Clamp between 1-3
// RTL language detection
$ezhp_rtl_languages = [
    'ar',
    'he',
    'fa',
    'ur',
    'ps',
    'sd',
    'yi',
    'ku',
    'dv',
    'ug',
    'arc',
    'azb',
    'ckb',
    'mzn',
    'pnb',
    'ks',
    'glk',
    'bal',
    'bqi',
    'luz',
    'gbz',
    'khw',
    'lrc',
    'prd',
    'sdh',
    'skr'
];
$ezhp_lang_base = strtolower( explode( '-', $ezhp_language )[0] );
// Handle variants like ar-SA, he-IL
$ezhp_is_rtl = in_array( $ezhp_lang_base, $ezhp_rtl_languages, true );
$ezhp_api_url = sprintf(
    'https://api.ezhoroscope.com/api/Horoscope/western-weekly?zodiacSign=%s&apikey=%s&language=%s',
    rawurlencode( $ezhp_sign ),
    rawurlencode( $ezhp_api_key ),
    rawurlencode( $ezhp_language )
);
// Build unique transient key (include sign, language, and heading toggle)
$ezhp_cache_key = 'ezhp_weekly_' . md5( $ezhp_sign . '_' . $ezhp_language . '_' . ($attributes['suppressHeading'] ?? '') );
// Try to load cached data first
$ezhp_cached_body = get_transient( $ezhp_cache_key );
$ezhp_body = false;
if ( false === $ezhp_cached_body ) {
    // Fetch fresh data from API
    $ezhp_response = wp_remote_get( $ezhp_api_url, [
        'timeout' => 20,
        'headers' => [
            'Accept' => 'application/json',
        ],
    ] );
    if ( is_wp_error( $ezhp_response ) ) {
        echo '<div class="ez-horoscope-block-error">' . esc_html__( 'Unable to retrieve horoscope at this time.', 'ez-horoscope' ) . ' Debug: ' . esc_html( $ezhp_response->get_error_message() ) . '</div>';
        return;
    }
    $ezhp_body = wp_remote_retrieve_body( $ezhp_response );
    // Only cache if body doesn't contain "error"
    if ( stripos( $ezhp_body, 'error' ) === false && !empty( $ezhp_body ) ) {
        set_transient( $ezhp_cache_key, $ezhp_body, HOUR_IN_SECONDS );
    }
} else {
    // Use cached response
    $ezhp_body = $ezhp_cached_body;
}
// Ensure $ezhp_body exists and is decoded properly
if ( empty( $ezhp_body ) ) {
    echo '<div class="ez-horoscope-block-error">' . esc_html__( 'Empty response from horoscope API.', 'ez-horoscope' ) . '</div>';
    return;
}
$ezhp_data = json_decode( $ezhp_body, true );
// Validate decoded structure
if ( !is_array( $ezhp_data ) || !isset( $ezhp_data['horoscopeText'] ) || empty( $ezhp_data['horoscopeText'] ) ) {
    // Delete bad cache so next request fetches fresh data
    delete_transient( $ezhp_cache_key );
    echo '<div class="ez-horoscope-block-error">' . esc_html__( 'Unable to decode horoscope data. Retrying later.', 'ez-horoscope' ) . '</div>';
    return;
}
// ============================================================================
// COLUMN LAYOUT INJECTION
// Add column class to the flexbox container
// ============================================================================
if ( isset( $ezhp_data['horoscopeText'] ) ) {
    $ezhp_html = $ezhp_data['horoscopeText'];
    // Add column layout class to the flexbox container
    $ezhp_column_class = 'ez-weekly-columns-' . $ezhp_column_layout;
    // Find the eztype-flexbox-container and add our column class
    $ezhp_html = preg_replace(
        '/(<div[^>]*class=["\'])([^"\']*eztype-flexbox-container[^"\']*)(["\']\\s*>)/is',
        '$1$2 ' . $ezhp_column_class . '$3',
        $ezhp_html,
        1
    );
    $ezhp_data['horoscopeText'] = $ezhp_html;
}
// ============================================================================
// SECTION HEADING LEVEL TRANSFORMATION
// Must happen BEFORE daily image injection so the <strong> tags are still in place
// ============================================================================
$ezhp_section_heading_level = $attributes['sectionHeadingLevel'] ?? 'bold';
if ( $ezhp_section_heading_level !== 'bold' && isset( $ezhp_data['horoscopeText'] ) ) {
    // Validate heading level
    $ezhp_valid_levels = ['h2', 'h3', 'h4'];
    if ( in_array( $ezhp_section_heading_level, $ezhp_valid_levels, true ) ) {
        $ezhp_tag = $ezhp_section_heading_level;
        // Replace <strong> tags that appear immediately after eztype-flexbox-content div opening
        // This targets only the section headers, not other bold text in paragraphs
        $ezhp_data['horoscopeText'] = preg_replace( '/<div\\s+class="eztype-flexbox-content">\\s*<strong>(.*?)<\\/strong>/is', '<div class="eztype-flexbox-content"><' . $ezhp_tag . ' class="ez-weekly-section-heading">$1</' . $ezhp_tag . '>', $ezhp_data['horoscopeText'] );
    }
}
// ============================================================================
// DEFAULT IMAGES - Planet images for each day of the week
// ============================================================================
// Get the plugin's assets URL for default images
$ezhp_plugin_url = plugins_url( 'assets/images/days-of-week/', dirname( dirname( dirname( __FILE__ ) ) ) );
// Map section IDs to default image filenames
$ezhp_default_images = [
    'weekly-sunday'    => $ezhp_plugin_url . 'sun.jpg',
    'weekly-monday'    => $ezhp_plugin_url . 'moon.jpg',
    'weekly-tuesday'   => $ezhp_plugin_url . 'mars.jpg',
    'weekly-wednesday' => $ezhp_plugin_url . 'mercury.jpg',
    'weekly-thursday'  => $ezhp_plugin_url . 'jupiter.jpg',
    'weekly-friday'    => $ezhp_plugin_url . 'venus.jpg',
    'weekly-saturday'  => $ezhp_plugin_url . 'saturn.jpg',
    'weekly-summary'   => $ezhp_plugin_url . 'cosmos.jpg',
];
// ============================================================================
// DAILY IMAGE REPLACEMENT (Background or Inline mode)
// ============================================================================
// Build daily images array - use custom URL if set, otherwise use default
$ezhp_daily_images = [
    'weekly-sunday'    => ( !empty( $attributes['sundayImageUrl'] ) ? $attributes['sundayImageUrl'] : $ezhp_default_images['weekly-sunday'] ),
    'weekly-monday'    => ( !empty( $attributes['mondayImageUrl'] ) ? $attributes['mondayImageUrl'] : $ezhp_default_images['weekly-monday'] ),
    'weekly-tuesday'   => ( !empty( $attributes['tuesdayImageUrl'] ) ? $attributes['tuesdayImageUrl'] : $ezhp_default_images['weekly-tuesday'] ),
    'weekly-wednesday' => ( !empty( $attributes['wednesdayImageUrl'] ) ? $attributes['wednesdayImageUrl'] : $ezhp_default_images['weekly-wednesday'] ),
    'weekly-thursday'  => ( !empty( $attributes['thursdayImageUrl'] ) ? $attributes['thursdayImageUrl'] : $ezhp_default_images['weekly-thursday'] ),
    'weekly-friday'    => ( !empty( $attributes['fridayImageUrl'] ) ? $attributes['fridayImageUrl'] : $ezhp_default_images['weekly-friday'] ),
    'weekly-saturday'  => ( !empty( $attributes['saturdayImageUrl'] ) ? $attributes['saturdayImageUrl'] : $ezhp_default_images['weekly-saturday'] ),
    'weekly-summary'   => ( !empty( $attributes['summaryImageUrl'] ) ? $attributes['summaryImageUrl'] : $ezhp_default_images['weekly-summary'] ),
];
// Shared daily image settings - NEW DEFAULTS: inline mode with left wrap
$ezhp_daily_display_mode = $attributes['dailyImageDisplayMode'] ?? 'inline';
$ezhp_daily_alignment = esc_attr( $attributes['dailyImageAlignment'] ?? 'center' );
$ezhp_daily_text_wrap = $attributes['dailyImageTextWrap'] ?? 'left';
$ezhp_daily_max_width = esc_attr( $attributes['dailyImageMaxWidth'] ?? '40%' );
$ezhp_daily_overlay_opacity = ( isset( $attributes['dailyImageOverlayOpacity'] ) ? floatval( $attributes['dailyImageOverlayOpacity'] ) : 40 );
$ezhp_daily_overlay_opacity = max( 0, min( 100, $ezhp_daily_overlay_opacity ) );
$ezhp_daily_overlay_color_name = $attributes['dailyImageOverlayColor'] ?? 'black';
$ezhp_daily_overlay_color = ( $ezhp_daily_overlay_color_name === 'white' ? '255,255,255' : '0,0,0' );
$ezhp_daily_overlay_class = ( $ezhp_daily_overlay_color_name === 'white' ? 'ez-daily-overlay light' : 'ez-daily-overlay dark' );
// Apply daily image replacements
if ( isset( $ezhp_data['horoscopeText'] ) ) {
    $ezhp_html = $ezhp_data['horoscopeText'];
    foreach ( $ezhp_daily_images as $ezhp_section_id => $ezhp_custom_image_url ) {
        if ( !empty( $ezhp_custom_image_url ) ) {
            $ezhp_safe_url = esc_url( $ezhp_custom_image_url );
            if ( $ezhp_daily_display_mode === 'background' ) {
                // ====== BACKGROUND MODE ======
                // Replace the URL in the existing background div and apply alignment
                $ezhp_new_bg_style = sprintf( 'background-image: url(\'%s\'); background-size: cover; background-repeat: no-repeat; background-position: %s;', $ezhp_safe_url, $ezhp_daily_alignment );
                // Pattern to find section by ID and replace background div style
                $ezhp_pattern = '/(<div[^>]*\\bid=["\']' . preg_quote( $ezhp_section_id, '/' ) . '["\'][^>]*>)\\s*(<div[^>]*class=["\'][^"\']*eztype-flexbox-background[^"\']*["\'][^>]*)style=["\'][^"\']*["\']/is';
                $ezhp_html = preg_replace(
                    $ezhp_pattern,
                    '$1$2style="' . $ezhp_new_bg_style . '"',
                    $ezhp_html,
                    1,
                    // Limit to 1 replacement
                    $ezhp_replace_count
                );
                // Only try alternative pattern if first didn't match
                if ( $ezhp_replace_count === 0 ) {
                    $ezhp_pattern_alt = '/(<div[^>]*class=["\'][^"\']*eztype-flexbox-item[^"\']*["\'][^>]*\\bid=["\']' . preg_quote( $ezhp_section_id, '/' ) . '["\'][^>]*>)\\s*(<div[^>]*class=["\'][^"\']*eztype-flexbox-background[^"\']*["\'][^>]*)style=["\'][^"\']*["\']/is';
                    $ezhp_html = preg_replace(
                        $ezhp_pattern_alt,
                        '$1$2style="' . $ezhp_new_bg_style . '"',
                        $ezhp_html,
                        1
                    );
                }
                // Add overlay div for background mode
                if ( $ezhp_daily_overlay_opacity > 0 ) {
                    $ezhp_opacity_css = $ezhp_daily_overlay_opacity / 100;
                    $ezhp_overlay_style = sprintf( 'background-color: rgba(%s, %.2f);', $ezhp_daily_overlay_color, $ezhp_opacity_css );
                    $ezhp_overlay_html = sprintf( '<div class="%s" style="%s"></div>', esc_attr( $ezhp_daily_overlay_class ), esc_attr( $ezhp_overlay_style ) );
                    // Insert overlay after the background div within this section
                    $ezhp_overlay_pattern = '/(<div[^>]*\\bid=["\']' . preg_quote( $ezhp_section_id, '/' ) . '["\'][^>]*>)\\s*(<div[^>]*class=["\'][^"\']*eztype-flexbox-background[^"\']*["\'][^>]*>)/is';
                    $ezhp_html = preg_replace(
                        $ezhp_overlay_pattern,
                        '$1$2' . $ezhp_overlay_html,
                        $ezhp_html,
                        1,
                        $ezhp_overlay_count
                    );
                    // Try alternative pattern if first didn't match
                    if ( $ezhp_overlay_count === 0 ) {
                        $ezhp_overlay_pattern_alt = '/(<div[^>]*class=["\'][^"\']*eztype-flexbox-item[^"\']*["\'][^>]*\\bid=["\']' . preg_quote( $ezhp_section_id, '/' ) . '["\'][^>]*>)\\s*(<div[^>]*class=["\'][^"\']*eztype-flexbox-background[^"\']*["\'][^>]*>)/is';
                        $ezhp_html = preg_replace(
                            $ezhp_overlay_pattern_alt,
                            '$1$2' . $ezhp_overlay_html,
                            $ezhp_html,
                            1
                        );
                    }
                }
            } else {
                // ====== INLINE MODE ======
                // Hide the existing background div
                $ezhp_hide_pattern = '/(<div[^>]*\\bid=["\']' . preg_quote( $ezhp_section_id, '/' ) . '["\'][^>]*>)\\s*(<div[^>]*class=["\'][^"\']*eztype-flexbox-background[^"\']*["\'][^>]*)style=["\']([^"\']*)["\']([^>]*>)/is';
                $ezhp_html = preg_replace(
                    $ezhp_hide_pattern,
                    '$1$2style="$3 display:none;"$4',
                    $ezhp_html,
                    1,
                    $ezhp_hide_count
                );
                // Only try alternative if first didn't match
                if ( $ezhp_hide_count === 0 ) {
                    $ezhp_hide_pattern_alt = '/(<div[^>]*class=["\'][^"\']*eztype-flexbox-item[^"\']*["\'][^>]*\\bid=["\']' . preg_quote( $ezhp_section_id, '/' ) . '["\'][^>]*>)\\s*(<div[^>]*class=["\'][^"\']*eztype-flexbox-background[^"\']*["\'][^>]*)style=["\']([^"\']*)["\']([^>]*>)/is';
                    $ezhp_html = preg_replace(
                        $ezhp_hide_pattern_alt,
                        '$1$2style="$3 display:none;"$4',
                        $ezhp_html,
                        1
                    );
                }
                // Determine float/margin style based on text wrap setting (RTL-aware)
                $ezhp_float_style = '';
                if ( $ezhp_daily_text_wrap === 'left' ) {
                    $ezhp_float_style = ( $ezhp_is_rtl ? 'float:right; margin:0 0 1rem 1rem;' : 'float:left; margin:0 1rem 1rem 0;' );
                } elseif ( $ezhp_daily_text_wrap === 'right' ) {
                    $ezhp_float_style = ( $ezhp_is_rtl ? 'float:left; margin:0 1rem 1rem 0;' : 'float:right; margin:0 0 1rem 1rem;' );
                } else {
                    // none = centered
                    $ezhp_float_style = 'display:block; margin:0 auto 1rem auto;';
                }
                // Build inline image with optional overlay
                $ezhp_inline_html = '<div class="ez-daily-inline-image" style="position:relative; ' . $ezhp_float_style . ' max-width:' . $ezhp_daily_max_width . ';">';
                $ezhp_inline_html .= '<img src="' . $ezhp_safe_url . '" alt="" style="width:100%; height:auto; border-radius:8px; display:block;">';
                // Add overlay if opacity > 0
                if ( $ezhp_daily_overlay_opacity > 0 ) {
                    $ezhp_opacity_css = $ezhp_daily_overlay_opacity / 100;
                    $ezhp_inline_html .= sprintf(
                        '<div class="%s" style="position:absolute; top:0; left:0; right:0; bottom:0; background-color:rgba(%s,%.2f); border-radius:8px; pointer-events:none;"></div>',
                        esc_attr( $ezhp_daily_overlay_class ),
                        $ezhp_daily_overlay_color,
                        $ezhp_opacity_css
                    );
                }
                $ezhp_inline_html .= '</div>';
                // Insert inline image at the start of the content div for this section
                // Pattern: find the section, then find its content div
                $ezhp_content_pattern = '/(<div[^>]*\\bid=["\']' . preg_quote( $ezhp_section_id, '/' ) . '["\'][^>]*>.*?<div[^>]*class=["\'][^"\']*eztype-flexbox-content[^"\']*["\'][^>]*>)/is';
                $ezhp_html = preg_replace(
                    $ezhp_content_pattern,
                    '$1' . $ezhp_inline_html,
                    $ezhp_html,
                    1,
                    // Limit to 1 replacement per section
                    $ezhp_inline_count
                );
                // Only try alternative pattern if first didn't match
                if ( $ezhp_inline_count === 0 ) {
                    $ezhp_content_pattern_alt = '/(<div[^>]*class=["\'][^"\']*eztype-flexbox-item[^"\']*["\'][^>]*\\bid=["\']' . preg_quote( $ezhp_section_id, '/' ) . '["\'][^>]*>.*?<div[^>]*class=["\'][^"\']*eztype-flexbox-content[^"\']*["\'][^>]*>)/is';
                    $ezhp_html = preg_replace(
                        $ezhp_content_pattern_alt,
                        '$1' . $ezhp_inline_html,
                        $ezhp_html,
                        1
                    );
                }
            }
        }
    }
    $ezhp_data['horoscopeText'] = $ezhp_html;
}
// ============================================================================
// HERO IMAGE INJECTION (existing functionality)
// ============================================================================
// Build default hero image URL based on zodiac sign
$ezhp_zodiac_images_url = plugins_url( 'assets/images/zodiac/', dirname( dirname( dirname( __FILE__ ) ) ) );
$ezhp_default_hero_url = $ezhp_zodiac_images_url . 'ez-' . $ezhp_sign . '.jpg';
// Inject hero image configuration before processing headings.
$ezhp_hero_url = ( !empty( $attributes['heroImageUrl'] ) ? $attributes['heroImageUrl'] : $ezhp_default_hero_url );
$ezhp_hero_mode = $attributes['heroImageDisplayMode'] ?? 'inline';
$ezhp_hero_align = $attributes['heroImageAlignment'] ?? 'center';
$ezhp_hero_wrap = $attributes['heroImageTextWrap'] ?? 'none';
$ezhp_hero_overlay = $attributes['heroImageOverlay'] ?? 'none';
$ezhp_hero_alt = esc_attr( $attributes['heroImageAlt'] ?? '' );
// If the API response contains the .ez-hero section and a hero image is set, inject style or image
if ( !empty( $ezhp_hero_url ) && isset( $ezhp_data['horoscopeText'] ) ) {
    $ezhp_html = $ezhp_data['horoscopeText'];
    // Handle weekly horoscope layout (<section class="eztype-flexbox-section">)
    if ( strpos( $ezhp_html, 'eztype-flexbox-section' ) !== false ) {
        if ( $ezhp_hero_mode === 'background' && !empty( $ezhp_hero_url ) ) {
            // Remove any existing eztype-flexbox-background div (replace it dynamically)
            $ezhp_html = preg_replace( '/<div[^>]*class="eztype-flexbox-background[^>]*>.*?<\\/div>/is', '', $ezhp_html );
            // Build the inline background style safely
            $ezhp_bg_url = esc_url( $ezhp_hero_url );
            $ezhp_bg_align = esc_attr( $ezhp_hero_align );
            $ezhp_style = "background-image: url('{$ezhp_bg_url}'); " . "background-size: cover; background-repeat: no-repeat; " . "background-position: {$ezhp_bg_align}; display:block; position:relative;";
            // Inject style attribute into .eztype-flexbox-item (id may appear before or after class)
            $ezhp_html = preg_replace_callback(
                '/<div([^>]*\\bclass="[^"]*eztype-flexbox-item[^"]*"[^>]*\\bid="weekly-week-ahead"[^>]*)>/i',
                function ( $ezhp_match ) use($ezhp_style) {
                    if ( strpos( $ezhp_match[1], 'style=' ) !== false ) {
                        // Append to existing style attribute (no esc_attr — already sanitized)
                        return '<div' . preg_replace( '/style="([^"]*)"/i', 'style="$1 ' . $ezhp_style . '"', $ezhp_match[1] ) . '>';
                    } else {
                        // Insert new style attribute (no esc_attr — already sanitized)
                        return '<div' . $ezhp_match[1] . ' style="' . $ezhp_style . '">';
                    }
                },
                $ezhp_html,
                1
            );
            // Add overlay div
            $ezhp_overlay_opacity = ( isset( $attributes['heroImageOverlayOpacity'] ) ? floatval( $attributes['heroImageOverlayOpacity'] ) : 50 );
            $ezhp_overlay_opacity = max( 0, min( 100, $ezhp_overlay_opacity ) );
            if ( $ezhp_overlay_opacity > 0 ) {
                $ezhp_opacity_css = $ezhp_overlay_opacity / 100;
                $ezhp_overlay_color = ( isset( $attributes['heroImageOverlayColor'] ) && $attributes['heroImageOverlayColor'] === 'white' ? '255,255,255' : '0,0,0' );
                $ezhp_overlay_class = ( $attributes['heroImageOverlayColor'] === 'white' ? 'ez-weekly-overlay light' : 'ez-weekly-overlay dark' );
                $ezhp_overlay_style = sprintf( '--ezhp-overlay-opacity: %.2f; background-color: rgba(%s, var(--ezhp-overlay-opacity)); opacity:1;', $ezhp_opacity_css, $ezhp_overlay_color );
                $ezhp_overlay_html = '<div class="' . esc_attr( $ezhp_overlay_class ) . '" data-opacity="' . intval( $ezhp_overlay_opacity ) . '" style="' . esc_attr( $ezhp_overlay_style ) . '"></div>';
                // Insert overlay immediately *before* the content container
                $ezhp_html = preg_replace(
                    '/(<div[^>]*class="eztype-flexbox-content"[^>]*>)/i',
                    $ezhp_overlay_html . '$1',
                    $ezhp_html,
                    1
                );
            }
        } elseif ( $ezhp_hero_mode === 'inline' && !empty( $ezhp_hero_url ) ) {
            // Determine float and margin style based on wrap setting
            // RTL-aware: swap left/right for RTL languages
            $ezhp_float_style = '';
            if ( $ezhp_hero_wrap === 'left' ) {
                $ezhp_float_style = ( $ezhp_is_rtl ? 'float:right; margin:0 0 1rem 1rem;' : 'float:left; margin:0 1rem 1rem 0;' );
            } elseif ( $ezhp_hero_wrap === 'right' ) {
                $ezhp_float_style = ( $ezhp_is_rtl ? 'float:left; margin:0 1rem 1rem 0;' : 'float:right; margin:0 0 1rem 1rem;' );
            } else {
                // none = centered
                $ezhp_float_style = 'display:block; margin:0 auto 1rem auto;';
            }
            // Apply max-width from attribute
            $ezhp_hero_max_width = $attributes['heroImageMaxWidth'] ?? '40%';
            // Build inline image with optional overlay (float on container, not img)
            $ezhp_inline_html = '<div class="ez-weekly-inline-image" style="position:relative; ' . $ezhp_float_style . ' max-width:' . esc_attr( $ezhp_hero_max_width ) . ';">';
            $ezhp_inline_html .= '<img src="' . esc_url( $ezhp_hero_url ) . '" alt="' . $ezhp_hero_alt . '" style="width:100%; height:auto; border-radius:8px; display:block;">';
            // Add overlay if opacity > 0
            $ezhp_hero_overlay_opacity = ( isset( $attributes['heroImageOverlayOpacity'] ) ? floatval( $attributes['heroImageOverlayOpacity'] ) : 50 );
            if ( $ezhp_hero_overlay_opacity > 0 ) {
                $ezhp_opacity_css = $ezhp_hero_overlay_opacity / 100;
                $ezhp_overlay_color = ( isset( $attributes['heroImageOverlayColor'] ) && $attributes['heroImageOverlayColor'] === 'white' ? '255,255,255' : '0,0,0' );
                $ezhp_overlay_class = ( $attributes['heroImageOverlayColor'] === 'white' ? 'ez-weekly-overlay light' : 'ez-weekly-overlay dark' );
                $ezhp_inline_html .= sprintf(
                    '<div class="%s" style="position:absolute; top:0; left:0; right:0; bottom:0; background-color:rgba(%s,%.2f); border-radius:8px; pointer-events:none;"></div>',
                    esc_attr( $ezhp_overlay_class ),
                    $ezhp_overlay_color,
                    $ezhp_opacity_css
                );
            }
            $ezhp_inline_html .= '</div>';
            // Hide the existing background div in the weekly-week-ahead section
            $ezhp_hide_pattern = '/(<div[^>]*\\bid=["\']weekly-week-ahead["\'][^>]*>)\\s*(<div[^>]*class=["\'][^"\']*eztype-flexbox-background[^"\']*["\'][^>]*)style=["\']([^"\']*)["\']([^>]*>)/is';
            $ezhp_html = preg_replace(
                $ezhp_hide_pattern,
                '$1$2style="$3 display:none;"$4',
                $ezhp_html,
                1,
                $ezhp_hide_count
            );
            // Try alternative pattern if first didn't match (class and id in different order)
            if ( $ezhp_hide_count === 0 ) {
                $ezhp_hide_pattern_alt = '/(<div[^>]*class=["\'][^"\']*eztype-flexbox-item[^"\']*["\'][^>]*\\bid=["\']weekly-week-ahead["\'][^>]*>)\\s*(<div[^>]*class=["\'][^"\']*eztype-flexbox-background[^"\']*["\'][^>]*)style=["\']([^"\']*)["\']([^>]*>)/is';
                $ezhp_html = preg_replace(
                    $ezhp_hide_pattern_alt,
                    '$1$2style="$3 display:none;"$4',
                    $ezhp_html,
                    1
                );
            }
            // Insert inline image inside the content area before first paragraph
            $ezhp_html = preg_replace(
                '/(<div[^>]*class="eztype-flexbox-content"[^>]*>)/i',
                '$1' . $ezhp_inline_html,
                $ezhp_html,
                1
            );
        }
    }
    if ( $ezhp_hero_mode === 'background' ) {
        // Build background CSS
        $ezhp_style = "background-image:url('" . esc_url( $ezhp_hero_url ) . "');";
        $ezhp_style .= "background-size:cover;background-repeat:no-repeat;background-position:" . esc_attr( $ezhp_hero_align ) . ";";
        $ezhp_style .= "display:block;min-height:300px;";
        // Inject inline background CSS into existing <section class="ez-hero">
        $ezhp_html = preg_replace(
            '/(<section[^>]*class="ez-hero"[^>]*)(>)/is',
            '$1 style="' . $ezhp_style . '"$2',
            $ezhp_html,
            1
        );
        // Optional overlay div
        // Add overlay div — identical logic to daily version
        $ezhp_overlay_opacity = ( isset( $attributes['heroImageOverlayOpacity'] ) ? floatval( $attributes['heroImageOverlayOpacity'] ) : 50 );
        $ezhp_overlay_opacity = max( 0, min( 100, $ezhp_overlay_opacity ) );
        if ( $ezhp_overlay_opacity > 0 ) {
            $ezhp_opacity_css = $ezhp_overlay_opacity / 100;
            // Determine overlay tint (black or white)
            $ezhp_overlay_color = ( isset( $attributes['heroImageOverlayColor'] ) && $attributes['heroImageOverlayColor'] === 'white' ? '255,255,255' : '0,0,0' );
            // Build complete overlay style (color + opacity)
            $ezhp_overlay_class = ( $attributes['heroImageOverlayColor'] === 'white' ? 'ez-weekly-overlay light' : 'ez-weekly-overlay dark' );
            $ezhp_overlay_style = sprintf( 'background-color:rgba(%s,%.2f); opacity:1;', $ezhp_overlay_color, $ezhp_opacity_css );
            // Ensure overlay fills hero area fully
            $ezhp_overlay_style .= ' position:absolute; top:0; left:0; right:0; bottom:0; pointer-events:none;';
            // Build overlay div
            $ezhp_overlay_html = '<div class="' . esc_attr( $ezhp_overlay_class ) . '" style="' . $ezhp_overlay_style . '"></div>';
            // Inject overlay div before the content container, same pattern as daily
            $ezhp_html = preg_replace(
                '/(<div\\s+class="eztype-flexbox-content">)/i',
                $ezhp_overlay_html . '$1',
                $ezhp_html,
                1
            );
        }
    } elseif ( $ezhp_hero_mode === 'inline' ) {
        // Insert inline image into .ez-hero-text
        // RTL-aware: swap left/right for RTL languages
        $ezhp_float_style = '';
        if ( $ezhp_hero_wrap === 'left' ) {
            $ezhp_float_style = ( $ezhp_is_rtl ? 'float:right; margin:0 0 1rem 1rem;' : 'float:left; margin:0 1rem 1rem 0;' );
        } elseif ( $ezhp_hero_wrap === 'right' ) {
            $ezhp_float_style = ( $ezhp_is_rtl ? 'float:left; margin:0 1rem 1rem 0;' : 'float:right; margin:0 0 1rem 1rem;' );
        } else {
            // none = centered
            $ezhp_float_style = 'display:block; margin:0 auto 1rem auto;';
        }
        $ezhp_hero_max_width = $attributes['heroImageMaxWidth'] ?? '40%';
        // Build inline image with optional overlay (float on container, not img)
        $ezhp_inline_html = '<div class="ez-weekly-inline-image" style="position:relative; ' . $ezhp_float_style . ' max-width:' . esc_attr( $ezhp_hero_max_width ) . ';">';
        $ezhp_inline_html .= '<img src="' . esc_url( $ezhp_hero_url ) . '" alt="' . $ezhp_hero_alt . '" style="width:100%; height:auto; border-radius:6px; display:block;">';
        // Add overlay if opacity > 0
        $ezhp_hero_overlay_opacity = ( isset( $attributes['heroImageOverlayOpacity'] ) ? floatval( $attributes['heroImageOverlayOpacity'] ) : 50 );
        if ( $ezhp_hero_overlay_opacity > 0 ) {
            $ezhp_opacity_css = $ezhp_hero_overlay_opacity / 100;
            $ezhp_overlay_color = ( isset( $attributes['heroImageOverlayColor'] ) && $attributes['heroImageOverlayColor'] === 'white' ? '255,255,255' : '0,0,0' );
            $ezhp_overlay_class = ( $attributes['heroImageOverlayColor'] === 'white' ? 'ez-weekly-overlay light' : 'ez-weekly-overlay dark' );
            $ezhp_inline_html .= sprintf(
                '<div class="%s" style="position:absolute; top:0; left:0; right:0; bottom:0; background-color:rgba(%s,%.2f); border-radius:6px; pointer-events:none;"></div>',
                esc_attr( $ezhp_overlay_class ),
                $ezhp_overlay_color,
                $ezhp_opacity_css
            );
        }
        $ezhp_inline_html .= '</div>';
        $ezhp_html = preg_replace(
            '/(<div\\s+class="ez-hero-text">)/i',
            '$1' . $ezhp_inline_html,
            $ezhp_html,
            1
        );
    }
    $ezhp_data['horoscopeText'] = $ezhp_html;
}
// Optionally suppress <h1> heading if requested.
$ezhp_suppress_heading = !empty( $attributes['suppressHeading'] ) && $attributes['suppressHeading'];
if ( $ezhp_suppress_heading && isset( $ezhp_data['horoscopeText'] ) ) {
    // Remove heading tags (<h1> or <h2 class="eztype-flexbox-heading">)
    $ezhp_data['horoscopeText'] = preg_replace( '/<(h1|h2)\\b[^>]*class="[^"]*\\beztype-flexbox-heading\\b[^"]*"[^>]*>.*?<\\/\\1>/is', '', $ezhp_data['horoscopeText'] );
}
// ============================================================================
// CALL TO ACTION INJECTION (Premium Feature)
// Shows in editor for all users (preview), but only on frontend for premium users
// ============================================================================
$ezhp_cta_placement = $attributes['ctaPlacement'] ?? 'none';
// Determine if we should render the CTA
$ezhp_is_editor_preview = defined( 'REST_REQUEST' ) && REST_REQUEST;
$ezhp_render_cta = false;
// Always show in editor preview for all users
if ( $ezhp_is_editor_preview ) {
    $ezhp_render_cta = true;
}
if ( $ezhp_render_cta && $ezhp_cta_placement !== 'none' && isset( $ezhp_data['horoscopeText'] ) ) {
    $ezhp_cta_headline = sanitize_text_field( $attributes['ctaHeadline'] ?? '' );
    $ezhp_cta_heading_level = ( in_array( $attributes['ctaHeadingLevel'] ?? 'h3', ['h2', 'h3', 'h4'], true ) ? $attributes['ctaHeadingLevel'] : 'h3' );
    $ezhp_cta_text = sanitize_textarea_field( $attributes['ctaText'] ?? '' );
    $ezhp_cta_button_text = sanitize_text_field( $attributes['ctaButtonText'] ?? '' );
    $ezhp_cta_button_url = esc_url( $attributes['ctaButtonUrl'] ?? '' );
    $ezhp_cta_image_url = esc_url( $attributes['ctaImageUrl'] ?? '' );
    $ezhp_cta_image_alt = esc_attr( $attributes['ctaImageAlt'] ?? '' );
    $ezhp_cta_image_clickable = !empty( $attributes['ctaImageClickable'] );
    $ezhp_cta_image_max_width = esc_attr( $attributes['ctaImageMaxWidth'] ?? '100%' );
    $ezhp_cta_bg_color = sanitize_hex_color( $attributes['ctaBackgroundColor'] ?? '' );
    $ezhp_cta_bg_transparent = !empty( $attributes['ctaBackgroundTransparent'] );
    $ezhp_cta_button_color = sanitize_hex_color( $attributes['ctaButtonColor'] ?? '' );
    // Build CTA HTML with optional custom background
    $ezhp_cta_style = '';
    $ezhp_cta_class = 'ez-weekly-cta';
    if ( $ezhp_cta_bg_transparent ) {
        $ezhp_cta_style = ' style="background: transparent; box-shadow: none; border: none;"';
        $ezhp_cta_class .= ' ez-weekly-cta-transparent';
    } elseif ( !empty( $ezhp_cta_bg_color ) ) {
        $ezhp_cta_style = sprintf( ' style="background: %s;"', $ezhp_cta_bg_color );
    }
    $ezhp_cta_html = '<div class="' . $ezhp_cta_class . '"' . $ezhp_cta_style . '>';
    // Headline
    if ( !empty( $ezhp_cta_headline ) ) {
        $ezhp_cta_html .= sprintf( '<%1$s class="ez-weekly-cta-headline">%2$s</%1$s>', $ezhp_cta_heading_level, esc_html( $ezhp_cta_headline ) );
    }
    // Image (above text/button)
    if ( !empty( $ezhp_cta_image_url ) ) {
        $ezhp_cta_img_tag = sprintf(
            '<img src="%s" alt="%s" class="ez-weekly-cta-image" style="max-width: %s;">',
            $ezhp_cta_image_url,
            $ezhp_cta_image_alt,
            $ezhp_cta_image_max_width
        );
        if ( $ezhp_cta_image_clickable && !empty( $ezhp_cta_button_url ) ) {
            $ezhp_cta_html .= sprintf( '<a href="%s" class="ez-weekly-cta-image-link">%s</a>', $ezhp_cta_button_url, $ezhp_cta_img_tag );
        } else {
            $ezhp_cta_html .= $ezhp_cta_img_tag;
        }
    }
    // Description text
    if ( !empty( $ezhp_cta_text ) ) {
        $ezhp_cta_html .= sprintf( '<p class="ez-weekly-cta-text">%s</p>', esc_html( $ezhp_cta_text ) );
    }
    // Button
    if ( !empty( $ezhp_cta_button_text ) && !empty( $ezhp_cta_button_url ) ) {
        $ezhp_button_style = '';
        if ( !empty( $ezhp_cta_button_color ) ) {
            $ezhp_button_style = sprintf( ' style="background: %s;"', $ezhp_cta_button_color );
        }
        $ezhp_cta_html .= sprintf(
            '<a href="%s" class="ez-weekly-cta-button"%s>%s</a>',
            $ezhp_cta_button_url,
            $ezhp_button_style,
            esc_html( $ezhp_cta_button_text )
        );
    }
    $ezhp_cta_html .= '</div>';
    // Map placement to section ID
    $ezhp_cta_section_map = [
        'after-week-ahead' => 'weekly-week-ahead',
        'after-sunday'     => 'weekly-sunday',
        'after-monday'     => 'weekly-monday',
        'after-tuesday'    => 'weekly-tuesday',
        'after-wednesday'  => 'weekly-wednesday',
        'after-thursday'   => 'weekly-thursday',
        'after-friday'     => 'weekly-friday',
        'after-saturday'   => 'weekly-saturday',
        'after-summary'    => 'weekly-summary',
    ];
    $ezhp_target_section = $ezhp_cta_section_map[$ezhp_cta_placement] ?? '';
    if ( !empty( $ezhp_target_section ) ) {
        // Define the order of sections to find what comes AFTER the target
        $ezhp_section_order = [
            'weekly-week-ahead',
            'weekly-sunday',
            'weekly-monday',
            'weekly-tuesday',
            'weekly-wednesday',
            'weekly-thursday',
            'weekly-friday',
            'weekly-saturday',
            'weekly-summary'
        ];
        $ezhp_target_index = array_search( $ezhp_target_section, $ezhp_section_order );
        $ezhp_next_section = ( isset( $ezhp_section_order[$ezhp_target_index + 1] ) ? $ezhp_section_order[$ezhp_target_index + 1] : null );
        if ( $ezhp_next_section ) {
            // Insert CTA BEFORE the next section's opening tag
            $ezhp_cta_pattern = '/(<div[^>]*\\bid=["\']' . preg_quote( $ezhp_next_section, '/' ) . '["\'])/is';
            $ezhp_data['horoscopeText'] = preg_replace(
                $ezhp_cta_pattern,
                $ezhp_cta_html . '$1',
                $ezhp_data['horoscopeText'],
                1
            );
        } else {
            // Target is the last section (summary), append CTA at the very end
            // Find the closing </div> of the flexbox container
            $ezhp_data['horoscopeText'] = preg_replace(
                '/(<\\/div>\\s*)$/is',
                $ezhp_cta_html . '$1',
                $ezhp_data['horoscopeText'],
                1
            );
        }
    }
}
if ( isset( $ezhp_data['horoscopeText'] ) && !empty( $ezhp_data['horoscopeText'] ) ) {
    // Skip wp_kses here — rgba() styles are safe and will be preserved.
    $ezhp_horoscope_text = $ezhp_data['horoscopeText'];
} else {
    $ezhp_horoscope_text = esc_html__( 'No horoscope data available for this week.', 'ez-horoscope' );
}
// Build block HTML with RTL support
$ezhp_dir_attr = ( $ezhp_is_rtl ? ' dir="rtl"' : '' );
$ezhp_rtl_class = ( $ezhp_is_rtl ? ' ez-horoscope-rtl' : '' );
$ezhp_column_wrapper_class = ' ez-weekly-layout-' . $ezhp_column_layout;
$ezhp_output = '<div class="ez-horoscope-block' . $ezhp_rtl_class . $ezhp_column_wrapper_class . '"' . $ezhp_dir_attr . ' data-language="' . esc_attr( $ezhp_language ) . '" data-columns="' . esc_attr( $ezhp_column_layout ) . '">';
$ezhp_output .= $ezhp_horoscope_text;
$ezhp_output .= '</div>';
// Output safely — PHPCS compliant.
echo wp_kses_post( $ezhp_output );