<?php
/**
 * Admin Settings Page for Author Website Templates
 * 
 * Creates a global settings page for configuring header and footer elements
 * used in the Single Book Template and other canvas templates.
 * 
 * @package Author_Website_Templates
 * @since 1.0.9
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Get all Reusable Blocks (Synced Patterns)
 * 
 * @return array Associative array of [Slug => Title]
 */
function rswpthemes_awt_get_reusable_blocks()
{
    $blocks = get_posts([
        'post_type' => 'wp_block',
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC',
        'post_status' => 'publish',
    ]);

    $reusable_blocks = [];
    foreach ($blocks as $block) {
        // Return Slug as key: [slug => Title]
        $reusable_blocks[$block->post_name] = $block->post_title;
    }

    return $reusable_blocks;
}

/**
 * Get Google Fonts List
 * 
 * @return array [Font Name => Font Family String]
 */
function rswpthemes_awt_get_google_fonts()
{
    return [
        'System Default' => 'sans-serif',
        'Nunito' => 'Nunito',
        'Inter' => 'Inter',
        'Libre Baskerville' => 'Libre Baskerville',
        'Roboto' => 'Roboto',
        'Open Sans' => 'Open Sans',
        'Lato' => 'Lato',
        'Montserrat' => 'Montserrat',
        'Poppins' => 'Poppins',
        'Merriweather' => 'Merriweather',
        'Playfair Display' => 'Playfair Display',
    ];
}

/**
 * Register the settings page under Settings menu
 */
function rswpthemes_awt_register_settings_page()
{
    add_options_page(
        __('Author Templates Settings', 'author-website-templates'),  // Page title
        __('Author Templates', 'author-website-templates'),           // Menu title
        'manage_options',                                                // Capability
        'awt-global-settings',                                           // Menu slug
        'rswpthemes_awt_render_settings_page'                           // Callback function
    );
}
add_action('admin_menu', 'rswpthemes_awt_register_settings_page');

/**
 * Register all settings fields and sections
 */
function rswpthemes_awt_register_settings()
{
    // Register the option group (Common for both tabs)
    register_setting('awt_global_settings', 'awt_global_settings', 'rswpthemes_awt_sanitize_settings');

    // --- Tab 3: Design Settings (Slug: awt-global-settings-design) ---
    add_settings_section(
        'awt_design_colors_section',
        __('Colors', 'author-website-templates'),
        'rswpthemes_awt_design_colors_section_callback',
        'awt-global-settings-design'
    );

    $colors = [
        'cream' => ['label' => 'Cream', 'default' => '#FFFDF5'],
        'navy' => ['label' => 'Navy', 'default' => '#264653'],
        'yellow-sun' => ['label' => 'Yellow Sun', 'default' => '#FFD166'],
        'blue-sky' => ['label' => 'Blue Sky', 'default' => '#00C6FF'],
        'coral-pop' => ['label' => 'Coral Pop', 'default' => '#EF476F'],
        'primary' => ['label' => 'Primary', 'default' => '#0f172a'],
        'secondary' => ['label' => 'Secondary', 'default' => '#475569'],
        'accent' => ['label' => 'Accent', 'default' => '#ea580c'],
        'paper' => ['label' => 'Paper', 'default' => '#F8FAFC'],
    ];

    foreach ($colors as $slug => $data) {
        add_settings_field(
            'color_' . $slug,
            $data['label'],
            'rswpthemes_awt_color_picker_callback',
            'awt-global-settings-design',
            'awt_design_colors_section',
            [
                'label_for' => 'color_' . $slug,
                'default' => $data['default']
            ]
        );
    }

    add_settings_section(
        'awt_design_typography_section',
        __('Typography', 'author-website-templates'),
        'rswpthemes_awt_design_typography_section_callback',
        'awt-global-settings-design'
    );

    $fonts = [
        'sans' => ['label' => 'Sans Font', 'default' => 'Nunito, sans-serif'],
        'inter' => ['label' => 'Inter Font', 'default' => 'Inter, sans-serif'],
        'serif' => ['label' => 'Serif Font', 'default' => 'Libre Baskerville, serif'],
    ];

    foreach ($fonts as $slug => $data) {
        add_settings_field(
            'font_' . $slug,
            $data['label'],
            'rswpthemes_awt_font_select_callback',
            'awt-global-settings-design',
            'awt_design_typography_section',
            [
                'label_for' => 'font_' . $slug,
                'default' => $data['default'],
                'description' => sprintf(__('Default: %s', 'author-website-templates'), $data['default'])
            ]
        );
    }

    // --- Tab 1: Templates Settings (Slug: awt-global-settings-templates) ---
    
    // General Settings Section
    add_settings_section(
        'awt_general_section',
        __('General Settings', 'author-website-templates'),
        'rswpthemes_awt_general_section_callback',
        'awt-global-settings-templates'
    );

    // Book Archive Template Selection
    add_settings_field(
        'awt_book_archive_template_id',
        __('Book Archive Template', 'author-website-templates'),
        'rswpthemes_awt_reusable_block_select_callback',
        'awt-global-settings-templates',
        'awt_general_section',
        [
            'label_for' => 'awt_book_archive_template_id',
            'description' => __('Select a Reusable Block to override the default Book Archive design. Leave empty to use the default layout.', 'author-website-templates'),
        ]
    );

    // Single Book Template Selection
    add_settings_field(
        'awt_book_single_template_id',
        __('Single Book Template', 'author-website-templates'),
        'rswpthemes_awt_reusable_block_select_callback',
        'awt-global-settings-templates',
        'awt_general_section',
        [
            'label_for' => 'awt_book_single_template_id',
            'description' => __('Select a Reusable Block to override the default Single Book design. Leave empty to use the default layout.', 'author-website-templates'),
        ]
    );

    // Blog & Archive Template Selection
    add_settings_field(
        'awt_blog_template_id',
        __('Blog & Archive Template', 'author-website-templates'),
        'rswpthemes_awt_reusable_block_select_callback',
        'awt-global-settings-templates',
        'awt_general_section',
        [
            'label_for' => 'awt_blog_template_id',
            'description' => __('Select a Reusable Block to use for blog and post archives. (Requires a compatible theme like <strong>Author Portfolio</strong>).', 'author-website-templates'),
        ]
    );

    // Global Page Title Template Selection
    add_settings_field(
        'awt_page_title_template_id',
        __('Global Page Title Template', 'author-website-templates'),
        'rswpthemes_awt_reusable_block_select_callback',
        'awt-global-settings-templates',
        'awt_general_section',
        [
            'label_for' => 'awt_page_title_template_id',
            'description' => __('Select a pattern to use on Archive, Search, and 404 pages. The title will update dynamically.', 'author-website-templates'),
        ]
    );

    // 404 Page Template Selection
    add_settings_field(
        'awt_404_template_id',
        __('404 Page Template', 'author-website-templates'),
        'rswpthemes_awt_reusable_block_select_callback',
        'awt-global-settings-templates',
        'awt_general_section',
        [
            'label_for' => 'awt_404_template_id',
            'description' => __('Select a Reusable Block to use as the Custom 404 Page.', 'author-website-templates'),
        ]
    );

    // Blog Single Template Selection
    add_settings_field(
        'awt_blog_single_template_id',
        __('Blog Single Template', 'author-website-templates'),
        'rswpthemes_awt_reusable_block_select_callback',
        'awt-global-settings-templates',
        'awt_general_section',
        [
            'label_for' => 'awt_blog_single_template_id',
            'description' => __('Select a Reusable Block to override the default Single Post design. (Requires compatible theme).', 'author-website-templates'),
        ]
    );

    // Header Settings Section
    add_settings_section(
        'awt_header_section',
        __('Header Settings', 'author-website-templates'),
        'rswpthemes_awt_header_section_callback',
        'awt-global-settings-templates'
    );

    // Global Header Block Selection
    add_settings_field(
        'awt_global_header_block',
        __('Header Block', 'author-website-templates'),
        'rswpthemes_awt_reusable_block_select_callback',
        'awt-global-settings-templates',
        'awt_header_section',
        [
            'label_for' => 'awt_global_header_block',
            'description' => __('Select a Reusable Block to use as the global header. Design your header in the block editor and save it as a Reusable Block first.', 'author-website-templates'),
        ]
    );

    // Force Header Display Globally
    add_settings_field(
        'awt_header_force_global',
        __('Force Display Globally', 'author-website-templates'),
        'rswpthemes_awt_checkbox_callback',
        'awt-global-settings-templates',
        'awt_header_section',
        [
            'label_for' => 'awt_header_force_global',
            'label' => __('Enable', 'author-website-templates'),
            'description' => __('Enable this to replace the default theme header with this block. (Works only with compatible themes like <strong>Author Portfolio</strong>).', 'author-website-templates'),
        ]
    );

    // Footer Settings Section
    add_settings_section(
        'awt_footer_section',
        __('Footer Settings', 'author-website-templates'),
        'rswpthemes_awt_footer_section_callback',
        'awt-global-settings-templates'
    );

    // Global Footer Block Selection
    add_settings_field(
        'awt_global_footer_block',
        __('Footer Block', 'author-website-templates'),
        'rswpthemes_awt_reusable_block_select_callback',
        'awt-global-settings-templates',
        'awt_footer_section',
        [
            'label_for' => 'awt_global_footer_block',
            'description' => __('Select a Reusable Block to use as the global footer. Design your footer in the block editor and save it as a Reusable Block first.', 'author-website-templates'),
        ]
    );

    // Force Footer Display Globally
    add_settings_field(
        'awt_footer_force_global',
        __('Force Display Globally', 'author-website-templates'),
        'rswpthemes_awt_checkbox_callback',
        'awt-global-settings-templates',
        'awt_footer_section',
        [
            'label_for' => 'awt_footer_force_global',
            'label' => __('Enable', 'author-website-templates'),
            'description' => __('Enable this to replace the default theme footer with this block. (Works only with compatible themes like <strong>Author Portfolio</strong>).', 'author-website-templates'),
        ]
    );

    // --- Tab 2: Social Media Settings (Slug: awt-global-settings-social) ---

    add_settings_section(
        'awt_social_section',
        __('Social Media URLs', 'author-website-templates'),
        'rswpthemes_awt_social_section_callback',
        'awt-global-settings-social'
    );

    $social_networks = [
        'instagram' => 'Instagram',
        'facebook' => 'Facebook',
        'twitter' => 'Twitter / X',
        'pinterest' => 'Pinterest',
        'youtube' => 'YouTube',
        'tiktok' => 'TikTok',
        'linkedin' => 'LinkedIn',
        'goodreads' => 'Goodreads',
        'amazon' => 'Amazon Author Page',
        'website' => 'Website',
        'email' => 'Email Address (mailto:)',
    ];

    foreach ($social_networks as $key => $label) {
        add_settings_field(
            'social_' . $key,
            $label,
            'rswpthemes_awt_text_field_callback',
            'awt-global-settings-social',
            'awt_social_section',
            [
                'label_for' => 'social_' . $key,
                'placeholder' => ($key === 'email') ? 'mailto:you@example.com' : 'https://' . $key . '.com/yourprofile'
            ]
        );
    }
}
add_action('admin_init', 'rswpthemes_awt_register_settings');

/**
 * Section callback for Design Colors
 */
function rswpthemes_awt_design_colors_section_callback() {
    echo '<p>' . esc_html__('Customize the collaborative color palette used throughout the site.', 'author-website-templates') . '</p>';
}

/**
 * Section callback for Design Typography
 */
function rswpthemes_awt_design_typography_section_callback() {
    echo '<p>' . esc_html__('Define the font stacks for your site. Select from the available Google Fonts.', 'author-website-templates') . '</p>';
}

/**
 * Callback for Font Selection Dropdown
 */
function rswpthemes_awt_font_select_callback($args) {
    $options = get_option('awt_global_settings', []);
    // Ensure we handle defaults correctly if they are complex strings in old versions, 
    // but here we expect just the Font Name keys or simple family strings.
    // Actually, we want to store the "Font Name" (key in our list) or the "Font Family" (value).
    // Let's store the "Font Name" for easy lookup and enqueueing, OR store the family string.
    // The requirement says: Users select "Poppins". 
    // Let's store the Font Name (e.g., 'Poppins') in the DB.
    
    // Check if the current value is a full stack (legacy) and convert if possible, or just default.
    // For simplicity, if it's not in our list, we might defaulting.
    
    $current_value = isset($options[$args['label_for']]) ? $options[$args['label_for']] : '';
    $fonts = rswpthemes_awt_get_google_fonts();
    
    // Attempt to match legacy defaults (e.g. 'Nunito, sans-serif') to Keys ('Nunito')
    // If exact match not found, we rely on the user to re-save. 
    // But for the specific defaults passed in register_settings, let's look at those.
    // The default passed in args is 'Nunito, sans-serif'.
    // If $current_value is empty, we use $args['default'].
    // We need to map 'Nunito, sans-serif' -> 'Nunito' for the select to show correctly.
    
    $selected = $current_value;
    if (empty($selected)) {
         // rough parsing for default
         $default_parts = explode(',', $args['default']);
         $selected = trim($default_parts[0], " '\"");
    } else {
         // If stored value is comma separated, take first part
         $parts = explode(',', $selected);
         $selected = trim($parts[0], " '\"");
    }

    echo '<select id="' . esc_attr($args['label_for']) . '" name="awt_global_settings[' . esc_attr($args['label_for']) . ']">';
    foreach ($fonts as $font_name => $font_family) {
        printf(
             '<option value="%s" %s>%s</option>',
             esc_attr($font_name), // Store 'Nunito'
             selected($selected, $font_name, false),
             esc_html($font_name)
        );
    }
    echo '</select>';

    if (!empty($args['description'])) {
        printf('<p class="description">%s</p>', esc_html($args['description']));
    }
}

/**
 * Callback for Color Picker
 */
function rswpthemes_awt_color_picker_callback($args) {
    $options = get_option('awt_global_settings', []);
    $value = isset($options[$args['label_for']]) ? $options[$args['label_for']] : $args['default'];
    
    printf(
        '<input type="color" id="%s" name="awt_global_settings[%s]" value="%s" style="height: 40px; width: 60px; padding: 2px;" />',
        esc_attr($args['label_for']),
        esc_attr($args['label_for']),
        esc_attr($value)
    );
}

/**
 * Section callback for general settings
 */
function rswpthemes_awt_general_section_callback()
{
    echo '<p>' . esc_html__('Choose your active author template design.', 'author-website-templates') . '</p>';
}

/**
 * Section callback for header settings
 */
function rswpthemes_awt_header_section_callback()
{
    echo '<p>' . esc_html__('Select a Reusable Block to use as the global header. Create your header design in the block editor first, then save it as a Reusable Block.', 'author-website-templates') . '</p>';
}

/**
 * Section callback for footer settings
 */
function rswpthemes_awt_footer_section_callback()
{
    echo '<p>' . esc_html__('Select a Reusable Block to use as the global footer. Create your footer design in the block editor first, then save it as a Reusable Block.', 'author-website-templates') . '</p>';
}

/**
 * Section callback for social settings
 */
function rswpthemes_awt_social_section_callback()
{
    echo '<p>' . esc_html__('Enter the full URLs for your social media profiles. These will be automatically displayed in the Footer and Socials blocks.', 'author-website-templates') . '</p>';
}

/**
 * Callback for text input fields
 */
function rswpthemes_awt_text_field_callback($args)
{
    $options = get_option('awt_global_settings', []);
    $value = isset($options[$args['label_for']]) ? $options[$args['label_for']] : '';
    $placeholder = isset($args['placeholder']) ? $args['placeholder'] : '';

    printf(
        '<input type="text" id="%s" name="awt_global_settings[%s]" value="%s" placeholder="%s" class="regular-text" />',
        esc_attr($args['label_for']),
        esc_attr($args['label_for']),
        esc_attr($value),
        esc_attr($placeholder)
    );

    if (!empty($args['description'])) {
        printf('<p class="description">%s</p>', esc_html($args['description']));
    }
}

/**
 * Callback for menu selection dropdown
 */
function rswpthemes_awt_menu_select_callback($args)
{
    $options = get_option('awt_global_settings', []);
    $value = isset($options[$args['label_for']]) ? $options[$args['label_for']] : '';
    $menus = wp_get_nav_menus();

    echo '<select id="' . esc_attr($args['label_for']) . '" name="awt_global_settings[' . esc_attr($args['label_for']) . ']">';
    echo '<option value="">' . esc_html__('— Select a Menu —', 'author-website-templates') . '</option>';

    foreach ($menus as $menu) {
        printf(
            '<option value="%s" %s>%s</option>',
            esc_attr($menu->term_id),
            selected($value, $menu->term_id, false),
            esc_html($menu->name)
        );
    }

    echo '</select>';

    if (!empty($args['description'])) {
        printf('<p class="description">%s</p>', esc_html($args['description']));
    }
}

/**
 * Callback for reusable block selection dropdown
 */
function rswpthemes_awt_reusable_block_select_callback($args)
{
    $options = get_option('awt_global_settings', []);
    $value = isset($options[$args['label_for']]) ? $options[$args['label_for']] : '';
    $blocks = rswpthemes_awt_get_reusable_blocks();

    echo '<select id="' . esc_attr($args['label_for']) . '" name="awt_global_settings[' . esc_attr($args['label_for']) . ']">';
    echo '<option value="">' . esc_html__('— Select a Reusable Block —', 'author-website-templates') . '</option>';

    if (!empty($blocks)) {
        foreach ($blocks as $block_id => $block_title) {
            printf(
                '<option value="%s" %s>%s</option>',
                esc_attr($block_id),
                selected($value, $block_id, false),
                esc_html($block_title)
            );
        }
    }

    echo '</select>';

    if (!empty($args['description'])) {
        printf('<p class="description">%s</p>', esc_html($args['description']));
    }

    // Show helpful message if no blocks available
    if (empty($blocks)) {
        echo '<p class="description" style="color: #d63638;">';
        echo esc_html__('No Reusable Blocks found. Create a Reusable Block in the block editor first.', 'author-website-templates');
        echo '</p>';
    }
}


/**
 * Callback for checkbox fields
 */
function rswpthemes_awt_checkbox_callback($args)
{
    $options = get_option('awt_global_settings', []);
    $value = isset($options[$args['label_for']]) ? $options[$args['label_for']] : '';

    printf(
        '<label><input type="checkbox" id="%s" name="awt_global_settings[%s]" value="1" %s /> %s</label>',
        esc_attr($args['label_for']),
        esc_attr($args['label_for']),
        checked($value, '1', false),
        isset($args['label']) ? esc_html($args['label']) : ''
    );

    if (!empty($args['description'])) {
        printf('<p class="description">%s</p>', esc_html($args['description']));
    }
}

/**
 * Sanitize settings before saving
 */
function rswpthemes_awt_sanitize_settings($input)
{
    // Start with existing settings to prevent data loss for hidden tabs
    $current_settings = get_option('awt_global_settings', []);
    $sanitized = is_array($current_settings) ? $current_settings : [];

    // Identify which tab submitted the form
    $tab_context = isset($_POST['awt_tab_context']) ? $_POST['awt_tab_context'] : 'templates';

    // --- Tab 1: Templates Logic --
    if ($tab_context === 'templates') {
        // Sanitize block selections
        $block_fields = [
            'awt_global_header_block',
            'awt_global_footer_block',
            'awt_book_archive_template_id',
            'awt_book_single_template_id',
            'awt_blog_template_id',
            'awt_blog_single_template_id',
            'awt_page_title_template_id',
            'awt_404_template_id',
        ];

        foreach ($block_fields as $field) {
            if (isset($input[$field])) {
                $sanitized[$field] = sanitize_text_field($input[$field]); // Save as Slug
            } else {
                $sanitized[$field] = '';
            }
        }

        // Sanitize Checkboxes (Important: If unchecked, they are missing from $input, so we manually check)
        $checkbox_fields = [
            'awt_header_force_global',
            'awt_footer_force_global',
        ];

        foreach ($checkbox_fields as $field) {
            $sanitized[$field] = isset($input[$field]) && $input[$field] === '1' ? '1' : '0';
        }
    }

    // --- Tab 2: Social Media Logic ---
    if ($tab_context === 'social') {
        $social_networks = ['instagram', 'facebook', 'twitter', 'pinterest', 'youtube', 'tiktok', 'linkedin', 'goodreads', 'amazon', 'website', 'email'];
        foreach ($social_networks as $network) {
            $key = 'social_' . $network;
            // Only update if the field was potentially on screen (though inputs are technically present in DOM if just hidden, 
            // settings API usually doesn't submit hidden tab fields if effectively managed. 
            // BUT simpler logic: If we are in 'social' tab, we expect these keys.
            if (isset($input[$key])) {
                $sanitized[$key] = sanitize_text_field($input[$key]);
            } else {
                // If input is missing but we are in social tab, it means user cleared it.
                $sanitized[$key] = '';
            }
        }
    }

    // --- Tab 3: Design Logic ---
    if ($tab_context === 'design') {
        $colors = ['cream', 'navy', 'yellow-sun', 'blue-sky', 'coral-pop', 'primary', 'secondary', 'accent', 'paper'];
        foreach ($colors as $slug) {
            $key = 'color_' . $slug;
            if (isset($input[$key])) {
                $sanitized[$key] = sanitize_hex_color($input[$key]);
            }
        }

        $fonts = ['sans', 'inter', 'serif'];
        foreach ($fonts as $slug) {
            $key = 'font_' . $slug;
            if (isset($input[$key])) {
                $sanitized[$key] = sanitize_text_field($input[$key]);
            }
        }
    }

    return $sanitized;
}

/**
 * Render the settings page
 */
function rswpthemes_awt_render_settings_page()
{
    // Check user capabilities
    if (!current_user_can('manage_options')) {
        return;
    }

    $active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'templates';
    ?>
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>

        <nav class="nav-tab-wrapper">
            <a href="?page=awt-global-settings&tab=templates" class="nav-tab <?php echo $active_tab == 'templates' ? 'nav-tab-active' : ''; ?>"><?php _e('Templates', 'author-website-templates'); ?></a>
            <a href="?page=awt-global-settings&tab=social" class="nav-tab <?php echo $active_tab == 'social' ? 'nav-tab-active' : ''; ?>"><?php _e('Social Media', 'author-website-templates'); ?></a>
            <a href="?page=awt-global-settings&tab=design" class="nav-tab <?php echo $active_tab == 'design' ? 'nav-tab-active' : ''; ?>"><?php _e('Design', 'author-website-templates'); ?></a>
        </nav>

        <form action="options.php" method="post">
            
            <!-- Hidden Input to Track Context -->
            <input type="hidden" name="awt_tab_context" value="<?php echo esc_attr($active_tab); ?>">

            <?php
            // Output security fields for the registered setting
            settings_fields('awt_global_settings');

            if ($active_tab == 'social') {
                do_settings_sections('awt-global-settings-social');
            } elseif ($active_tab == 'design') {
                do_settings_sections('awt-global-settings-design');
            } else {
                do_settings_sections('awt-global-settings-templates');
            }

            // Output save settings button
            submit_button(__('Save Settings', 'author-website-templates'));
            ?>
        </form>
    </div>
    <?php
}

/**
 * Get Social Icons Helper Function
 * 
 * Generates HTML for social icons based on global settings.
 * 
 * @param string $style 'fun' or 'elegant'
 * @param array $custom_colors ['color' => '#...', 'hover' => '#...']
 * @return string HTML output
 */
function rswpthemes_awt_get_social_icons($style = 'fun', $custom_colors = [])
{
    $options = get_option('awt_global_settings', []);
    $output = '';

    $networks = [
        'instagram' => '<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.07 1.646.07 4.85s-.012 3.584-.07 4.85c-.148 3.227-1.667 4.77-4.919 4.919-1.266.058-1.646.07-4.85.07s-3.584-.012-4.85-.07c-3.252-.148-4.771-1.691-4.919-4.919-.058-1.265-.07-1.646-.07-4.85s.012-3.584.07-4.85c.148-3.227 1.667 4.77 4.919 4.919 1.266.058 1.646.07 4.85.07zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948s.014 3.667.072 4.947c.2 4.358 2.618 6.78 6.98 6.98 1.281.059 1.689.073 4.948.073s3.667-.014 4.947-.072c4.358-.2 6.78-2.618 6.98-6.98.059-1.281.073-1.689.073-4.948s-.014-3.667-.072-4.947c-.2-4.358-2.618-6.78-6.98-6.98-1.281-.059-1.689-.073-4.948-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.162 6.162 6.162 6.162-2.759 6.162-6.162-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.791-4-4s1.791-4 4-4 4 1.791 4 4-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.44-.645 1.44-1.44s-.645-1.44-1.44-1.44z"/>',
        'facebook' => '<path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.791-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>',
        'twitter' => '<path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>',
        'pinterest' => '<path d="M12 0c-6.627 0-12 5.373-12 12 0 5.084 3.163 9.426 7.627 11.174-.105-.949-.2-2.405.042-3.441.218-.937 1.407-5.965 1.407-5.965s-.359-.719-.359-1.782c0-1.668.967-2.914 2.171-2.914 1.023 0 1.518.769 1.518 1.69 0 1.029-.655 2.568-.992 3.995-.283 1.195.599 2.169 1.777 2.169 2.133 0 3.772-2.249 3.772-5.495 0-2.873-2.064-4.882-5.012-4.882-3.65 0-5.789 2.738-5.789 5.57 0 1.103.425 2.286.956 2.922.105.124.12.235.089.425-.098.411-.318 1.292-.361 1.472-.056.238-.255.289-.59.174-2.199-.75-3.568-3.097-3.568-5.003 0-4.072 2.957-7.818 8.527-7.818 4.478 0 7.957 3.19 7.957 7.452 0 4.448-2.805 8.03-6.697 8.03-1.308 0-2.536-.68-2.958-1.482 0 0-.648 2.466-.805 3.07-.291 1.115-1.077 2.496-1.602 3.328 1.206.357 2.483.55 3.805.55 6.627 0 12-5.373 12-12 0-6.627-5.373-12-12-12z"/>',
        'youtube' => '<path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/>',
        'tiktok' => '<path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93v6.14c0 1.39-.23 2.73-1.09 3.91-1.21 1.74-3.5 2.5-5.51 1.79-1.6-.48-2.73-1.85-2.95-3.5-.23-1.95 1.05-3.9 2.96-4.32.75-.24 1.54-.25 2.32-.05h.02v4.07c-1.2-.55-2.45.19-2.58 1.4-.04.66.38 1.25.99 1.48.51.27 1.14.28 1.67-.01.52-.25.86-.77.87-1.34v-11.8c-1.3-.01-2.61 0-3.91-.01v-4.01z"/>',
        'linkedin' => '<path d="M4.98 3.5c0 1.381-1.11 2.5-2.48 2.5s-2.48-1.119-2.48-2.5c0-1.38 1.11-2.5 2.48-2.5s2.48 1.12 2.48 2.5zm.02 4.5h-5v16h5v-16zm7.982 0h-4.968v16h4.969v-8.399c0-4.67 6.029-5.052 6.029 0v8.399h4.988v-10.131c0-7.88-8.922-7.593-11.018-3.714v-2.155z"/>',
        'goodreads' => '<path d="M2.5 7.5v-2.5h-2.5v2.5h2.5zm0-5v-2.5h-2.5v2.5h2.5zm5 0v-2.5h-2.5v2.5h2.5zm0 5v-2.5h-2.5v2.5h2.5zm5 0v-2.5h-2.5v2.5h2.5zm0-5v-2.5h-2.5v2.5h2.5zm5 0v-2.5h2.5v2.5h-2.5zm0 5v-2.5h-2.5v2.5h2.5zm2.5 12.5h-2.5v-2.5h-2.5v2.5h-10v-2.5h-2.5v7.5h17.5v-5zm-15 2.5v-2.5h2.5v2.5h-2.5zm5 0v-2.5h2.5v2.5h-2.5zm5 0v-2.5h2.5v2.5h-2.5z"/>', // Approximate placeholder fallback, Goodreads SVG is complex
        'amazon' => '<path d="M13.882 11.232c-2.348 0-4.205 1.547-4.205 3.93 0 2.215 1.71 3.593 4.254 3.593 1.884 0 3.023-.74 3.73-1.638v-5.26c-.722-.52-2.028-.625-3.78-.625zm4.846-1.55c0-.663-.04-1.258-.1-1.748-.372-2.074-2.128-2.87-4.9-2.87-3.047 0-4.974.925-5.467 2.478l1.45.39c.265-.89 1.482-1.493 3.655-1.493 1.536 0 2.87.352 2.87 1.45 0 .42-.258.625-.97.747-3.804.608-6.176 1.637-6.176 4.71 0 2.563 1.956 4.086 4.887 4.086 2.373 0 3.903-1.077 4.542-2.14.07.608.136 1.42.136 1.95h1.66v-7.56z"/>',
        'website' => '<path d="M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm-2.033 11.35C8.952 6.954 10.38 3.479 12 3.479s3.048 3.475 2.033 7.871l-4.066 0zm-4.07 10.597c.48-2.585 1.928-4.945 3.869-6.95H4.21c-.72 2.052-1.39 4.39-1.39 6.83 0 .04 0 .08.01.12h3.07zM3.666 12.35h3.83c-1.05 4.302-2.316 7.603-2.316 7.603-1.715-2.037-3.219-4.38-3.414-7.603zm.29-2.35h5.45C9.462 6.643 9.4 3.67 9.4 3.67c-1.884.288-3.6 1-5.11 2C3.542 6.61 3.593 9.61 3.956 10zm6.01-6.521c-1.014-4.39-2.45-7.872-2.45-7.872C9.426.697 11.206 0 12 0s2.574.697 4.484 1.607c0 0-1.436 3.482-2.45 7.872l-4.068 0zM12 20.521c-1.62 0-3.048-3.475-2.033-7.871l4.066 0c1.015 4.396-.413 7.871-2.033 7.871zm3.87-5.65c.48 2.585 1.928 4.945 3.869 6.95h-5.509c.72-2.052 1.39-4.39 1.39-6.83 0-.04 0-.08-.01-.12h-3.07zM16.51 3.67c0 0-.062 2.973.006 6.33h5.45c.363-.39.414-3.39-.334-7.33-1.51-1-3.226-1.712-5.11-2H16.51z"/>',
        'email' => '<path d="M2.25 5.5v13h19.5v-13H2.25zm.966 1.5H20.78l-8.784 7.5L3.216 7zm-.966 11.236V7.697l9.75 8.324 9.75-8.324v10.54H2.25z"/>',
    ];

    $styles = [];
    if (!empty($custom_colors['color'])) {
        $styles[] = "color: {$custom_colors['color']} !important;";
    }
    
    // Using a class for hover since we can't easily inline hover states. 
    // The render.php should handle the style block for hover based on CSS vars, 
    // or we just rely on the element classes if possible.
    // However, if we need inline control, we can only do static props.
    // We'll rely on the 'awt-social-icon' class and the variables set in render.php.
    
    $inline_style = !empty($styles) ? 'style="' . implode(' ', $styles) . '"' : '';

    foreach ($networks as $key => $svg_path) {
        $url_key = 'social_' . $key;
        if (!empty($options[$url_key])) {
            $url = esc_url($options[$url_key]);
            if ($key === 'email' && strpos($url, 'mailto:') !== 0) {
                $url = 'mailto:' . $url;
            }

            $icon_class = "awt-social-icon transition-colors duration-300";
            if ($style === 'fun') {
                $icon_class .= " transform hover:scale-110";
                $svg_size = "w-8 h-8";
            } else {
                 $svg_size = "w-6 h-6";
            }

            // If we are in Elegant style, we might want different base classes or specific layout
            // But usually the footer controls the container.
            
            // Build the HTML
            $output .= sprintf(
                '<a href="%s" class="%s" %s target="_blank" rel="noopener noreferrer" title="%s">',
                $url,
                $icon_class,
                $inline_style,
                ucfirst($key)
            );
            $output .= sprintf(
                '<svg class="%s" fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">%s</svg>',
                $svg_size,
                $svg_path
            );
            $output .= '</a>';
        }
    }

    return $output;
}

/**
 * Inject Custom CSS Variables into Head
 */
function rswpthemes_awt_custom_styles()
{
    $options = get_option('awt_global_settings', []);

    // Defaults matching original tailwind config
    $defaults = [
        'color_cream' => '#FFFDF5',
        'color_navy' => '#264653',
        'color_yellow-sun' => '#FFD166',
        'color_blue-sky' => '#00C6FF',
        'color_coral-pop' => '#EF476F',
        'color_primary' => '#0f172a',
        'color_secondary' => '#475569',
        'color_accent' => '#ea580c',
        'color_paper' => '#F8FAFC',
        'font_sans' => 'Nunito, sans-serif',
        'font_inter' => 'Inter, sans-serif',
        'font_serif' => 'Libre Baskerville, serif',
    ];

    $css_vars = [];

    // Colors
    $colors = ['cream', 'navy', 'yellow-sun', 'blue-sky', 'coral-pop', 'primary', 'secondary', 'accent', 'paper'];
    foreach ($colors as $slug) {
        $key = 'color_' . $slug;
        $value = !empty($options[$key]) ? $options[$key] : $defaults[$key];
        $css_vars[] = "--awt-color-{$slug}: {$value};";
    }

    // Fonts
    $fonts_map = rswpthemes_awt_get_google_fonts();
    $fonts = ['sans', 'inter', 'serif'];
    
    foreach ($fonts as $slug) {
        $key = 'font_' . $slug;
        $stored_val = !empty($options[$key]) ? $options[$key] : '';
        
        // If stored value is empty, use default from $defaults array
        if (empty($stored_val)) {
             // Parse the default string to get the key again? Or just use the default full string.
             // The defaults array has full strings: 'Nunito, sans-serif'.
             // We can just use that.
             $final_font_stack = $defaults[$key];
        } else {
             // If stored value exists, it is likely the Key (e.g., 'Poppins')
             // We need to look it up in the map to get 'Poppins' (redundant but safe) 
             // and then append generic fallback.
             
             // Check if it's a key in our map
             if (array_key_exists($stored_val, $fonts_map)) {
                  $font_family = $fonts_map[$stored_val];
                  if ($font_family === 'sans-serif') {
                      $final_font_stack = 'sans-serif';
                  } elseif ($font_family === 'serif') {
                      $final_font_stack = 'serif';
                  } else {
                      // Append appropriate fallback
                      if ($slug === 'serif') {
                           $final_font_stack = "'{$font_family}', serif";
                      } else {
                           $final_font_stack = "'{$font_family}', sans-serif";
                      }
                  }
             } else {
                  // Fallback: it might be a raw string from before the update
                  $final_font_stack = $stored_val;
             }
        }

        $css_vars[] = "--awt-font-{$slug}: {$final_font_stack};";
    }

    echo "<style>:root {\n" . implode("\n", $css_vars) . "\n}</style>\n";
}
add_action('wp_head', 'rswpthemes_awt_custom_styles', 999);
add_action('admin_head', 'rswpthemes_awt_custom_styles', 999); // Also inject in admin for block editor preview

/**
 * Enqueue Google Fonts
 */
function rswpthemes_awt_enqueue_google_fonts() {
    $options = get_option('awt_global_settings', []);
    $fonts_map = rswpthemes_awt_get_google_fonts();
    
    // We need to gather all unique fonts that aren't system defaults
    $fonts_to_load = [];
    $font_fields = ['font_sans', 'font_inter', 'font_serif'];
    
    // Default fallback keys if nothing saved
    $default_keys = [
        'font_sans' => 'Nunito',
        'font_inter' => 'Inter',
        'font_serif' => 'Libre Baskerville'
    ];

    foreach ($font_fields as $field) {
        $val = isset($options[$field]) ? $options[$field] : $default_keys[$field];
        
        // If it's in our map and NOT 'System Default'
        if (array_key_exists($val, $fonts_map) && $val !== 'System Default') {
            $fonts_to_load[] = $val; // The Key is the Font Name e.g. 'Poppins'
        } elseif (!array_key_exists($val, $fonts_map) && strpos($val, ',') === false) {
             // It might be a custom string "Nunito" from default
             // Just add it if it looks like a clean name
             $fonts_to_load[] = $val;
        }
    }
    
    $fonts_to_load = array_unique($fonts_to_load);
    
    if (empty($fonts_to_load)) {
        return;
    }
    
    // Construct URL
    // Format: family=Name:wght@400;700&...
    $family_args = [];
    foreach ($fonts_to_load as $font) {
        $font_encoded = urlencode($font);
        $family_args[] = "family={$font_encoded}:wght@400;600;700;900"; // Load common weights
    }
    
    $query_args = implode('&', $family_args) . '&display=swap';
    $fonts_url = "https://fonts.googleapis.com/css2?" . $query_args;
    
    wp_enqueue_style('awt-google-fonts', $fonts_url, [], null);
}
add_action('wp_enqueue_scripts', 'rswpthemes_awt_enqueue_google_fonts');
add_action('admin_enqueue_scripts', 'rswpthemes_awt_enqueue_google_fonts'); // Load in admin too
