/*
Theme Name: OceanWP Child Theme
Theme URI: https://oceanwp.org/
Description: OceanWP WordPress theme. Sample child theme.
Author: OceanWP
Author URI: https://oceanwp.org/
Template: oceanwp
Version: 1.0
*/

/* Parent stylesheet should be loaded from functions.php not using @import */

<?php
/**
 * Hound and Friends Child Theme Functions
 *
 * Keeps all parent theme, WordPress, and WooCommerce functionality intact
 * while adding dynamic WooCommerce swatches, AJAX cart controls,
 * category cards, and header cart synchronization.
 *
 * @package HoundAndFriends
 */

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

define( 'HF_CHILD_VERSION', '1.0.0' );
define( 'HF_CHILD_DIR', get_stylesheet_directory() );
define( 'HF_CHILD_URI', get_stylesheet_directory_uri() );

/**
 * Hound and Friends — Dynamic WooCommerce Swatches, Categories,
 * Interactive Cart Controls, and Live Header Cart Fragments.
 *
 * @package HoundAndFriends
 */

/**
 * --------------------------------------------------------------------------
 * 1. THEME SUPPORT & ASSET ENQUEUEING
 * --------------------------------------------------------------------------
 */

add_action( 'after_setup_theme', 'hf_woo_theme_support' );
function hf_woo_theme_support() {
	add_theme_support( 'woocommerce' );
	add_theme_support( 'wc-product-gallery-zoom' );
	add_theme_support( 'wc-product-gallery-lightbox' );
	add_theme_support( 'wc-product-gallery-slider' );
}

/**
 * Provide localized runtime data for both Website Engine (homepage)
 * and fallback assets (non-homepage pages such as Shop/Category/Product).
 */
add_action( 'wp_enqueue_scripts', 'hf_enqueue_frontend_assets', 30 );
function hf_enqueue_frontend_assets() {
	if ( ! class_exists( 'WooCommerce' ) ) {
		return;
	}

	// Ensure WooCommerce cart fragments script is available everywhere for header badge sync.
	wp_enqueue_script( 'wc-cart-fragments' );

	// Always output a tiny global config object before Website Engine runs.
	$cart_map = hf_get_cart_quantity_map();
	$config   = array(
		'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
		'nonce'          => wp_create_nonce( 'hf_store_nonce' ),
		'cartUrl'        => function_exists( 'wc_get_cart_url' ) ? wc_get_cart_url() : home_url( '/cart/' ),
		'shopUrl'        => function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'shop' ) : home_url( '/shop/' ),
		'currencySymbol' => function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol() : '$',
		'cartCount'      => WC()->cart ? (int) WC()->cart->get_cart_contents_count() : 0,
		'cartMap'        => $cart_map,
		'i18n'           => array(
			'selectOptions'  => __( 'Select color or texture', 'hound-and-friends' ),
			'outOfStock'     => __( 'Out of stock', 'hound-and-friends' ),
			'added'          => __( 'Added to bag', 'hound-and-friends' ),
			'error'          => __( 'Could not update cart. Please try again.', 'hound-and-friends' ),
			'searchEmpty'    => __( 'No matching accessories found.', 'hound-and-friends' ),
			'searchLoading'  => __( 'Searching...', 'hound-and-friends' ),
			'subSuccess'     => __( 'Welcome to the pack! Check your inbox soon.', 'hound-and-friends' ),
			'subInvalid'     => __( 'Please enter a valid email address.', 'hound-and-friends' ),
		),
	);

	// Register lightweight header/footer baseline stylesheet (header & footer do NOT contain Website Engine).
	$hf_base_css = HF_CHILD_DIR . '/assets/css/hf-header-footer.css';
	if ( file_exists( $hf_base_css ) ) {
		wp_enqueue_style(
			'hf-header-footer',
			HF_CHILD_URI . '/assets/css/hf-header-footer.css',
			array(),
			filemtime( $hf_base_css )
		);
	}

	// On non-homepage routes (Shop, Category, Single Product, Events, About),
	// enqueue the storefront CSS/JS fallback so dynamic cards, swatches, and header search work everywhere.
	// On the homepage, the centralized "Website Engine" HTML widget handles all page CSS/JS.
	if ( ! is_front_page() ) {
		$fallback_css = HF_CHILD_DIR . '/assets/css/hf-storefront-fallback.css';
		$fallback_js  = HF_CHILD_DIR . '/assets/js/hf-storefront-fallback.js';

		if ( file_exists( $fallback_css ) ) {
			wp_enqueue_style(
				'hf-storefront-fallback',
				HF_CHILD_URI . '/assets/css/hf-storefront-fallback.css',
				array(),
				filemtime( $fallback_css )
			);
		}
		if ( file_exists( $fallback_js ) ) {
			wp_enqueue_script(
				'hf-storefront-fallback',
				HF_CHILD_URI . '/assets/js/hf-storefront-fallback.js',
				array( 'jquery' ),
				filemtime( $fallback_js ),
				true
			);
		}
	}

	// Attach global runtime data safely in head so Website Engine always reads it immediately.
	wp_register_script( 'hf-runtime-config', false, array(), HF_CHILD_VERSION, false );
	wp_enqueue_script( 'hf-runtime-config' );
	wp_add_inline_script(
		'hf-runtime-config',
		'window.hfStoreData = ' . wp_json_encode( $config ) . ';',
		'before'
	);
}

/**
 * --------------------------------------------------------------------------
 * 2. ADMIN: PRODUCT CATEGORY TAGLINE & ATTRIBUTE SWATCH META
 * --------------------------------------------------------------------------
 */

add_action( 'admin_enqueue_scripts', 'hf_enqueue_admin_swatch_assets' );
function hf_enqueue_admin_swatch_assets( $hook ) {
	if ( ! in_array( $hook, array( 'edit-tags.php', 'term.php' ), true ) ) {
		return;
	}

	$taxonomy = isset( $_GET['taxonomy'] ) ? sanitize_key( wp_unslash( $_GET['taxonomy'] ) ) : '';
	if ( strpos( $taxonomy, 'pa_' ) !== 0 && 'product_cat' !== $taxonomy ) {
		return;
	}

	wp_enqueue_media();
	wp_enqueue_style( 'wp-color-picker' );

	$admin_css = HF_CHILD_DIR . '/assets/css/hf-admin-swatches.css';
	$admin_js  = HF_CHILD_DIR . '/assets/js/hf-admin-swatches.js';

	if ( file_exists( $admin_css ) ) {
		wp_enqueue_style( 'hf-admin-swatches', HF_CHILD_URI . '/assets/css/hf-admin-swatches.css', array(), filemtime( $admin_css ) );
	}
	if ( file_exists( $admin_js ) ) {
		wp_enqueue_script( 'hf-admin-swatches', HF_CHILD_URI . '/assets/js/hf-admin-swatches.js', array( 'jquery', 'wp-color-picker' ), filemtime( $admin_js ), true );
	}
}

/**
 * Category Tagline field for WooCommerce Product Categories (used on Figma category cards).
 */
add_action( 'product_cat_add_form_fields', 'hf_product_cat_add_tagline_field' );
function hf_product_cat_add_tagline_field() {
	?>
	<div class="form-field term-hf-tagline-wrap">
		<label for="hf_cat_tagline"><?php esc_html_e( 'Card Tagline (Short Subtitle)', 'hound-and-friends' ); ?></label>
		<input type="text" name="hf_cat_tagline" id="hf_cat_tagline" value="" placeholder="<?php esc_attr_e( 'e.g. Small accessory. Big personality.', 'hound-and-friends' ); ?>" />
		<p class="description"><?php esc_html_e( 'Short tagline displayed on homepage category cards.', 'hound-and-friends' ); ?></p>
	</div>
	<?php
}

add_action( 'product_cat_edit_form_fields', 'hf_product_cat_edit_tagline_field' );
function hf_product_cat_edit_tagline_field( $term ) {
	$tagline = get_term_meta( $term->term_id, 'hf_cat_tagline', true );
	?>
	<tr class="form-field term-hf-tagline-wrap">
		<th scope="row"><label for="hf_cat_tagline"><?php esc_html_e( 'Card Tagline (Short Subtitle)', 'hound-and-friends' ); ?></label></th>
		<td>
			<input type="text" name="hf_cat_tagline" id="hf_cat_tagline" value="<?php echo esc_attr( $tagline ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'e.g. Small accessory. Big personality.', 'hound-and-friends' ); ?>" />
			<p class="description"><?php esc_html_e( 'Short tagline displayed on homepage category cards.', 'hound-and-friends' ); ?></p>
		</td>
	</tr>
	<?php
}

add_action( 'created_product_cat', 'hf_save_product_cat_tagline' );
add_action( 'edited_product_cat', 'hf_save_product_cat_tagline' );
function hf_save_product_cat_tagline( $term_id ) {
	if ( isset( $_POST['hf_cat_tagline'] ) ) {
		update_term_meta( $term_id, 'hf_cat_tagline', sanitize_text_field( wp_unslash( $_POST['hf_cat_tagline'] ) ) );
	}
}

/**
 * Determine attribute visual swatch type ('color' or 'texture') by attribute slug.
 */
function hf_detect_attribute_swatch_type( $taxonomy_slug ) {
	$slug = strtolower( $taxonomy_slug );
	if ( false !== strpos( $slug, 'color' ) || false !== strpos( $slug, 'colour' ) ) {
		return 'color';
	}
	if (
		false !== strpos( $slug, 'texture' ) ||
		false !== strpos( $slug, 'pattern' ) ||
		false !== strpos( $slug, 'fabric' ) ||
		false !== strpos( $slug, 'material' ) ||
		false !== strpos( $slug, 'print' )
	) {
		return 'texture';
	}
	return 'text';
}

/**
 * Register Color Picker & Texture Image Uploader on WooCommerce Attribute taxonomies.
 */
add_action( 'admin_init', 'hf_register_attribute_swatch_hooks' );
function hf_register_attribute_swatch_hooks() {
	if ( ! function_exists( 'wc_get_attribute_taxonomies' ) ) {
		return;
	}

	$taxonomies = wc_get_attribute_taxonomies();
	if ( empty( $taxonomies ) ) {
		return;
	}

	foreach ( $taxonomies as $tax ) {
		$taxonomy_name = wc_attribute_taxonomy_name( $tax->attribute_name );
		$type          = hf_detect_attribute_swatch_type( $taxonomy_name );

		if ( 'color' === $type ) {
			add_action( "{$taxonomy_name}_add_form_fields", 'hf_attr_add_color_field' );
			add_action( "{$taxonomy_name}_edit_form_fields", 'hf_attr_edit_color_field', 10, 2 );
			add_filter( "manage_edit-{$taxonomy_name}_columns", 'hf_attr_add_swatch_column' );
			add_filter( "manage_{$taxonomy_name}_custom_column", 'hf_attr_render_color_column', 10, 3 );
		} elseif ( 'texture' === $type ) {
			add_action( "{$taxonomy_name}_add_form_fields", 'hf_attr_add_texture_field' );
			add_action( "{$taxonomy_name}_edit_form_fields", 'hf_attr_edit_texture_field', 10, 2 );
			add_filter( "manage_edit-{$taxonomy_name}_columns", 'hf_attr_add_swatch_column' );
			add_filter( "manage_{$taxonomy_name}_custom_column", 'hf_attr_render_texture_column', 10, 3 );
		}

		add_action( "created_{$taxonomy_name}", 'hf_save_attribute_swatch_meta' );
		add_action( "edited_{$taxonomy_name}", 'hf_save_attribute_swatch_meta' );
	}
}

function hf_attr_add_color_field() {
	?>
	<div class="form-field term-hf-color-wrap">
		<label for="hf_swatch_color"><?php esc_html_e( 'Swatch Color', 'hound-and-friends' ); ?></label>
		<input type="text" name="hf_swatch_color" id="hf_swatch_color" class="hf-color-picker" value="#2152E5" />
		<p class="description"><?php esc_html_e( 'Choose the circular swatch color displayed on product cards.', 'hound-and-friends' ); ?></p>
	</div>
	<?php
}

function hf_attr_edit_color_field( $term ) {
	$color = get_term_meta( $term->term_id, 'hf_swatch_color', true );
	if ( empty( $color ) ) {
		$color = get_term_meta( $term->term_id, 'product_attribute_color', true );
	}
	?>
	<tr class="form-field term-hf-color-wrap">
		<th scope="row"><label for="hf_swatch_color"><?php esc_html_e( 'Swatch Color', 'hound-and-friends' ); ?></label></th>
		<td>
			<input type="text" name="hf_swatch_color" id="hf_swatch_color" class="hf-color-picker" value="<?php echo esc_attr( $color ); ?>" />
			<p class="description"><?php esc_html_e( 'Choose the circular swatch color displayed on product cards.', 'hound-and-friends' ); ?></p>
		</td>
	</tr>
	<?php
}

function hf_attr_add_texture_field() {
	?>
	<div class="form-field term-hf-texture-wrap">
		<label for="hf_swatch_image_id"><?php esc_html_e( 'Texture Swatch Image', 'hound-and-friends' ); ?></label>
		<div class="hf-texture-uploader">
			<input type="hidden" name="hf_swatch_image_id" id="hf_swatch_image_id" value="" />
			<div class="hf-texture-preview" id="hf-texture-preview"></div>
			<button type="button" class="button hf-upload-texture-btn"><?php esc_html_e( 'Upload / Choose Texture', 'hound-and-friends' ); ?></button>
			<button type="button" class="button hf-remove-texture-btn" style="display:none;"><?php esc_html_e( 'Remove', 'hound-and-friends' ); ?></button>
		</div>
		<p class="description"><?php esc_html_e( 'Square fabric/pattern swatch image shown on product cards.', 'hound-and-friends' ); ?></p>
	</div>
	<?php
}

function hf_attr_edit_texture_field( $term ) {
	$image_id  = absint( get_term_meta( $term->term_id, 'hf_swatch_image_id', true ) );
	$image_url = $image_id ? wp_get_attachment_image_url( $image_id, 'thumbnail' ) : '';
	?>
	<tr class="form-field term-hf-texture-wrap">
		<th scope="row"><label for="hf_swatch_image_id"><?php esc_html_e( 'Texture Swatch Image', 'hound-and-friends' ); ?></label></th>
		<td>
			<div class="hf-texture-uploader">
				<input type="hidden" name="hf_swatch_image_id" id="hf_swatch_image_id" value="<?php echo esc_attr( $image_id ); ?>" />
				<div class="hf-texture-preview" id="hf-texture-preview">
					<?php if ( $image_url ) : ?>
						<img src="<?php echo esc_url( $image_url ); ?>" alt="" />
					<?php endif; ?>
				</div>
				<button type="button" class="button hf-upload-texture-btn"><?php esc_html_e( 'Upload / Choose Texture', 'hound-and-friends' ); ?></button>
				<button type="button" class="button hf-remove-texture-btn" <?php echo $image_url ? '' : 'style="display:none;"'; ?>><?php esc_html_e( 'Remove', 'hound-and-friends' ); ?></button>
			</div>
			<p class="description"><?php esc_html_e( 'Square fabric/pattern swatch image shown on product cards.', 'hound-and-friends' ); ?></p>
		</td>
	</tr>
	<?php
}

function hf_save_attribute_swatch_meta( $term_id ) {
	if ( isset( $_POST['hf_swatch_color'] ) ) {
		$hex = sanitize_hex_color( wp_unslash( $_POST['hf_swatch_color'] ) );
		update_term_meta( $term_id, 'hf_swatch_color', $hex ? $hex : '' );
	}
	if ( isset( $_POST['hf_swatch_image_id'] ) ) {
		update_term_meta( $term_id, 'hf_swatch_image_id', absint( wp_unslash( $_POST['hf_swatch_image_id'] ) ) );
	}
}

function hf_attr_add_swatch_column( $columns ) {
	$new_columns = array();
	foreach ( $columns as $key => $label ) {
		if ( 'name' === $key ) {
			$new_columns['hf_swatch'] = __( 'Swatch', 'hound-and-friends' );
		}
		$new_columns[ $key ] = $label;
	}
	return $new_columns;
}

function hf_attr_render_color_column( $content, $column_name, $term_id ) {
	if ( 'hf_swatch' === $column_name ) {
		$hex = hf_resolve_term_color_hex( $term_id );
		return '<span class="hf-admin-swatch-dot" style="background:' . esc_attr( $hex ) . '"></span>';
	}
	return $content;
}

function hf_attr_render_texture_column( $content, $column_name, $term_id ) {
	if ( 'hf_swatch' === $column_name ) {
		$img_id = absint( get_term_meta( $term_id, 'hf_swatch_image_id', true ) );
		$url    = $img_id ? wp_get_attachment_image_url( $img_id, 'thumbnail' ) : '';
		if ( $url ) {
			return '<img class="hf-admin-swatch-tex" src="' . esc_url( $url ) . '" alt="" />';
		}
		return '<span class="hf-admin-swatch-empty">—</span>';
	}
	return $content;
}

/**
 * Resolve hex color from term meta, WoodMart/plugin meta, or sensible slug fallback.
 */
function hf_resolve_term_color_hex( $term_id, $term_slug = '' ) {
	$hex = get_term_meta( $term_id, 'hf_swatch_color', true );
	if ( empty( $hex ) ) {
		$hex = get_term_meta( $term_id, 'product_attribute_color', true );
	}
	if ( empty( $hex ) ) {
		$hex = get_term_meta( $term_id, 'color', true );
	}
	if ( ! empty( $hex ) ) {
		return $hex;
	}

	$slug = strtolower( $term_slug );
	$map  = array(
		'blue'         => '#2152E5',
		'royal-blue'   => '#2152E5',
		'cobalt'       => '#2152E5',
		'navy'         => '#1E3A5F',
		'sky-blue'     => '#8FB3F4',
		'beige'        => '#DFD2BE',
		'tan'          => '#D5BA9D',
		'oatmeal'      => '#E8E2D5',
		'cream'        => '#EFECE4',
		'sand'         => '#D8C7B2',
		'terracotta'   => '#B56B52',
		'brown'        => '#8E5B43',
		'blush'        => '#E3ACA0',
		'coral'        => '#D97B6C',
		'sage'         => '#8A9A84',
		'olive'        => '#73826A',
		'forest'       => '#2F523B',
		'charcoal'     => '#3D4249',
		'black'        => '#1A1D23',
		'white'        => '#F8FAFC',
		'red'          => '#C83E3B',
		'burgundy'     => '#7B2D3B',
		'yellow'       => '#E6B84C',
	);

	foreach ( $map as $key => $color ) {
		if ( false !== strpos( $slug, $key ) ) {
			return $color;
		}
	}

	return '#CBD5E1';
}

/**
 * Resolve texture image URL from term meta or fallback to matching variation image.
 */
function hf_resolve_term_texture_url( $term_id, $taxonomy = '', $term_slug = '', $variations = array() ) {
	$image_id = absint( get_term_meta( $term_id, 'hf_swatch_image_id', true ) );
	if ( ! $image_id ) {
		$image_id = absint( get_term_meta( $term_id, 'image', true ) );
	}
	if ( ! $image_id ) {
		$image_id = absint( get_term_meta( $term_id, 'product_attribute_image', true ) );
	}
	if ( $image_id ) {
		$url = wp_get_attachment_image_url( $image_id, 'thumbnail' );
		if ( $url ) {
			return $url;
		}
	}

	// Fallback: look for any variation image matching this texture term.
	if ( ! empty( $variations ) && $taxonomy && $term_slug ) {
		$attr_key = 'attribute_' . $taxonomy;
		foreach ( $variations as $variation ) {
			if ( isset( $variation['attributes'][ $attr_key ] ) && $variation['attributes'][ $attr_key ] === $term_slug ) {
				if ( ! empty( $variation['image_thumb'] ) ) {
					return $variation['image_thumb'];
				}
				if ( ! empty( $variation['image_src'] ) ) {
					return $variation['image_src'];
				}
			}
		}
	}

	return '';
}

/**
 * --------------------------------------------------------------------------
 * 3. SHORTCODE: DYNAMIC PRODUCT CATEGORIES ([hf_product_categories])
 * --------------------------------------------------------------------------
 */

add_shortcode( 'hf_product_categories', 'hf_shortcode_product_categories' );
function hf_shortcode_product_categories( $atts ) {
	if ( ! class_exists( 'WooCommerce' ) ) {
		return '';
	}

	$atts = shortcode_atts(
		array(
			'limit'      => 4,
			'columns'    => 4,
			'hide_empty' => 'false',
			'slugs'      => '',
		),
		$atts,
		'hf_product_categories'
	);

	$hide_empty = filter_var( $atts['hide_empty'], FILTER_VALIDATE_BOOLEAN );
	$limit      = max( 1, absint( $atts['limit'] ) );
	$columns    = max( 1, min( 6, absint( $atts['columns'] ) ) );

	$args = array(
		'taxonomy'   => 'product_cat',
		'hide_empty' => $hide_empty,
		'parent'     => 0,
	);

	// Exclude default Uncategorized term.
	$default_cat_id = (int) get_option( 'default_product_cat', 0 );
	if ( $default_cat_id > 0 ) {
		$args['exclude'] = array( $default_cat_id );
	}

	if ( ! empty( $atts['slugs'] ) ) {
		$args['slug']    = array_map( 'sanitize_title', explode( ',', $atts['slugs'] ) );
		$args['orderby'] = 'slug__in';
	}

	$terms = get_terms( $args );
	if ( is_wp_error( $terms ) || empty( $terms ) ) {
		return '<div class="hf-empty-notice">' . esc_html__( 'No product categories found in WooCommerce yet. Add categories in Products → Categories.', 'hound-and-friends' ) . '</div>';
	}

	// Preserve canonical Figma order for the 4 primary categories when present.
	if ( empty( $atts['slugs'] ) ) {
		$preferred_order = array(
			'bow-ties'              => 1,
			'harnesses'             => 2,
			'leashes'               => 3,
			'pet-owner-accessories' => 4,
		);
		usort(
			$terms,
			function ( $a, $b ) use ( $preferred_order ) {
				$pa = isset( $preferred_order[ $a->slug ] ) ? $preferred_order[ $a->slug ] : 99;
				$pb = isset( $preferred_order[ $b->slug ] ) ? $preferred_order[ $b->slug ] : 99;
				if ( $pa === $pb ) {
					return strcasecmp( $a->name, $b->name );
				}
				return $pa <=> $pb;
			}
		);
	}

	$terms = array_slice( $terms, 0, $limit );

	ob_start();
	?>
	<div class="hf-categories-grid hf-cols-<?php echo esc_attr( $columns ); ?>" data-hf-reveal-group>
		<?php
		foreach ( $terms as $index => $term ) :
			$thumb_id  = absint( get_term_meta( $term->term_id, 'thumbnail_id', true ) );
			$image_url = $thumb_id ? wp_get_attachment_image_url( $thumb_id, 'medium_large' ) : wc_placeholder_img_src( 'medium_large' );
			$term_link = get_term_link( $term );
			$tagline   = get_term_meta( $term->term_id, 'hf_cat_tagline', true );
			if ( empty( $tagline ) && ! empty( $term->description ) ) {
				$tagline = wp_trim_words( wp_strip_all_tags( $term->description ), 8, '...' );
			}
			$count = absint( $term->count );
			?>
			<a href="<?php echo esc_url( is_wp_error( $term_link ) ? '#' : $term_link ); ?>"
			   class="hf-cat-card hf-reveal"
			   style="--hf-stagger: <?php echo esc_attr( $index * 70 ); ?>ms;">
				<div class="hf-cat-card__media">
					<img src="<?php echo esc_url( $image_url ); ?>"
					     alt="<?php echo esc_attr( $term->name ); ?>"
					     loading="lazy" />
					<?php if ( $count > 0 ) : ?>
						<span class="hf-cat-card__count">
							<?php
							/* translators: %d: number of products */
							echo esc_html( sprintf( _n( '%d item', '%d items', $count, 'hound-and-friends' ), $count ) );
							?>
						</span>
					<?php endif; ?>
				</div>
				<div class="hf-cat-card__body">
					<div class="hf-cat-card__meta">
						<h3 class="hf-cat-card__title"><?php echo esc_html( $term->name ); ?></h3>
						<?php if ( ! empty( $tagline ) ) : ?>
							<p class="hf-cat-card__tagline"><?php echo esc_html( $tagline ); ?></p>
						<?php endif; ?>
					</div>
					<span class="hf-cat-card__arrow" aria-hidden="true">
						<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
							<path d="M4.5 11.5L11.5 4.5M11.5 4.5H5.5M11.5 4.5V10.5" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
						</svg>
					</span>
				</div>
			</a>
		<?php endforeach; ?>
	</div>
	<?php
	return ob_get_clean();
}

/**
 * --------------------------------------------------------------------------
 * 4. SHORTCODE: FEATURED PRODUCTS & SHOP CATALOG
 * --------------------------------------------------------------------------
 */

add_shortcode( 'hf_featured_products', 'hf_shortcode_featured_products' );
function hf_shortcode_featured_products( $atts ) {
	if ( ! class_exists( 'WooCommerce' ) ) {
		return '';
	}

	$atts = shortcode_atts(
		array(
			'limit'    => 4,
			'columns'  => 4,
			'featured' => 'auto',
			'category' => '',
			'orderby'  => 'menu_order date',
			'order'    => 'DESC',
		),
		$atts,
		'hf_featured_products'
	);

	$limit   = max( 1, absint( $atts['limit'] ) );
	$columns = max( 1, min( 6, absint( $atts['columns'] ) ) );

	$query_args = array(
		'status'  => 'publish',
		'limit'   => $limit,
		'orderby' => sanitize_text_field( $atts['orderby'] ),
		'order'   => 'ASC' === strtoupper( $atts['order'] ) ? 'ASC' : 'DESC',
	);

	if ( ! empty( $atts['category'] ) ) {
		$query_args['category'] = array_map( 'sanitize_title', explode( ',', $atts['category'] ) );
	}

	$products = array();

	if ( 'true' === $atts['featured'] || 'auto' === $atts['featured'] ) {
		$featured_args             = $query_args;
		$featured_args['featured'] = true;
		$products                  = wc_get_products( $featured_args );
	}

	if ( 'false' === $atts['featured'] || ( 'auto' === $atts['featured'] && count( $products ) < $limit ) ) {
		$exclude_ids = array_map(
			function ( $p ) {
				return $p->get_id();
			},
			$products
		);

		$fill_args = $query_args;
		$fill_args['limit'] = $limit - count( $products );
		if ( ! empty( $exclude_ids ) ) {
			$fill_args['exclude'] = $exclude_ids;
		}
		$more_products = wc_get_products( $fill_args );
		$products      = array_merge( $products, $more_products );
	}

	if ( empty( $products ) ) {
		return '<div class="hf-empty-notice">' . esc_html__( 'No WooCommerce products found yet. Add products in Products → Add New.', 'hound-and-friends' ) . '</div>';
	}

	$cart_map = hf_get_cart_quantity_map();

	ob_start();
	?>
	<div class="hf-products-grid hf-cols-<?php echo esc_attr( $columns ); ?>" data-hf-reveal-group>
		<?php
		foreach ( $products as $index => $product ) {
			hf_render_product_card( $product, $cart_map, $index );
		}
		?>
	</div>
	<?php
	return ob_get_clean();
}

/**
 * Dynamic Shop & Category Archive catalog with category filter bar.
 */
add_shortcode( 'hf_shop_catalog', 'hf_shortcode_shop_catalog' );
function hf_shortcode_shop_catalog( $atts ) {
	if ( ! class_exists( 'WooCommerce' ) ) {
		return '';
	}

	$atts = shortcode_atts(
		array(
			'limit'   => 12,
			'columns' => 4,
		),
		$atts,
		'hf_shop_catalog'
	);

	$active_cat = '';
	if ( is_product_category() ) {
		$queried = get_queried_object();
		if ( $queried && isset( $queried->slug ) ) {
			$active_cat = $queried->slug;
		}
	} elseif ( isset( $_GET['hf_cat'] ) ) {
		$active_cat = sanitize_title( wp_unslash( $_GET['hf_cat'] ) );
	}

	$orderby = isset( $_GET['orderby'] ) ? sanitize_key( wp_unslash( $_GET['orderby'] ) ) : 'menu_order';
	$paged   = max( 1, get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : ( isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1 ) );

	$query_args = array(
		'status'   => 'publish',
		'limit'    => absint( $atts['limit'] ),
		'page'     => $paged,
		'paginate' => true,
	);

	if ( ! empty( $active_cat ) ) {
		$query_args['category'] = array( $active_cat );
	}

	switch ( $orderby ) {
		case 'price':
			$query_args['orderby'] = 'meta_value_num';
			$query_args['meta_key'] = '_price';
			$query_args['order']   = 'ASC';
			break;
		case 'price-desc':
			$query_args['orderby'] = 'meta_value_num';
			$query_args['meta_key'] = '_price';
			$query_args['order']   = 'DESC';
			break;
		case 'date':
			$query_args['orderby'] = 'date';
			$query_args['order']   = 'DESC';
			break;
		default:
			$query_args['orderby'] = 'menu_order date';
			$query_args['order']   = 'ASC';
			break;
	}

	$results  = wc_get_products( $query_args );
	$products = ! empty( $results->products ) ? $results->products : array();
	$cart_map = hf_get_cart_quantity_map();
	$shop_url = wc_get_page_permalink( 'shop' );

	$default_cat_id = (int) get_option( 'default_product_cat', 0 );
	$categories     = get_terms(
		array(
			'taxonomy'   => 'product_cat',
			'hide_empty' => false,
			'parent'     => 0,
			'exclude'    => $default_cat_id ? array( $default_cat_id ) : array(),
		)
	);

	ob_start();
	?>
	<div class="hf-catalog-wrap">
		<div class="hf-catalog-toolbar">
			<div class="hf-catalog-pills" role="navigation" aria-label="<?php esc_attr_e( 'Product Categories', 'hound-and-friends' ); ?>">
				<a href="<?php echo esc_url( $shop_url ); ?>" class="hf-filter-pill <?php echo '' === $active_cat ? 'is-active' : ''; ?>">
					<?php esc_html_e( 'All Accessories', 'hound-and-friends' ); ?>
				</a>
				<?php if ( ! is_wp_error( $categories ) ) : ?>
					<?php foreach ( $categories as $cat ) : ?>
						<?php $cat_link = get_term_link( $cat ); ?>
						<a href="<?php echo esc_url( is_wp_error( $cat_link ) ? '#' : $cat_link ); ?>"
						   class="hf-filter-pill <?php echo $active_cat === $cat->slug ? 'is-active' : ''; ?>">
							<?php echo esc_html( $cat->name ); ?>
						</a>
					<?php endforeach; ?>
				<?php endif; ?>
			</div>

			<form class="hf-catalog-sort" method="get">
				<?php if ( ! empty( $active_cat ) && ! is_product_category() ) : ?>
					<input type="hidden" name="hf_cat" value="<?php echo esc_attr( $active_cat ); ?>" />
				<?php endif; ?>
				<label class="screen-reader-text" for="hf-orderby"><?php esc_html_e( 'Sort products', 'hound-and-friends' ); ?></label>
				<select id="hf-orderby" name="orderby" onchange="this.form.submit()">
					<option value="menu_order" <?php selected( $orderby, 'menu_order' ); ?>><?php esc_html_e( 'Featured', 'hound-and-friends' ); ?></option>
					<option value="date" <?php selected( $orderby, 'date' ); ?>><?php esc_html_e( 'Newest', 'hound-and-friends' ); ?></option>
					<option value="price" <?php selected( $orderby, 'price' ); ?>><?php esc_html_e( 'Price: Low to High', 'hound-and-friends' ); ?></option>
					<option value="price-desc" <?php selected( $orderby, 'price-desc' ); ?>><?php esc_html_e( 'Price: High to Low', 'hound-and-friends' ); ?></option>
				</select>
			</form>
		</div>

		<?php if ( empty( $products ) ) : ?>
			<div class="hf-empty-notice"><?php esc_html_e( 'No products match this category yet.', 'hound-and-friends' ); ?></div>
		<?php else : ?>
			<div class="hf-products-grid hf-cols-<?php echo esc_attr( absint( $atts['columns'] ) ); ?>" data-hf-reveal-group>
				<?php
				foreach ( $products as $index => $product ) {
					hf_render_product_card( $product, $cart_map, $index );
				}
				?>
			</div>
		<?php endif; ?>
	</div>
	<?php
	return ob_get_clean();
}

/**
 * Render a single Figma-faithful dynamic WooCommerce product card.
 *
 * @param WC_Product $product  Product object.
 * @param array      $cart_map Current cart map keyed by product/variation ID.
 * @param int        $index    Card index for stagger reveal animation.
 */
function hf_render_product_card( $product, $cart_map = array(), $index = 0 ) {
	if ( ! $product instanceof WC_Product ) {
		return;
	}

	$product_id   = $product->get_id();
	$product_type = $product->get_type();
	$permalink    = $product->get_permalink();
	$title        = $product->get_name();
	$image_id     = $product->get_image_id();
	$image_url    = $image_id ? wp_get_attachment_image_url( $image_id, 'medium_large' ) : wc_placeholder_img_src( 'medium_large' );

	// Primary product category eyebrow (excluding Uncategorized).
	$default_cat_id = (int) get_option( 'default_product_cat', 0 );
	$cat_terms      = get_the_terms( $product_id, 'product_cat' );
	$category_label = '';
	if ( ! empty( $cat_terms ) && ! is_wp_error( $cat_terms ) ) {
		foreach ( $cat_terms as $term ) {
			if ( (int) $term->term_id !== $default_cat_id ) {
				$category_label = $term->name;
				break;
			}
		}
	}

	// Variable product attributes & variation matrix.
	$is_variable       = $product->is_type( 'variable' );
	$variations_data   = array();
	$color_groups      = array();
	$texture_groups    = array();
	$other_groups      = array();
	$default_attrs     = array();
	$selected_var_id   = 0;
	$initial_image_url = $image_url;
	$initial_price     = $product->get_price_html();

	if ( $is_variable ) {
		$default_attrs        = $product->get_default_attributes();
		$variation_attributes = $product->get_variation_attributes();
		$raw_variations       = $product->get_available_variations();

		foreach ( $raw_variations as $v ) {
			$v_obj = wc_get_product( $v['variation_id'] );
			if ( ! $v_obj ) {
				continue;
			}
			$v_img_id  = $v_obj->get_image_id();
			$v_img_src = $v_img_id ? wp_get_attachment_image_url( $v_img_id, 'medium_large' ) : $image_url;
			$v_thumb   = $v_img_id ? wp_get_attachment_image_url( $v_img_id, 'thumbnail' ) : '';

			$variations_data[] = array(
				'variation_id' => (int) $v['variation_id'],
				'attributes'   => $v['attributes'],
				'is_in_stock'  => (bool) $v['is_in_stock'],
				'is_purchasable' => (bool) $v['is_purchasable'],
				'price_html'   => $v_obj->get_price_html(),
				'image_src'    => $v_img_src,
				'image_thumb'  => $v_thumb,
			);
		}

		// Match pre-selected default variation if WooCommerce defaults are configured.
		if ( ! empty( $default_attrs ) && ! empty( $variations_data ) ) {
			foreach ( $variations_data as $vd ) {
				$matched = true;
				foreach ( $default_attrs as $d_tax => $d_val ) {
					$key = 'attribute_' . sanitize_title( $d_tax );
					if ( ! isset( $vd['attributes'][ $key ] ) || $vd['attributes'][ $key ] !== $d_val ) {
						$matched = false;
						break;
					}
				}
				if ( $matched ) {
					$selected_var_id   = $vd['variation_id'];
					$initial_image_url = $vd['image_src'];
					$initial_price     = $vd['price_html'];
					break;
				}
			}
		}

		foreach ( $variation_attributes as $attr_name => $options ) {
			if ( empty( $options ) ) {
				continue;
			}
			$taxonomy   = sanitize_title( $attr_name );
			$is_tax     = taxonomy_exists( $taxonomy );
			$group_type = hf_detect_attribute_swatch_type( $taxonomy );
			$attr_label = wc_attribute_label( $attr_name, $product );

			$items = array();
			foreach ( $options as $opt_slug ) {
				$term_obj = $is_tax ? get_term_by( 'slug', $opt_slug, $taxonomy ) : false;
				$label    = $term_obj ? $term_obj->name : $opt_slug;
				$term_id  = $term_obj ? (int) $term_obj->term_id : 0;

				$item = array(
					'slug'  => $opt_slug,
					'label' => $label,
				);

				if ( 'color' === $group_type ) {
					$item['hex'] = hf_resolve_term_color_hex( $term_id, $opt_slug );
				} elseif ( 'texture' === $group_type ) {
					$item['image'] = hf_resolve_term_texture_url( $term_id, $taxonomy, $opt_slug, $variations_data );
				}

				$items[] = $item;
			}

			$group_payload = array(
				'taxonomy' => $taxonomy,
				'attr_key' => 'attribute_' . $taxonomy,
				'label'    => $attr_label,
				'default'  => isset( $default_attrs[ $taxonomy ] ) ? $default_attrs[ $taxonomy ] : '',
				'items'    => $items,
			);

			if ( 'color' === $group_type ) {
				$color_groups[] = $group_payload;
			} elseif ( 'texture' === $group_type ) {
				$texture_groups[] = $group_payload;
			} else {
				$other_groups[] = $group_payload;
			}
		}
	}

	// Determine current cart quantity for this product (or selected default variation).
	$cart_lookup_key = $is_variable ? ( $selected_var_id ? $product_id . ':' . $selected_var_id : '' ) : (string) $product_id;
	$initial_qty     = ( $cart_lookup_key && isset( $cart_map[ $cart_lookup_key ] ) ) ? (int) $cart_map[ $cart_lookup_key ]['qty'] : 0;
	$initial_item_k  = ( $cart_lookup_key && isset( $cart_map[ $cart_lookup_key ] ) ) ? $cart_map[ $cart_lookup_key ]['key'] : '';

	$rating_avg   = (float) $product->get_average_rating();
	$rating_count = (int) $product->get_review_count();
	$is_on_sale   = $product->is_on_sale();
	?>
	<article class="hf-product-card hf-reveal <?php echo $initial_qty > 0 ? 'has-qty' : ''; ?>"
	         style="--hf-stagger: <?php echo esc_attr( $index * 70 ); ?>ms;"
	         data-product-id="<?php echo esc_attr( $product_id ); ?>"
	         data-product-type="<?php echo esc_attr( $product_type ); ?>"
	         data-variation-id="<?php echo esc_attr( $selected_var_id ); ?>"
	         data-cart-key="<?php echo esc_attr( $initial_item_k ); ?>"
	         data-qty="<?php echo esc_attr( $initial_qty ); ?>"
	         data-default-image="<?php echo esc_url( $image_url ); ?>"
	         data-default-price="<?php echo esc_attr( $product->get_price_html() ); ?>"
	         data-variations="<?php echo esc_attr( wp_json_encode( $variations_data ) ); ?>">

		<div class="hf-product-card__media">
			<a href="<?php echo esc_url( $permalink ); ?>" class="hf-product-card__img-link" aria-label="<?php echo esc_attr( $title ); ?>">
				<img class="hf-product-card__img"
				     src="<?php echo esc_url( $initial_image_url ); ?>"
				     alt="<?php echo esc_attr( $title ); ?>"
				     loading="lazy" />
			</a>

			<?php if ( $is_on_sale ) : ?>
				<span class="hf-product-card__badge"><?php esc_html_e( 'Sale', 'hound-and-friends' ); ?></span>
			<?php endif; ?>

			<button type="button"
			        class="hf-wishlist-btn"
			        data-product-id="<?php echo esc_attr( $product_id ); ?>"
			        aria-label="<?php esc_attr_e( 'Save to wishlist', 'hound-and-friends' ); ?>"
			        aria-pressed="false">
				<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
					<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
				</svg>
			</button>

			<?php if ( $product->is_purchasable() && $product->is_in_stock() ) : ?>
				<div class="hf-cart-control <?php echo $initial_qty > 0 ? 'is-expanded' : ''; ?>">
					<button type="button"
					        class="hf-qty-trigger"
					        aria-label="<?php esc_attr_e( 'Add to cart', 'hound-and-friends' ); ?>">
						<svg width="15" height="15" viewBox="0 0 16 16" fill="none" aria-hidden="true">
							<path d="M8 3.25V12.75M3.25 8H12.75" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
						</svg>
					</button>
					<div class="hf-qty-pill" aria-hidden="<?php echo $initial_qty > 0 ? 'false' : 'true'; ?>">
						<button type="button" class="hf-qty-btn hf-qty-minus" aria-label="<?php esc_attr_e( 'Decrease quantity', 'hound-and-friends' ); ?>">
							<svg width="12" height="12" viewBox="0 0 16 16" fill="none"><path d="M3.5 8H12.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
						</button>
						<span class="hf-qty-value"><?php echo esc_html( max( 0, $initial_qty ) ); ?></span>
						<button type="button" class="hf-qty-btn hf-qty-plus" aria-label="<?php esc_attr_e( 'Increase quantity', 'hound-and-friends' ); ?>">
							<svg width="12" height="12" viewBox="0 0 16 16" fill="none"><path d="M8 3.5V12.5M3.5 8H12.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
						</button>
					</div>
				</div>
			<?php endif; ?>

			<div class="hf-card-toast" role="status" aria-live="polite"></div>
		</div>

		<div class="hf-product-card__body">
			<?php if ( ! empty( $category_label ) ) : ?>
				<span class="hf-product-card__cat"><?php echo esc_html( $category_label ); ?></span>
			<?php endif; ?>

			<h3 class="hf-product-card__title">
				<a href="<?php echo esc_url( $permalink ); ?>"><?php echo esc_html( $title ); ?></a>
			</h3>

			<div class="hf-product-card__price-row">
				<div class="hf-product-card__price"><?php echo wp_kses_post( $initial_price ); ?></div>
				<?php if ( $rating_count > 0 ) : ?>
					<div class="hf-product-card__rating" aria-label="<?php echo esc_attr( sprintf( __( 'Rated %.1f out of 5', 'hound-and-friends' ), $rating_avg ) ); ?>">
						<span class="hf-star" aria-hidden="true">★</span>
						<span><?php echo esc_html( number_format( $rating_avg, 1 ) ); ?></span>
					</div>
				<?php endif; ?>
			</div>

			<?php if ( $is_variable && ( ! empty( $texture_groups ) || ! empty( $color_groups ) || ! empty( $other_groups ) ) ) : ?>
				<div class="hf-swatches-container">
					<?php
					// Texture swatches (image-based swatches) — visually separate from color swatches.
					foreach ( $texture_groups as $group ) :
						?>
						<div class="hf-swatch-group hf-swatch-group--texture"
						     data-attr-key="<?php echo esc_attr( $group['attr_key'] ); ?>"
						     role="radiogroup"
						     aria-label="<?php echo esc_attr( $group['label'] ); ?>">
							<?php foreach ( $group['items'] as $item ) : ?>
								<?php $is_active = ( $group['default'] === $item['slug'] ); ?>
								<button type="button"
								        class="hf-swatch hf-swatch-texture <?php echo $is_active ? 'is-selected' : ''; ?>"
								        data-attr-key="<?php echo esc_attr( $group['attr_key'] ); ?>"
								        data-value="<?php echo esc_attr( $item['slug'] ); ?>"
								        title="<?php echo esc_attr( $item['label'] ); ?>"
								        aria-label="<?php echo esc_attr( $group['label'] . ': ' . $item['label'] ); ?>"
								        aria-checked="<?php echo $is_active ? 'true' : 'false'; ?>"
								        role="radio">
									<?php if ( ! empty( $item['image'] ) ) : ?>
										<img src="<?php echo esc_url( $item['image'] ); ?>" alt="" loading="lazy" />
									<?php else : ?>
										<span class="hf-swatch-texture__fallback"></span>
									<?php endif; ?>
								</button>
							<?php endforeach; ?>
						</div>
					<?php endforeach; ?>

					<?php if ( ! empty( $texture_groups ) && ! empty( $color_groups ) ) : ?>
						<span class="hf-swatch-divider" aria-hidden="true"></span>
					<?php endif; ?>

					<?php
					// Color swatches (circular color dots, never text names).
					foreach ( $color_groups as $group ) :
						?>
						<div class="hf-swatch-group hf-swatch-group--color"
						     data-attr-key="<?php echo esc_attr( $group['attr_key'] ); ?>"
						     role="radiogroup"
						     aria-label="<?php echo esc_attr( $group['label'] ); ?>">
							<?php foreach ( $group['items'] as $item ) : ?>
								<?php $is_active = ( $group['default'] === $item['slug'] ); ?>
								<button type="button"
								        class="hf-swatch hf-swatch-color <?php echo $is_active ? 'is-selected' : ''; ?>"
								        data-attr-key="<?php echo esc_attr( $group['attr_key'] ); ?>"
								        data-value="<?php echo esc_attr( $item['slug'] ); ?>"
								        style="--swatch-color: <?php echo esc_attr( $item['hex'] ); ?>;"
								        title="<?php echo esc_attr( $item['label'] ); ?>"
								        aria-label="<?php echo esc_attr( $group['label'] . ': ' . $item['label'] ); ?>"
								        aria-checked="<?php echo $is_active ? 'true' : 'false'; ?>"
								        role="radio">
								</button>
							<?php endforeach; ?>
						</div>
					<?php endforeach; ?>

					<?php
					// Any additional custom attribute (e.g. size) stays compact and non-cluttered.
					foreach ( $other_groups as $group ) :
						?>
						<div class="hf-swatch-group hf-swatch-group--pill"
						     data-attr-key="<?php echo esc_attr( $group['attr_key'] ); ?>"
						     role="radiogroup"
						     aria-label="<?php echo esc_attr( $group['label'] ); ?>">
							<?php foreach ( $group['items'] as $item ) : ?>
								<?php $is_active = ( $group['default'] === $item['slug'] ); ?>
								<button type="button"
								        class="hf-swatch hf-swatch-pill <?php echo $is_active ? 'is-selected' : ''; ?>"
								        data-attr-key="<?php echo esc_attr( $group['attr_key'] ); ?>"
								        data-value="<?php echo esc_attr( $item['slug'] ); ?>"
								        aria-checked="<?php echo $is_active ? 'true' : 'false'; ?>"
								        role="radio">
									<?php echo esc_html( $item['label'] ); ?>
								</button>
							<?php endforeach; ?>
						</div>
					<?php endforeach; ?>
				</div>
			<?php endif; ?>
		</div>
	</article>
	<?php
}

/**
 * --------------------------------------------------------------------------
 * 5. HEADER CART, HEADER SEARCH & FRAGMENT SYNCHRONIZATION
 * --------------------------------------------------------------------------
 */

add_shortcode( 'hf_header_cart', 'hf_shortcode_header_cart' );
function hf_shortcode_header_cart() {
	if ( ! class_exists( 'WooCommerce' ) ) {
		return '';
	}

	$count    = WC()->cart ? (int) WC()->cart->get_cart_contents_count() : 0;
	$cart_url = function_exists( 'wc_get_cart_url' ) ? wc_get_cart_url() : '#';
	$cart_map = hf_get_cart_quantity_map();

	ob_start();
	?>
	<div class="hf-header-cart-wrap">
		<a href="<?php echo esc_url( $cart_url ); ?>"
		   class="hf-header-cart hf-icon-btn"
		   aria-label="<?php esc_attr_e( 'View shopping bag', 'hound-and-friends' ); ?>">
			<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
				<path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/>
				<line x1="3" y1="6" x2="21" y2="6"/>
				<path d="M16 10a4 4 0 0 1-8 0"/>
			</svg>
			<span class="hf-cart-count" data-count="<?php echo esc_attr( $count ); ?>" data-cart-map="<?php echo esc_attr( wp_json_encode( $cart_map ) ); ?>"><?php echo esc_html( $count ); ?></span>
		</a>
	</div>
	<?php
	return ob_get_clean();
}

/**
 * Header Search trigger + live AJAX product search popover.
 */
add_shortcode( 'hf_header_search', 'hf_shortcode_header_search' );
function hf_shortcode_header_search() {
	$shop_url = function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'shop' ) : home_url( '/' );
	ob_start();
	?>
	<div class="hf-header-search-wrap">
		<button type="button"
		        class="hf-search-toggle hf-icon-btn"
		        aria-expanded="false"
		        aria-label="<?php esc_attr_e( 'Search accessories', 'hound-and-friends' ); ?>">
			<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
				<circle cx="11" cy="11" r="8"/>
				<line x1="21" y1="21" x2="16.65" y2="16.65"/>
			</svg>
		</button>
		<div class="hf-search-popover" hidden>
			<form role="search" method="get" action="<?php echo esc_url( $shop_url ); ?>" class="hf-search-form">
				<input type="search"
				       name="s"
				       class="hf-search-input"
				       placeholder="<?php esc_attr_e( 'Search bow ties, harnesses, leashes...', 'hound-and-friends' ); ?>"
				       autocomplete="off" />
				<input type="hidden" name="post_type" value="product" />
			</form>
			<div class="hf-search-results"></div>
		</div>
	</div>
	<?php
	return ob_get_clean();
}

/**
 * Header Account link icon.
 */
add_shortcode( 'hf_header_account', 'hf_shortcode_header_account' );
function hf_shortcode_header_account() {
	$account_url = function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'myaccount' ) : wp_login_url();
	ob_start();
	?>
	<a href="<?php echo esc_url( $account_url ); ?>"
	   class="hf-header-account hf-icon-btn"
	   aria-label="<?php esc_attr_e( 'My Account', 'hound-and-friends' ); ?>">
		<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
			<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
			<circle cx="12" cy="7" r="4"/>
		</svg>
	</a>
	<?php
	return ob_get_clean();
}

/**
 * Newsletter form shortcode (used in Newsletter banner or fallback if Elementor Form is swapped).
 */
add_shortcode( 'hf_newsletter_form', 'hf_shortcode_newsletter_form' );
function hf_shortcode_newsletter_form() {
	ob_start();
	?>
	<form class="hf-newsletter-form" method="post" novalidate>
		<div class="hf-newsletter-pill">
			<label for="hf-newsletter-email" class="screen-reader-text"><?php esc_html_e( 'Email address', 'hound-and-friends' ); ?></label>
			<input id="hf-newsletter-email"
			       type="email"
			       name="email"
			       required
			       placeholder="<?php esc_attr_e( 'Your email address', 'hound-and-friends' ); ?>" />
			<button type="submit" class="hf-newsletter-submit">
				<span><?php esc_html_e( 'Subscribe', 'hound-and-friends' ); ?></span>
				<svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
					<path d="M3.5 8H12.5M12.5 8L8.5 4M12.5 8L8.5 12" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
				</svg>
			</button>
		</div>
		<div class="hf-newsletter-feedback" role="status" aria-live="polite"></div>
	</form>
	<?php
	return ob_get_clean();
}

/**
 * Keep WooCommerce cart fragments synchronized on every add/remove across all pages.
 */
add_filter( 'woocommerce_add_to_cart_fragments', 'hf_woocommerce_cart_fragments' );
function hf_woocommerce_cart_fragments( $fragments ) {
	if ( ! WC()->cart ) {
		return $fragments;
	}

	$count    = (int) WC()->cart->get_cart_contents_count();
	$cart_map = hf_get_cart_quantity_map();
	ob_start();
	?>
	<span class="hf-cart-count" data-count="<?php echo esc_attr( $count ); ?>" data-cart-map="<?php echo esc_attr( wp_json_encode( $cart_map ) ); ?>"><?php echo esc_html( $count ); ?></span>
	<?php
	$fragments['span.hf-cart-count'] = ob_get_clean();

	return $fragments;
}

/**
 * Helper: map active cart items by "product_id" and "product_id:variation_id".
 */
function hf_get_cart_quantity_map() {
	$map = array();
	if ( ! class_exists( 'WooCommerce' ) || ! WC()->cart ) {
		return $map;
	}

	foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
		$pid = absint( $cart_item['product_id'] );
		$vid = absint( $cart_item['variation_id'] );
		$qty = absint( $cart_item['quantity'] );

		$lookup = $vid > 0 ? $pid . ':' . $vid : (string) $pid;
		if ( ! isset( $map[ $lookup ] ) ) {
			$map[ $lookup ] = array(
				'key' => $cart_item_key,
				'qty' => 0,
			);
		}
		$map[ $lookup ]['qty'] += $qty;
	}

	return $map;
}

/**
 * --------------------------------------------------------------------------
 * 6. AJAX ENDPOINTS (ADD TO CART, UPDATE QTY, LIVE SEARCH, NEWSLETTER)
 * --------------------------------------------------------------------------
 */

add_action( 'wp_ajax_hf_add_to_cart', 'hf_ajax_add_to_cart' );
add_action( 'wp_ajax_nopriv_hf_add_to_cart', 'hf_ajax_add_to_cart' );
function hf_ajax_add_to_cart() {
	check_ajax_referer( 'hf_store_nonce', 'nonce' );

	if ( ! class_exists( 'WooCommerce' ) || ! WC()->cart ) {
		wp_send_json_error( array( 'message' => __( 'WooCommerce cart is unavailable.', 'hound-and-friends' ) ), 400 );
	}

	$product_id   = isset( $_POST['product_id'] ) ? absint( wp_unslash( $_POST['product_id'] ) ) : 0;
	$variation_id = isset( $_POST['variation_id'] ) ? absint( wp_unslash( $_POST['variation_id'] ) ) : 0;
	$quantity     = isset( $_POST['quantity'] ) ? max( 1, absint( wp_unslash( $_POST['quantity'] ) ) ) : 1;
	$attributes   = array();

	if ( isset( $_POST['attributes'] ) && is_array( $_POST['attributes'] ) ) {
		foreach ( wp_unslash( $_POST['attributes'] ) as $k => $v ) {
			$attributes[ sanitize_text_field( $k ) ] = sanitize_text_field( $v );
		}
	}

	$product = wc_get_product( $product_id );
	if ( ! $product ) {
		wp_send_json_error( array( 'message' => __( 'Product not found.', 'hound-and-friends' ) ), 404 );
	}

	if ( $product->is_type( 'variable' ) && $variation_id <= 0 ) {
		wp_send_json_error( array( 'message' => __( 'Please select all required options.', 'hound-and-friends' ) ), 422 );
	}

	$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $attributes );
	if ( ! $passed_validation ) {
		wp_send_json_error( array( 'message' => __( 'This selection cannot be added to the cart.', 'hound-and-friends' ) ), 422 );
	}

	$cart_item_key = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $attributes );
	if ( ! $cart_item_key ) {
		wp_send_json_error( array( 'message' => __( 'Unable to add item to bag.', 'hound-and-friends' ) ), 400 );
	}

	do_action( 'woocommerce_ajax_added_to_cart', $product_id );
	WC()->cart->calculate_totals();

	$cart_map = hf_get_cart_quantity_map();
	$lookup   = $variation_id > 0 ? $product_id . ':' . $variation_id : (string) $product_id;
	$new_qty  = isset( $cart_map[ $lookup ] ) ? $cart_map[ $lookup ]['qty'] : $quantity;

	wp_send_json_success(
		array(
			'cart_item_key' => $cart_item_key,
			'qty'           => $new_qty,
			'cart_count'    => (int) WC()->cart->get_cart_contents_count(),
			'cart_map'      => $cart_map,
			'fragments'     => apply_filters( 'woocommerce_add_to_cart_fragments', array() ),
		)
	);
}

add_action( 'wp_ajax_hf_update_cart_qty', 'hf_ajax_update_cart_qty' );
add_action( 'wp_ajax_nopriv_hf_update_cart_qty', 'hf_ajax_update_cart_qty' );
function hf_ajax_update_cart_qty() {
	check_ajax_referer( 'hf_store_nonce', 'nonce' );

	if ( ! class_exists( 'WooCommerce' ) || ! WC()->cart ) {
		wp_send_json_error( array( 'message' => __( 'WooCommerce cart is unavailable.', 'hound-and-friends' ) ), 400 );
	}

	$cart_item_key = isset( $_POST['cart_item_key'] ) ? sanitize_text_field( wp_unslash( $_POST['cart_item_key'] ) ) : '';
	$product_id    = isset( $_POST['product_id'] ) ? absint( wp_unslash( $_POST['product_id'] ) ) : 0;
	$variation_id  = isset( $_POST['variation_id'] ) ? absint( wp_unslash( $_POST['variation_id'] ) ) : 0;
	$quantity      = isset( $_POST['quantity'] ) ? max( 0, absint( wp_unslash( $_POST['quantity'] ) ) ) : 0;

	if ( empty( $cart_item_key ) && $product_id > 0 ) {
		$cart_map = hf_get_cart_quantity_map();
		$lookup   = $variation_id > 0 ? $product_id . ':' . $variation_id : (string) $product_id;
		if ( isset( $cart_map[ $lookup ] ) ) {
			$cart_item_key = $cart_map[ $lookup ]['key'];
		}
	}

	if ( empty( $cart_item_key ) || ! WC()->cart->get_cart_item( $cart_item_key ) ) {
		wp_send_json_error( array( 'message' => __( 'Cart item not found.', 'hound-and-friends' ) ), 404 );
	}

	if ( 0 === $quantity ) {
		WC()->cart->remove_cart_item( $cart_item_key );
	} else {
		WC()->cart->set_quantity( $cart_item_key, $quantity, true );
	}

	WC()->cart->calculate_totals();

	wp_send_json_success(
		array(
			'cart_item_key' => $quantity > 0 ? $cart_item_key : '',
			'qty'           => $quantity,
			'cart_count'    => (int) WC()->cart->get_cart_contents_count(),
			'cart_map'      => hf_get_cart_quantity_map(),
			'fragments'     => apply_filters( 'woocommerce_add_to_cart_fragments', array() ),
		)
	);
}

add_action( 'wp_ajax_hf_live_search', 'hf_ajax_live_search' );
add_action( 'wp_ajax_nopriv_hf_live_search', 'hf_ajax_live_search' );
function hf_ajax_live_search() {
	check_ajax_referer( 'hf_store_nonce', 'nonce' );

	$term = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : '';
	if ( strlen( $term ) < 2 || ! class_exists( 'WooCommerce' ) ) {
		wp_send_json_success( array( 'items' => array() ) );
	}

	$products = wc_get_products(
		array(
			'status' => 'publish',
			'limit'  => 5,
			's'      => $term,
		)
	);

	$items = array();
	foreach ( $products as $p ) {
		$img_id = $p->get_image_id();
		$items[] = array(
			'id'    => $p->get_id(),
			'title' => $p->get_name(),
			'url'   => $p->get_permalink(),
			'price' => wp_strip_all_tags( $p->get_price_html() ),
			'image' => $img_id ? wp_get_attachment_image_url( $img_id, 'thumbnail' ) : wc_placeholder_img_src( 'thumbnail' ),
		);
	}

	wp_send_json_success( array( 'items' => $items ) );
}

add_action( 'wp_ajax_hf_newsletter_subscribe', 'hf_ajax_newsletter_subscribe' );
add_action( 'wp_ajax_nopriv_hf_newsletter_subscribe', 'hf_ajax_newsletter_subscribe' );
function hf_ajax_newsletter_subscribe() {
	check_ajax_referer( 'hf_store_nonce', 'nonce' );

	$email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
	if ( ! is_email( $email ) ) {
		wp_send_json_error( array( 'message' => __( 'Please enter a valid email address.', 'hound-and-friends' ) ), 422 );
	}

	$subscribers = get_option( 'hf_newsletter_subscribers', array() );
	if ( ! is_array( $subscribers ) ) {
		$subscribers = array();
	}

	if ( ! in_array( $email, $subscribers, true ) ) {
		$subscribers[] = $email;
		update_option( 'hf_newsletter_subscribers', $subscribers, false );
		do_action( 'hf_newsletter_subscribed', $email );
	}

	wp_send_json_success(
		array(
			'message' => __( 'Welcome to the pack! You are subscribed.', 'hound-and-friends' ),
		)
	);
}


/**
 * Enqueue parent theme stylesheet (safe for Hello Elementor, WoodMart Child, etc.)
 * and Google Fonts (Plus Jakarta Sans, DM Sans, Caveat).
 */
add_action( 'wp_enqueue_scripts', 'hf_enqueue_theme_styles_and_fonts', 20 );
function hf_enqueue_theme_styles_and_fonts() {
	$parent_style = 'parent-style';
	$theme        = wp_get_theme();
	$parent       = $theme->parent();

	if ( $parent ) {
		wp_enqueue_style(
			$parent_style,
			get_template_directory_uri() . '/style.css',
			array(),
			$parent->get( 'Version' )
		);
		wp_enqueue_style(
			'hf-child-style',
			get_stylesheet_uri(),
			array( $parent_style ),
			HF_CHILD_VERSION
		);
	}

	// Ensure brand fonts are always available globally.
	wp_enqueue_style(
		'hf-google-fonts',
		'https://fonts.googleapis.com/css2?family=Caveat:wght@500;600;700&family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;1,9..40,400&family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap',
		array(),
		null
	);
}
