<?php
/**
 * Product Name Widget — render functions
 * All functions are standalone, prefixed ggmc_product_name_.
 * $widget replaces $this throughout.
 */

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

/**
 * Main render entry point.
 *
 * @param \GGM_Commerce_Widget_Product_Name $widget
 */
function ggmc_product_name_render( $widget ) {
    $settings = $widget->get_settings_for_display();

    // Get product data (includes preview product support)
    $product_data = $widget->get_product_data();

    // Get product name
    $product_name = 'Product Name'; // Default placeholder for editor

    if ( $product_data && isset( $product_data->name ) && ! empty( $product_data->name ) ) {
        $product_name = $product_data->name;
    } elseif ( ! ggmc_is_editor_mode() ) {
        $product_name = ''; // Show nothing on live site if no product
    }

    // If no product name on live site, don't render anything
    if ( empty( $product_name ) && ! ggmc_is_editor_mode() ) {
        return;
    }

    $html_tag = $settings['html_tag'] ?? 'h2';

    // Add CSS classes and default margin
    $widget->add_render_attribute( 'product_name', 'class', 'ggmc-product-name' );

    // Add default bottom margin when defaults are enabled
    if ( ggmc_product_name_has_default_styling( $widget ) ) {
        $widget->add_render_attribute( 'product_name', 'style', 'margin-bottom: 16px;' );
    }

    // Build the HTML
    $title_html = sprintf(
        '<%1$s %2$s>%3$s</%1$s>',
        $html_tag,
        $widget->get_render_attribute_string( 'product_name' ),
        esc_html( $product_name )
    );

    // Wrap with link if enabled
    if ( ! empty( $settings['enable_link'] ) && $settings['enable_link'] === 'yes' && ! empty( $settings['link']['url'] ) ) {
        $widget->add_link_attributes( 'link', $settings['link'] );
        $widget->add_render_attribute( 'link', 'class', 'ggmc-product-name-link' );
        $title_html = sprintf(
            '<a %1$s>%2$s</a>',
            $widget->get_render_attribute_string( 'link' ),
            $title_html
        );
    }

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $title_html is built from escaped components
    echo $title_html;
}

/**
 * Check if default styling is currently enabled.
 *
 * @param \GGM_Commerce_Widget_Product_Name $widget
 * @return bool
 */
function ggmc_product_name_has_default_styling( $widget ) {
    // Check if defaults are enabled by looking at the current file content
    $widget_file = dirname( __FILE__ ) . '/../widget-product-name.php';
    $content = file_get_contents( $widget_file );

    // If text_color has the default value, assume defaults are enabled
    $has_defaults = strpos( $content, "'default' => '#1F2937'" ) !== false;

    return $has_defaults;
}
