<?php
/**
 * Font stack normalization utilities.
 *
 * Handles extracting font family names from CSS font stacks and
 * building proper font-family CSS rules.
 *
 * @package B3WVS\VariationSwatches\Assets\TypographyRenderer
 */

namespace B3WVS\VariationSwatches\Assets\TypographyRenderer;

defined( 'ABSPATH' ) || exit;

/**
 * Generic font keywords that should not be extracted as family names.
 */
const GENERIC_FONT_KEYWORDS = array(
	'inherit',
	'serif',
	'sans-serif',
	'monospace',
	'cursive',
	'fantasy',
	'system-ui',
);

/**
 * Extract font family from a font stack string.
 *
 * @param string $stack Font stack (e.g., "Inter, sans-serif").
 * @return string Family name or empty string.
 */
function extract_family_name_from_font_stack( $stack ) {
	$stack = is_string( $stack ) ? trim( $stack ) : '';
	if ( '' === $stack || 'inherit' === $stack ) {
		return '';
	}

	// Check for double-quoted font names.
	if ( preg_match( '/^\"([^\"]+)\"/', $stack, $m ) ) {
		return sanitize_text_field( (string) $m[1] );
	}

	// Check for single-quoted font names.
	if ( preg_match( '/^\'([^\']+)\'/', $stack, $m ) ) {
		return sanitize_text_field( (string) $m[1] );
	}

	// Split by comma and get first non-generic font.
	$parts = explode( ',', $stack );
	if ( ! empty( $parts ) ) {
		$first = trim( $parts[0] );
		if ( '' !== $first && ! in_array( strtolower( $first ), GENERIC_FONT_KEYWORDS, true ) ) {
			return sanitize_text_field( $first );
		}
	}

	return '';
}

/**
 * Build font-family CSS rule while preserving quotes.
 *
 * Adds quotes around font names with spaces that don't already have them.
 *
 * @param string $family Font stack.
 * @return string CSS snippet (e.g., 'font-family: "Inter", sans-serif !important;').
 */
function font_family_rule( $family ) {
	$font_parts      = array_map( 'trim', explode( ',', $family ) );
	$formatted_fonts = array();

	foreach ( $font_parts as $font_part ) {
		// Add quotes if:
		// - Contains spaces AND
		// - Not already quoted AND
		// - Not a generic font keyword.
		if (
			strpos( $font_part, ' ' ) !== false &&
			strpos( $font_part, '"' ) === false &&
			strpos( $font_part, "'" ) === false &&
			! in_array( strtolower( $font_part ), GENERIC_FONT_KEYWORDS, true )
		) {
			$formatted_fonts[] = '"' . $font_part . '"';
		} else {
			$formatted_fonts[] = $font_part;
		}
	}

	return sprintf( 'font-family: %s !important;', implode( ', ', $formatted_fonts ) );
}
