<?php
/**
 * Customizer Section Shortcuts
 * 
 * Adds clickable edit icons to each homepage section when in Customizer preview.
 * Clicking an icon navigates to that section's settings panel.
 *
 * @package Paws_And_Care
 * @since 3.0.1
 */

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

/**
 * Output a section shortcut button
 * 
 * Only outputs when in Customizer preview mode.
 *
 * @param string $section_id The Customizer section ID to focus when clicked
 * @param string $label      Optional label for the tooltip (defaults to "Edit Section")
 */
function paws_and_care_section_shortcut($section_id, $label = '')
{
    // Only show in Customizer preview
    if (!is_customize_preview()) {
        return;
    }

    // Sanitize section ID
    $section_id = sanitize_key($section_id);

    // Default label
    if (empty($label)) {
        $label = __('Edit Section', 'paws-and-care');
    }

    // Output the shortcut button
    ?>
    <button type="button" class="customizer-section-shortcut" data-section="<?php echo esc_attr($section_id); ?>"
        title="<?php echo esc_attr($label); ?>" aria-label="<?php echo esc_attr($label); ?>">
        <i class="fa-solid fa-pencil" aria-hidden="true"></i>
        <span class="screen-reader-text"><?php echo esc_html($label); ?></span>
    </button>
    <?php
}

/**
 * Enqueue section shortcut assets for Customizer preview
 */
function paws_and_care_section_shortcut_assets()
{
    // CSS for shortcut styling
    wp_enqueue_style(
        'paws-and-care-section-shortcuts',
        get_template_directory_uri() . '/inc/customizer/assets/css/section-shortcuts.css',
        array(),
        PAWS_AND_CARE_VERSION
    );

    // JS for shortcut functionality (handles both click events and scroll requests)
    wp_enqueue_script(
        'paws-and-care-section-shortcuts',
        get_template_directory_uri() . '/inc/customizer/assets/js/section-shortcuts.js',
        array('jquery', 'customize-preview'),
        PAWS_AND_CARE_VERSION,
        true
    );
}
// Use customize_preview_init to ensure scripts load in the preview iframe
add_action('customize_preview_init', 'paws_and_care_section_shortcut_assets');

/**
 * Enqueue Customizer panel script (for receiving focus messages and sending scroll requests)
 */
function paws_and_care_customizer_panel_script()
{
    wp_enqueue_script(
        'paws-and-care-customizer-panel',
        get_template_directory_uri() . '/inc/customizer/assets/js/customizer-panel.js',
        array('customize-controls'),
        PAWS_AND_CARE_VERSION,
        true
    );
}
add_action('customize_controls_enqueue_scripts', 'paws_and_care_customizer_panel_script');
