<?php

/**
 * Swatch payload normalizer.
 *
 * @package B3WVS\VariationSwatches\Frontend
 */
namespace B3WVS\VariationSwatches\Frontend;

defined( 'ABSPATH' ) || exit;
/**
 * Class SwatchPayloadNormalizer
 */
class SwatchPayloadNormalizer {
    /**
     * Normalize swatch payload so mismatched types gracefully downgrade instead of rendering invisible UI.
     *
     * @param array  $raw   Raw shared swatch data (type/color/hide_label).
     * @param string $label Human-friendly label for the option.
     * @return array        Safe, normalized swatch payload for the frontend.
     */
    public static function normalize( $raw, $label ) {
        $type = ( isset( $raw['type'] ) ? (string) $raw['type'] : '' );
        $color = ( isset( $raw['color'] ) ? (string) $raw['color'] : '' );
        $valid_types = array('button', 'color');
        if ( !in_array( $type, $valid_types, true ) ) {
            $type = '';
        }
        $has_color = '' !== trim( $color );
        if ( '' === $type && $has_color ) {
            $type = 'color';
            $effective_type = 'color';
        } else {
            $effective_type = $type;
        }
        if ( 'color' === $effective_type && !$has_color ) {
            $effective_type = 'button';
        }
        return array(
            'type'  => $effective_type,
            'color' => ( $has_color ? $color : '' ),
            'label' => $label,
        );
    }

}
