<?php
/**
 * Server-side rendering for Author Pro Header Block
 */

// --- ATTRIBUTE EXTRACTION ---
$menu_slug = isset($attributes['menuSlug']) ? $attributes['menuSlug'] : '';
$cta_text = isset($attributes['ctaText']) ? $attributes['ctaText'] : 'Latest Book!';
$cta_url = isset($attributes['ctaUrl']) ? $attributes['ctaUrl'] : '#featured-book';

// Colors
$header_bg_color = isset($attributes['headerBgColor']) && !empty($attributes['headerBgColor']) ? $attributes['headerBgColor'] : (isset($attributes['navBgColor']) ? $attributes['navBgColor'] : '');
$site_title_color = isset($attributes['siteTitleColor']) ? $attributes['siteTitleColor'] : '';
$link_color = isset($attributes['linkColor']) ? $attributes['linkColor'] : '';
$btn_bg_color = isset($attributes['btnBgColor']) ? $attributes['btnBgColor'] : '';
$btn_text_color = isset($attributes['btnTextColor']) ? $attributes['btnTextColor'] : '';
$btn_hover_bg_color = isset($attributes['btnHoverBgColor']) ? $attributes['btnHoverBgColor'] : '';
$btn_hover_text_color = isset($attributes['btnHoverTextColor']) ? $attributes['btnHoverTextColor'] : '';

$block_id = isset($attributes['blockId']) ? $attributes['blockId'] : 'header-' . uniqid();
$header_style = isset($attributes['headerStyle']) && !empty($attributes['headerStyle']) ? $attributes['headerStyle'] : 'author-pro';
$is_sticky = isset($attributes['isSticky']) ? $attributes['isSticky'] : false;

// Logo
$logo_type = isset($attributes['logoType']) ? $attributes['logoType'] : 'custom';
$logo_text = isset($attributes['logoText']) ? $attributes['logoText'] : 'Danielle Steel';
$logo_image_url = isset($attributes['logoImageUrl']) ? $attributes['logoImageUrl'] : '';

// Get menu tree
if (function_exists('rswpthemes_awt_get_menu_tree')) {
    $menu_tree = rswpthemes_awt_get_menu_tree($menu_slug);
} else {
    $menu_tree = [];
}

// --- LOGO LOGIC ---
$logo_content = '';
if ($logo_type === 'image' && !empty($logo_image_url)) {
    $logo_content = sprintf('<img src="%s" alt="%s" class="awt-logo-img w-32 md:w-40 h-auto" />', esc_url($logo_image_url), esc_attr(get_bloginfo('name')));
} elseif ($logo_type === 'site_title') {
    $logo_content = get_bloginfo('name');
} else {
    $logo_content = esc_html($logo_text);
}

// --- DEFINE CLASSES AND MENU ARGS BASED ON STYLE ---

if ($header_style === 'author-pro') {
    $nav_classes = 'w-full relative z-50 bg-white border-b border-slate-100';
    $container_classes = 'awt-container mx-auto py-5 flex justify-between items-center';
    $logo_classes = 'awt-site-title text-2xl md:text-3xl font-serif font-bold text-primary tracking-tight hover:text-accent transition-colors no-underline';
    $cta_classes = 'hidden md:inline-block px-6 py-2.5 bg-accent text-white text-sm font-bold rounded-full hover:bg-orange-700 transition shadow-lg shadow-orange-200 awt-cta-btn';
    $toggle_classes = 'lg:hidden text-primary hover:text-white focus:outline-none transition-colors mobile-toggle-btn';

    $desktop_menu_args = [
        'ul_class' => 'hidden lg:flex space-x-8 items-center list-none m-0 p-0',
        'item_class' => 'relative group',
        'link_class' => 'text-sm font-medium font-inter text-secondary hover:text-accent transition transition-colors no-underline',
        'submenu_ul_class' => 'absolute pl-0 top-full left-0 mt-4 w-56 bg-white border border-slate-100 shadow-xl rounded-none py-2 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50',
        'submenu_item_class' => '',
        'submenu_link_class' => 'block px-5 py-3 text-sm transition font-inter text-secondary hover:text-accent hover:bg-slate-50 transition-colors no-underline'
    ];

    $mobile_menu_args = [
        'link_class' => 'block py-3 text-sm font-medium font-inter text-secondary hover:text-accent transition-colors border-b border-slate-50',
        'submenu_border' => 'border-slate-100',
        'summary_class' => 'flex justify-between items-center py-3 hover:bg-gray-50 cursor-pointer marker:content-none text-sm font-medium font-inter text-secondary border-b border-slate-50',
        'container_class' => 'flex list-none flex-col px-4 space-y-0'
    ];

} elseif ($header_style === 'elegant') {
    $nav_classes = 'w-full relative z-50 bg-white/95 backdrop-blur-sm border-b border-gray-200';
    $container_classes = 'awt-container mx-auto px-6 py-4 flex justify-between items-center';
    $logo_classes = 'awt-site-title text-2xl font-serif font-bold text-slate-800 tracking-tight hover:text-slate-600 transition-colors no-underline';
    $cta_classes = 'hidden md:inline-block px-6 py-2 bg-slate-900 text-white font-medium rounded text-sm hover:bg-gray-800 transition-all no-underline awt-cta-btn';
    $toggle_classes = 'lg:hidden text-slate-800 hover:text-slate-600 focus:outline-none mobile-toggle-btn';

    $desktop_menu_args = [
        'ul_class' => 'hidden lg:flex space-x-8 items-center list-none m-0 p-0',
        'item_class' => 'relative group',
        'link_class' => 'text-sm font-medium text-slate-800/80 uppercase tracking-wide hover:text-slate-900 transition-colors no-underline',
        'submenu_ul_class' => 'absolute top-full left-0 mt-2 w-48 bg-white border border-gray-100 shadow-lg rounded py-2 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50',
        'submenu_item_class' => '',
        'submenu_link_class' => 'block px-4 py-2 text-sm hover:bg-gray-50 transition-colors no-underline'
    ];

    $mobile_menu_args = [
        'link_class' => 'block py-3 text-sm font-medium text-slate-800/80 uppercase tracking-wide hover:text-slate-900 transition-colors border-b border-gray-100',
        'submenu_border' => 'border-gray-200',
        'summary_class' => 'flex justify-between items-center py-3 hover:bg-gray-50 cursor-pointer marker:content-none text-sm font-medium text-slate-800/80 uppercase tracking-wide border-b border-gray-100',
        'container_class' => 'flex list-none flex-col px-4 space-y-0'
    ];

} else {
    $nav_classes = 'w-full relative z-50 bg-white/80 backdrop-blur-sm border-b border-yellow-sun/30';
    $container_classes = 'awt-container mx-auto px-4 py-3 flex justify-between items-center';
    $logo_classes = 'awt-site-title text-3xl font-black text-navy tracking-tighter hover:text-blue-sky transition-colors no-underline';
    $cta_classes = 'hidden md:inline-block btn-fun btn-yellow text-sm no-underline awt-cta-btn';
    $toggle_classes = 'lg:hidden text-navy hover:text-blue-sky focus:outline-none mobile-toggle-btn';

    $desktop_menu_args = [
        'ul_class' => 'hidden md:flex space-x-6 lg:space-x-8 items-center list-none m-0 p-0',
        'item_class' => 'relative group',
        'link_class' => 'font-bold text-navy/80 hover:text-blue-sky transition-colors no-underline',
        'submenu_ul_class' => 'absolute top-full left-0 mt-2 w-48 bg-white shadow-xl rounded-2xl py-3 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50 border-2 border-cream',
        'submenu_item_class' => '',
        'submenu_link_class' => 'block px-4 py-2 text-sm hover:bg-gray-50 transition-colors no-underline'
    ];

    $mobile_menu_args = [
        'link_class' => 'block py-3 font-bold text-navy/80 hover:text-blue-sky transition-colors border-b border-yellow-sun/20',
        'submenu_border' => 'border-yellow-sun/20',
        'summary_class' => 'flex justify-between items-center py-3 hover:bg-gray-50 cursor-pointer marker:content-none font-bold text-navy/80 border-b border-yellow-sun/20',
        'container_class' => 'flex list-none flex-col px-4 space-y-0 font-bold'
    ];

}

// Detect Editor Preview (ServerSideRender uses REST API)
$is_editor_request = defined('REST_REQUEST') && REST_REQUEST === true;

// Ensure CTA button is visible in Gutenberg Editor
if ( $is_editor_request ) {
    $cta_classes = str_replace( 'hidden md:inline-block', 'inline-block', $cta_classes );
}

// Apply Sticky ONLY on Frontend
if ( $is_sticky && ! $is_editor_request ) {
    // Remove 'relative' and add fixed positioning
    $nav_classes = str_replace('relative', 'fixed', $nav_classes);
    $nav_classes .= ' top-0 left-0 z-50 bg-white/95 backdrop-blur-md border-b border-gray-100 shadow-sm';
}

// --- DYNAMIC STYLES (SCOPED) ---
$styles = [];

if ($header_bg_color) {
    $styles[] = ".block-{$block_id} { background-color: {$header_bg_color} !important; }";
}
if ($site_title_color) {
    $styles[] = ".block-{$block_id} .awt-site-title { color: {$site_title_color} !important; }";
}
if ($link_color) {
    $styles[] = ".block-{$block_id} ul li a { color: {$link_color} !important; }";
    $styles[] = ".block-{$block_id} .mobile-menu a { color: {$link_color} !important; }";
}
if ($btn_bg_color || $btn_text_color) {
    $bg = $btn_bg_color ? "background-color: {$btn_bg_color} !important; border-color: {$btn_bg_color} !important;" : '';
    $color = $btn_text_color ? "color: {$btn_text_color} !important;" : '';
    $styles[] = ".block-{$block_id} .awt-cta-btn { {$bg} {$color} }";
}
if ($btn_hover_bg_color || $btn_hover_text_color) {
    $bg = $btn_hover_bg_color ? "background-color: {$btn_hover_bg_color} !important; border-color: {$btn_hover_bg_color} !important;" : '';
    $color = $btn_hover_text_color ? "color: {$btn_hover_text_color} !important;" : '';
    $styles[] = ".block-{$block_id} .awt-cta-btn:hover { {$bg} {$color} }";
}

$scoped_style_block = !empty($styles) ? "<style>" . implode(' ', $styles) . "</style>" : "";

// Force Visibility Logic (Safety for JS Toggling)
$scoped_style_block .= "
<style>
    .block-{$block_id} .mobile-menu.hidden { display: none !important; }
    .block-{$block_id} .mobile-menu { display: block; }
</style>
";

$show_cta = isset($attributes['showCta']) ? $attributes['showCta'] : true;
// Ensure we also check emptiness of text/url if show_cta is enabled, though attributes control visibility now.
$show_cta = $show_cta && !empty($cta_text) && !empty($cta_url);

$show_mini_cart = isset($attributes['showMiniCart']) ? $attributes['showMiniCart'] : false;

// --- WOOCOMMERCE MINI CART ---
$mini_cart_html = '';
if ( $show_mini_cart && class_exists( 'WooCommerce' ) ) {
    $cart_count = WC()->cart ? WC()->cart->get_cart_contents_count() : 0;
    
    // Choose icon color based on style


    
    $icon_color_class = 'text-gray-600 hover:text-accent'; 
    if ($header_style === 'elegant') {
        $icon_color_class = 'text-slate-800 hover:text-slate-600';
    } elseif ($header_style === 'fun') {
        $icon_color_class = 'text-navy hover:text-blue-sky';
    }
    
    // Using a simple cart icon SVG
    $mini_cart_html = sprintf(
        '<a href="%s" class="relative group %s transition-colors" title="%s">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-6 h-6">
                <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 00-16.536-1.84M7.5 14.25L5.106 5.272M6 20.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm12.75 0a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" />
            </svg>
            <span class="absolute -top-1 -right-1 bg-accent text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full shadow-sm">%d</span>
        </a>',
        esc_url( wc_get_cart_url() ),
        esc_attr( $icon_color_class ),
        esc_attr__( 'View Cart', 'author-website-templates' ),
        $cart_count
    );
}

// Logic to align menu to the right if there are no action buttons (CTA / Mini Cart)
$menu_alignment_class = '';
if ( ! $show_cta && empty( $mini_cart_html ) ) {
    $menu_alignment_class = 'ml-auto';
}
// Append alignment class to the desktop menu args
if ( isset( $desktop_menu_args['ul_class'] ) ) {
    $desktop_menu_args['ul_class'] .= ' ' . $menu_alignment_class;
}
?>

<?php echo $scoped_style_block; ?>

<nav class="awt-header-block <?php echo esc_attr($nav_classes); ?> block-<?php echo esc_attr($block_id); ?>">
    <div class="<?php echo esc_attr($container_classes); ?>">
        <a href="<?php echo esc_url(home_url('/')); ?>" class="<?php echo esc_attr($logo_classes); ?>">
            <?php echo $logo_content; ?>
        </a>

        <?php
        if (function_exists('rswpthemes_awt_render_desktop_menu')) {
            echo rswpthemes_awt_render_desktop_menu($menu_tree, $desktop_menu_args);
        }
        ?>

        <div class="flex items-center gap-4">
            <?php if ( ! empty( $mini_cart_html ) ): ?>
                <div class="hidden md:block">
                    <?php echo $mini_cart_html; ?>
                </div>
            <?php endif; ?>

            <?php if ($show_cta): ?>
                <a href="<?php echo esc_url($cta_url); ?>" class="<?php echo esc_attr($cta_classes); ?>">
                    <?php echo esc_html($cta_text); ?>
                </a>
            <?php endif; ?>

            <button id="mobile-menu-btn-<?php echo esc_attr( $block_id ); ?>" type="button" aria-expanded="false" aria-controls="mobile-menu-<?php echo esc_attr( $block_id ); ?>" class="<?php echo esc_attr( $toggle_classes ); ?>">
                <svg class="w-8 h-8" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16m-7 6h7"></path>
                </svg>
            </button>
        </div>
    </div>

    <div id="mobile-menu-<?php echo esc_attr( $block_id ); ?>"
        class="mobile-menu hidden lg:hidden bg-white border-t border-gray-100 absolute left-0 top-full w-full shadow-lg z-40">
        <?php
        if (function_exists('rswpthemes_awt_render_mobile_menu')) {
            echo rswpthemes_awt_render_mobile_menu($menu_tree, $mobile_menu_args);
        }
        ?>
        
        <?php if ( ! empty( $mini_cart_html ) || $show_cta ): ?>
        <div class="p-4 border-t border-gray-100 flex flex-col gap-4 items-center">
            <?php if ( ! empty( $mini_cart_html ) ): ?>
                <div class="flex items-center gap-2">
                    <span class="text-sm font-bold text-gray-700"><?php esc_html_e( 'Cart:', 'author-website-templates' ); ?></span>
                    <?php echo $mini_cart_html; ?>
                </div>
            <?php endif; ?>

            <?php if ($show_cta): ?>
                <a href="<?php echo esc_url($cta_url); ?>"
                    class="block text-center px-6 py-2.5 bg-yellow-sun text-navy font-black rounded-full shadow-md hover:bg-yellow-400 transition-all text-sm awt-cta-btn w-full">
                    <?php echo esc_html($cta_text); ?>
                </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</nav>
<div class="scroll-smooth d-none"></div>