HEX
Server: nginx/1.24.0
System: Linux 0c1023d6c65e 6.8.0-137-generic #137-Ubuntu SMP PREEMPT_DYNAMIC Fri Jul 17 20:28:23 UTC 2026 x86_64
User: root (0)
PHP: 8.3.33
Disabled: NONE
Upload Files
File: /var/www/html/wp-content/mu-plugins/ethnic-case-studies-architecture.php
<?php
/**
 * Plugin Name: Ethnic Case Studies Architecture
 * Description: Refactors portfolio items into the public Case Studies architecture.
 * Version: 1.0.0
 */

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

if ( ! defined( 'ETHNIC_CASE_STUDIES_VERSION' ) ) {
	define( 'ETHNIC_CASE_STUDIES_VERSION', '20260421.1' );
}

if ( ! defined( 'ETHNIC_CASE_STUDIES_POST_TYPE' ) ) {
	define( 'ETHNIC_CASE_STUDIES_POST_TYPE', 'thegem_pf_item' );
}

if ( ! defined( 'ETHNIC_CASE_STUDIES_LOGO_POST_TYPE' ) ) {
	define( 'ETHNIC_CASE_STUDIES_LOGO_POST_TYPE', 'ethnic_case_logo' );
}

if ( ! function_exists( 'ethnic_case_studies_archive_slug' ) ) {
	function ethnic_case_studies_archive_slug() {
		return 'case-studies';
	}
}

if ( ! function_exists( 'ethnic_case_studies_app_archive_variant' ) ) {
	function ethnic_case_studies_app_archive_variant() {
		return 'app-development';
	}
}

if ( ! function_exists( 'ethnic_case_studies_archive_variant_slug' ) ) {
	function ethnic_case_studies_archive_variant_slug( $variant = '' ) {
		$variant = sanitize_title( (string) $variant );

		if ( '' !== $variant ) {
			return trim( ethnic_case_studies_archive_slug(), '/' ) . '/' . trim( $variant, '/' );
		}

		return trim( ethnic_case_studies_archive_slug(), '/' );
	}
}

if ( ! function_exists( 'ethnic_case_studies_current_archive_variant' ) ) {
	function ethnic_case_studies_current_archive_variant() {
		$variant = get_query_var( 'ethnic_case_study_archive_variant' );
		$variant = is_scalar( $variant ) ? sanitize_title( (string) $variant ) : '';

		return '' !== $variant ? $variant : '';
	}
}

if ( ! function_exists( 'ethnic_case_studies_request_segments' ) ) {
	function ethnic_case_studies_request_segments( $request_path = '' ) {
		$request_path = is_scalar( $request_path ) ? (string) $request_path : '';

		if ( '' === $request_path && isset( $_SERVER['REQUEST_URI'] ) ) {
			$request_path = (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH );
		}

		$home_path = (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH );

		if ( '' !== $home_path && '/' !== $home_path && 0 === strpos( $request_path, $home_path ) ) {
			$request_path = substr( $request_path, strlen( $home_path ) );
		}

		$request_path = trim( (string) $request_path, '/' );

		if ( '' === $request_path ) {
			return array();
		}

		return array_values(
			array_filter(
				array_map(
					static function ( $segment ) {
						return sanitize_title( (string) $segment );
					},
					explode( '/', $request_path )
				)
			)
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_is_app_archive_variant' ) ) {
	function ethnic_case_studies_is_app_archive_variant( $variant = '' ) {
		if ( '' === $variant ) {
			$variant = ethnic_case_studies_current_archive_variant();
		}

		return ethnic_case_studies_app_archive_variant() === sanitize_title( (string) $variant );
	}
}

if ( ! function_exists( 'ethnic_case_studies_resolve_archive_variant_slug' ) ) {
	function ethnic_case_studies_resolve_archive_variant_slug( $variant = '' ) {
		$variant = sanitize_title( (string) $variant );

		if ( '' === $variant ) {
			return '';
		}

		if ( ethnic_case_studies_is_app_archive_variant( $variant ) ) {
			return $variant;
		}

		$category_term = ethnic_case_studies_category_term_by_slug( $variant );

		return $category_term instanceof WP_Term ? $category_term->slug : '';
	}
}

if ( ! function_exists( 'ethnic_case_studies_match_archive_request' ) ) {
	function ethnic_case_studies_match_archive_request( $request_path = '' ) {
		$request_segments = ethnic_case_studies_request_segments( $request_path );
		$archive_base     = sanitize_title( ethnic_case_studies_archive_slug() );

		if ( count( $request_segments ) < 2 || $archive_base !== $request_segments[0] ) {
			return array();
		}

		$variant = ethnic_case_studies_resolve_archive_variant_slug( $request_segments[1] );

		if ( '' === $variant ) {
			return array();
		}

		if ( isset( $request_segments[2] ) && 'page' !== $request_segments[2] ) {
			return array();
		}

		$paged = 1;

		if ( isset( $request_segments[2], $request_segments[3] ) && 'page' === $request_segments[2] && ctype_digit( $request_segments[3] ) ) {
			$paged = max( 1, (int) $request_segments[3] );
		}

		if ( isset( $request_segments[4] ) ) {
			return array();
		}

		return array(
			'variant' => $variant,
			'paged'   => $paged,
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_match_single_request' ) ) {
	function ethnic_case_studies_match_single_request( $request_path = '' ) {
		$request_segments = ethnic_case_studies_request_segments( $request_path );
		$archive_base     = sanitize_title( ethnic_case_studies_archive_slug() );

		if ( 3 !== count( $request_segments ) || $archive_base !== $request_segments[0] ) {
			return array();
		}

		$variant = ethnic_case_studies_resolve_archive_variant_slug( $request_segments[1] );

		if ( '' === $variant ) {
			return array();
		}

		if ( 'page' === $request_segments[2] ) {
			return array();
		}

		return array(
			'variant' => $variant,
			'name'    => sanitize_title_for_query( $request_segments[2] ),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_archive_url' ) ) {
	function ethnic_case_studies_archive_url( $filters = array(), $page = 1, $variant = '' ) {
		$url = home_url( '/' . trim( ethnic_case_studies_archive_variant_slug( $variant ), '/' ) . '/' );

		if ( $page > 1 ) {
			$url = trailingslashit( $url ) . user_trailingslashit( 'page/' . absint( $page ) );
		}

		$query_args = ethnic_case_studies_normalize_filter_map( $filters );

		if ( ! empty( $query_args ) ) {
			$url = add_query_arg( $query_args, $url );
		}

		return $url;
	}
}

if ( ! function_exists( 'ethnic_case_studies_contact_url' ) ) {
	function ethnic_case_studies_contact_url( $args = array() ) {
		return ethnic_consultation_route_contact_url( $args, home_url( '/contact-us/' ) );
	}
}

if ( ! function_exists( 'ethnic_case_studies_taxonomies' ) ) {
	function ethnic_case_studies_taxonomies() {
		return array(
			'category' => 'ethnic_case_study_category',
			'service'  => 'ethnic_case_study_service',
			'platform' => 'ethnic_case_study_platform',
			'industry' => 'ethnic_case_study_industry',
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_featured_meta_key' ) ) {
	function ethnic_case_studies_featured_meta_key() {
		return 'ethnic_case_study_featured';
	}
}

if ( ! function_exists( 'ethnic_case_studies_logo_selection_meta_key' ) ) {
	function ethnic_case_studies_logo_selection_meta_key() {
		return 'ethnic_case_study_logo_ids';
	}
}

if ( ! function_exists( 'ethnic_case_studies_logo_image_id_meta_key' ) ) {
	function ethnic_case_studies_logo_image_id_meta_key() {
		return 'ethnic_case_study_logo_image_id';
	}
}

if ( ! function_exists( 'ethnic_case_studies_logo_image_url_meta_key' ) ) {
	function ethnic_case_studies_logo_image_url_meta_key() {
		return 'ethnic_case_study_logo_image_url';
	}
}

if ( ! function_exists( 'ethnic_case_studies_service_page_case_study_ids_meta_key' ) ) {
	function ethnic_case_studies_service_page_case_study_ids_meta_key() {
		return 'ethnic_service_page_case_study_ids';
	}
}

if ( ! function_exists( 'ethnic_case_studies_service_page_selection_limit' ) ) {
	function ethnic_case_studies_service_page_selection_limit() {
		return 6;
	}
}

if ( ! function_exists( 'ethnic_case_studies_is_service_page' ) ) {
	function ethnic_case_studies_is_service_page( $post = null ) {
		$post = get_post( $post );

		if ( ! ( $post instanceof WP_Post ) || 'page' !== $post->post_type ) {
			return false;
		}

		$page_uri = trim( (string) get_page_uri( $post->ID ), '/' );

		return '' !== $page_uri && 0 === strpos( $page_uri, 'services/' );
	}
}

if ( ! defined( 'ETHNIC_CASE_STUDIES_HEADER_TEMPLATE_ID' ) ) {
	define( 'ETHNIC_CASE_STUDIES_HEADER_TEMPLATE_ID', 27277 );
}

if ( ! function_exists( 'ethnic_case_studies_should_force_builder_header' ) ) {
	function ethnic_case_studies_should_force_builder_header( $post_id = 0, $type = false ) {
		if ( is_admin() ) {
			return false;
		}

		if ( ! function_exists( 'is_singular' ) || ! is_singular( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			return false;
		}

		if ( $type ) {
			return false;
		}

		$queried_id = function_exists( 'get_queried_object_id' ) ? (int) get_queried_object_id() : 0;
		$post_id    = (int) $post_id;

		if ( $queried_id < 1 || $post_id < 1 || $queried_id !== $post_id ) {
			return false;
		}

		return ETHNIC_CASE_STUDIES_POST_TYPE === get_post_type( $post_id );
	}
}

if ( ! function_exists( 'ethnic_case_studies_override_page_settings' ) ) {
	function ethnic_case_studies_override_page_settings( $settings, $post_id = 0, $item_data = array(), $type = false ) {
		if ( ! is_array( $settings ) || ! ethnic_case_studies_should_force_builder_header( $post_id, $type ) ) {
			return $settings;
		}

		$header_builder = function_exists( 'thegem_get_option' ) ? (int) thegem_get_option( 'header_builder' ) : 0;
		$sticky_builder = function_exists( 'thegem_get_option' ) ? (int) thegem_get_option( 'header_builder_sticky' ) : 0;

		if ( $header_builder < 1 ) {
			$header_builder = ETHNIC_CASE_STUDIES_HEADER_TEMPLATE_ID;
		}

		if ( $sticky_builder < 1 ) {
			$sticky_builder = $header_builder;
		}

		if ( $header_builder < 1 || ! get_post( $header_builder ) ) {
			return $settings;
		}

		$settings['effects_hide_header']               = 0;
		$settings['header_source']                     = 'builder';
		$settings['header_builder']                    = $header_builder;
		$settings['header_builder_sticky']             = $sticky_builder;
		$settings['header_builder_sticky_desktop']     = 1;
		$settings['header_builder_sticky_mobile']      = 1;
		$settings['header_builder_sticky_hide_desktop'] = 0;
		$settings['header_builder_sticky_hide_mobile'] = 0;
		$settings['header_builder_sticky_opacity']     = 100;
		$settings['header_transparent']                = 0;
		$settings['header_transparent_mobile']         = 0;
		$settings['header_opacity']                    = 100;
		$settings['header_menu_logo_light']            = 0;
		$settings['menu_show']                         = 1;

		return $settings;
	}
}

if ( ! function_exists( 'ethnic_case_studies_old_archive_page_id' ) ) {
	function ethnic_case_studies_old_archive_page_id() {
		static $page_id = null;

		if ( null === $page_id ) {
			$page    = get_page_by_path( 'our-works' );
			$page_id = $page instanceof WP_Post ? (int) $page->ID : 0;
		}

		return $page_id;
	}
}

if ( ! function_exists( 'ethnic_case_studies_text' ) ) {
	function ethnic_case_studies_text( $value, $fallback = '' ) {
		$value = is_scalar( $value ) ? trim( wp_strip_all_tags( (string) $value ) ) : '';

		return '' !== $value ? $value : $fallback;
	}
}

if ( ! function_exists( 'ethnic_case_studies_is_placeholder' ) ) {
	function ethnic_case_studies_is_placeholder( $text ) {
		$text = strtolower( ethnic_case_studies_text( $text ) );

		if ( '' === $text ) {
			return true;
		}

		foreach ( array( '(demo)', 'demo project', 'demo portfolio', 'sample project', 'placeholder', 'lorem ipsum' ) as $token ) {
			if ( false !== strpos( $text, $token ) ) {
				return true;
			}
		}

		return false;
	}
}

if ( ! function_exists( 'ethnic_case_studies_split_list' ) ) {
	function ethnic_case_studies_split_list( $value, $limit = 0 ) {
		$value = ethnic_case_studies_text( $value );

		if ( '' === $value || ethnic_case_studies_is_placeholder( $value ) ) {
			return array();
		}

		$items = preg_split( '/\s*[,;|]\s*/', $value );
		$items = is_array( $items ) ? $items : array();
		$items = array_values(
			array_filter(
				array_map( 'trim', $items ),
				static function ( $item ) {
					return '' !== $item;
				}
			)
		);
		$items = array_values( array_unique( $items ) );

		if ( $limit > 0 ) {
			$items = array_slice( $items, 0, $limit );
		}

		return $items;
	}
}

if ( ! function_exists( 'ethnic_case_studies_trim_text' ) ) {
	function ethnic_case_studies_trim_text( $text, $words = 26, $fallback = '' ) {
		$text = ethnic_case_studies_text( $text, $fallback );

		if ( '' === $text ) {
			return '';
		}

		return wp_trim_words( $text, max( 10, (int) $words ), '…' );
	}
}

if ( ! function_exists( 'ethnic_case_studies_normalize_requested_slugs' ) ) {
	function ethnic_case_studies_normalize_requested_slugs( $value ) {
		$items = array();

		if ( is_array( $value ) ) {
			foreach ( $value as $part ) {
				$items = array_merge( $items, ethnic_case_studies_normalize_requested_slugs( $part ) );
			}
		} elseif ( is_scalar( $value ) ) {
			$items = preg_split( '/\s*,\s*/', (string) $value );
			$items = is_array( $items ) ? $items : array();
		}

		$items = array_values(
			array_filter(
				array_map(
					static function ( $item ) {
						return sanitize_title( (string) $item );
					},
					$items
				)
			)
		);

		sort( $items );

		return array_values( array_unique( $items ) );
	}
}

if ( ! function_exists( 'ethnic_case_studies_selected_filters' ) ) {
	function ethnic_case_studies_selected_filters() {
		static $filters = null;

		if ( null !== $filters ) {
			return $filters;
		}

		$filters = array(
			'service'  => array(),
			'platform' => array(),
			'industry' => array(),
		);

		foreach ( array_keys( $filters ) as $key ) {
			$value = array();

			if ( isset( $_GET[ $key ] ) ) {
				$value = ethnic_case_studies_normalize_requested_slugs( wp_unslash( $_GET[ $key ] ) );
			}

			if ( empty( $value ) && isset( $_GET[ $key . '_selector' ] ) ) {
				$value = ethnic_case_studies_normalize_requested_slugs( wp_unslash( $_GET[ $key . '_selector' ] ) );
			}

			$filters[ $key ] = $value;
		}

		return $filters;
	}
}

if ( ! function_exists( 'ethnic_case_studies_normalize_filter_map' ) ) {
	function ethnic_case_studies_normalize_filter_map( $filters ) {
		$normalized = array();

		foreach ( array( 'service', 'platform', 'industry' ) as $key ) {
			$slugs = array();

			if ( isset( $filters[ $key ] ) ) {
				$slugs = ethnic_case_studies_normalize_requested_slugs( $filters[ $key ] );
			}

			if ( ! empty( $slugs ) ) {
				$normalized[ $key ] = implode( ',', $slugs );
			}
		}

		return $normalized;
	}
}

if ( ! function_exists( 'ethnic_case_studies_normalized_archive_url_from_request' ) ) {
	function ethnic_case_studies_normalized_archive_url_from_request() {
		$variant = ethnic_case_studies_current_archive_variant();
		$filters = ethnic_case_studies_is_app_archive_variant( $variant ) ? array() : ethnic_case_studies_selected_filters();

		return ethnic_case_studies_archive_url(
			$filters,
			max( 1, (int) get_query_var( 'paged' ) ),
			$variant
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_filter_definitions' ) ) {
	function ethnic_case_studies_filter_definitions() {
		$taxonomies = ethnic_case_studies_taxonomies();

		return array(
			'service'  => array(
				'label'    => 'Service',
				'taxonomy' => $taxonomies['service'],
			),
			'platform' => array(
				'label'    => 'Platform',
				'taxonomy' => $taxonomies['platform'],
			),
			'industry' => array(
				'label'    => 'Industry',
				'taxonomy' => $taxonomies['industry'],
			),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_cover_image' ) ) {
	function ethnic_case_studies_cover_image( $post_id, $size = 'large' ) {
		$post_id      = (int) $post_id;
		$thumbnail_id = (int) get_post_thumbnail_id( $post_id );
		$image_url    = $thumbnail_id ? wp_get_attachment_image_url( $thumbnail_id, $size ) : '';
		$image_alt    = $thumbnail_id ? ethnic_case_studies_text( get_post_meta( $thumbnail_id, '_wp_attachment_image_alt', true ) ) : '';

		if ( '' === $image_alt ) {
			$image_alt = ethnic_case_studies_text( get_the_title( $post_id ) );
		}

		return array(
			'url' => $image_url,
			'alt' => $image_alt,
			'id'  => $thumbnail_id,
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_is_demo_post' ) ) {
	function ethnic_case_studies_is_demo_post( $post ) {
		$post = get_post( $post );

		if ( ! ( $post instanceof WP_Post ) ) {
			return true;
		}

		$haystack = strtolower(
			implode(
				' ',
				array_filter(
					array(
						ethnic_case_studies_text( $post->post_title ),
						ethnic_case_studies_text( $post->post_excerpt ),
						ethnic_case_studies_text( $post->post_content ),
						ethnic_case_studies_text( get_post_meta( $post->ID, '_thegem_cf_services', true ) ),
						ethnic_case_studies_text( get_post_meta( $post->ID, '_thegem_cf_client', true ) ),
					)
				)
			)
		);

		if ( '' === $haystack ) {
			return false;
		}

		return false !== strpos( $haystack, '(demo)' )
			|| false !== strpos( $haystack, 'demo project' )
			|| false !== strpos( $haystack, 'demo portfolio' )
			|| false !== strpos( $haystack, 'placeholder' )
			|| false !== strpos( $haystack, 'sample project' );
	}
}

if ( ! function_exists( 'ethnic_case_studies_legacy_term_maps' ) ) {
	function ethnic_case_studies_legacy_term_maps() {
		return array(
			'industry' => array(
				'retail'                   => 'Retail',
				'retail-ecommerce'         => 'Retail & eCommerce',
				'ecommerce'                => 'Retail & eCommerce',
				'healthcare'               => 'Healthcare',
				'fintech'                  => 'Fintech',
				'logistics'                => 'Logistics',
				'logistics-supply-chain'   => 'Logistics & Supply Chain',
				'logistics-supplychain'    => 'Logistics & Supply Chain',
				'education'                => 'Education',
				'real-estate'              => 'Real Estate',
				'manufacturing'            => 'Manufacturing',
				'gaming'                   => 'Gaming & Entertainment',
				'gaming-entertainment'     => 'Gaming & Entertainment',
				'travel-hospitality'       => 'Travel & Hospitality',
				'travel-hospitality-'      => 'Travel & Hospitality',
				'hospitality'              => 'Travel & Hospitality',
				'food-beverage'            => 'Food & Beverage',
			),
			'service'  => array(
				'app-development'         => 'App Development',
				'app-development-services'=> 'App Development',
				'mobile-app-development'  => 'Mobile App Development',
				'web-app-development'     => 'Web App Development',
				'android-app-development' => 'Android App Development',
				'ios-app-development'     => 'iOS App Development',
				'flutter-app-development' => 'Flutter App Development',
				'react-native'            => 'React Native App Development',
				'ecommerce-development'   => 'eCommerce Development',
				'magento-development'     => 'Magento Development',
				'shopify-development'     => 'Shopify Development',
				'headless-commerce'       => 'Headless Commerce',
				'headless-commerce-development' => 'Headless Commerce',
				'ai-ml'                   => 'AI / ML',
				'devops'                  => 'DevOps',
				'blockchain'              => 'Blockchain',
				'game-development'        => 'Game Development',
			),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_title_case_from_slug' ) ) {
	function ethnic_case_studies_title_case_from_slug( $slug ) {
		$slug = trim( str_replace( array( '-', '_' ), ' ', (string) $slug ) );
		$slug = preg_replace( '/\s+/', ' ', $slug );

		return '' !== $slug ? ucwords( $slug ) : '';
	}
}

if ( ! function_exists( 'ethnic_case_studies_infer_industry_terms' ) ) {
	function ethnic_case_studies_infer_industry_terms( $post_id ) {
		$terms      = get_the_terms( $post_id, 'thegem_portfolios' );
		$maps       = ethnic_case_studies_legacy_term_maps();
		$industries = array();

		if ( is_array( $terms ) ) {
			foreach ( $terms as $term ) {
				$slug = sanitize_title( $term->slug );

				if ( isset( $maps['industry'][ $slug ] ) ) {
					$industries[] = $maps['industry'][ $slug ];
					continue;
				}

				if ( isset( $maps['service'][ $slug ] ) ) {
					continue;
				}

				$name = ethnic_case_studies_text( $term->name );

				if ( '' !== $name && ! ethnic_case_studies_is_placeholder( $name ) ) {
					$industries[] = $name;
				}
			}
		}

		if ( empty( $industries ) ) {
			$text = strtolower(
				implode(
					' ',
					array(
						ethnic_case_studies_text( get_the_title( $post_id ) ),
						ethnic_case_studies_text( get_the_excerpt( $post_id ) ),
						ethnic_case_studies_text( get_post_field( 'post_content', $post_id ) ),
					)
				)
			);

			foreach ( array(
				'Retail'                  => array( 'retail', 'ecommerce' ),
				'Healthcare'              => array( 'healthcare', 'health care', 'medical' ),
				'Fintech'                 => array( 'fintech', 'financial', 'banking' ),
				'Logistics'               => array( 'logistics', 'dispatch', 'supply chain', 'operations' ),
				'Education'               => array( 'education', 'learning', 'edtech' ),
				'Real Estate'             => array( 'real estate', 'property' ),
				'Manufacturing'           => array( 'manufacturing', 'factory' ),
				'Travel & Hospitality'    => array( 'travel', 'hospitality', 'hotel' ),
				'Food & Beverage'         => array( 'food', 'beverage', 'restaurant' ),
				'Gaming & Entertainment'  => array( 'gaming', 'entertainment', 'game' ),
			) as $industry => $keywords ) {
				foreach ( $keywords as $keyword ) {
					if ( false !== strpos( $text, $keyword ) ) {
						$industries[] = $industry;
						break;
					}
				}
			}
		}

		return array_values( array_unique( array_filter( $industries ) ) );
	}
}

if ( ! function_exists( 'ethnic_case_studies_infer_service_terms' ) ) {
	function ethnic_case_studies_infer_service_terms( $post_id ) {
		$service_meta = ethnic_case_studies_split_list( get_post_meta( $post_id, '_thegem_cf_services', true ) );

		if ( ! empty( $service_meta ) ) {
			return $service_meta;
		}

		$terms    = get_the_terms( $post_id, 'thegem_portfolios' );
		$maps     = ethnic_case_studies_legacy_term_maps();
		$services = array();

		if ( is_array( $terms ) ) {
			foreach ( $terms as $term ) {
				$slug = sanitize_title( $term->slug );

				if ( isset( $maps['service'][ $slug ] ) ) {
					$services[] = $maps['service'][ $slug ];
				}
			}
		}

		if ( empty( $services ) ) {
			$text = strtolower(
				implode(
					' ',
					array(
						ethnic_case_studies_text( get_the_title( $post_id ) ),
						ethnic_case_studies_text( get_the_excerpt( $post_id ) ),
						ethnic_case_studies_text( get_post_field( 'post_content', $post_id ) ),
					)
				)
			);

			foreach ( array(
				'App Development'          => array( 'app development', 'application development' ),
				'Mobile App Development'   => array( 'mobile app', 'mobile application' ),
				'Web App Development'      => array( 'web app', 'web application', 'portal', 'dashboard' ),
				'App Modernization'        => array( 'modernization', 'modernisation' ),
				'Workflow Platform'        => array( 'workflow platform', 'workflow', 'operations platform' ),
				'Digital Onboarding'       => array( 'onboarding', 'client portal' ),
				'eCommerce Development'    => array( 'ecommerce', 'shopify', 'magento', 'woocommerce' ),
				'Magento Development'      => array( 'magento', 'adobe commerce', 'hyva' ),
				'Shopify Development'      => array( 'shopify', 'shopify plus' ),
				'Headless Commerce'        => array( 'headless commerce', 'headless storefront', 'graphcommerce', 'composable commerce', 'next.js commerce', 'pwa storefront' ),
				'AI / ML'                  => array( 'ai', 'machine learning' ),
				'DevOps'                   => array( 'devops', 'observability', 'infrastructure' ),
				'Blockchain'               => array( 'blockchain', 'web3', 'smart contract', 'dapp' ),
				'Game Development'         => array( 'game development', 'gaming', 'unity game', 'multiplayer game' ),
			) as $service => $keywords ) {
				foreach ( $keywords as $keyword ) {
					if ( false !== strpos( $text, $keyword ) ) {
						$services[] = $service;
						break;
					}
				}
			}
		}

		return array_values( array_unique( array_filter( $services ) ) );
	}
}

if ( ! function_exists( 'ethnic_case_studies_infer_category_terms' ) ) {
	function ethnic_case_studies_infer_category_terms( $post_id ) {
		$text = strtolower(
			implode(
				' ',
				array(
					ethnic_case_studies_text( get_the_title( $post_id ) ),
					ethnic_case_studies_text( get_the_excerpt( $post_id ) ),
					ethnic_case_studies_text( get_post_field( 'post_content', $post_id ) ),
					implode( ' ', ethnic_case_studies_infer_service_terms( $post_id ) ),
					implode( ' ', ethnic_case_studies_infer_platform_terms( $post_id ) ),
				)
			)
		);

		$categories = array();

		if ( ethnic_case_studies_is_app_related_terms(
			ethnic_case_studies_infer_service_terms( $post_id ),
			ethnic_case_studies_infer_platform_terms( $post_id ),
			get_the_title( $post_id ),
			ethnic_case_studies_get_summary( $post_id )
		) ) {
			$categories[] = 'App Development';
		}

		foreach ( array(
			'Headless Commerce' => array( 'headless commerce', 'headless storefront', 'graphcommerce', 'composable commerce' ),
			'Magento'      => array( 'magento', 'adobe commerce', 'adobe-commerce' ),
			'Shopify'      => array( 'shopify' ),
			'WooCommerce'  => array( 'woocommerce', 'woo commerce' ),
			'Flutter'      => array( 'flutter' ),
			'React Native' => array( 'react native' ),
			'iOS'          => array( ' ios ', 'iphone', 'ipad', 'swift' ),
			'Android'      => array( ' android ', 'kotlin' ),
			'SaaS'         => array( ' saas ', 'software as a service' ),
		) as $category => $keywords ) {
			foreach ( $keywords as $keyword ) {
				if ( false !== strpos( ' ' . $text . ' ', $keyword ) ) {
					$categories[] = $category;
					break;
				}
			}
		}

		return array_values( array_unique( array_filter( $categories ) ) );
	}
}

if ( ! function_exists( 'ethnic_case_studies_infer_platform_terms' ) ) {
	function ethnic_case_studies_infer_platform_terms( $post_id ) {
		$text = strtolower(
			implode(
				' ',
				array(
					ethnic_case_studies_text( get_the_title( $post_id ) ),
					ethnic_case_studies_text( get_the_excerpt( $post_id ) ),
					ethnic_case_studies_text( get_post_field( 'post_content', $post_id ) ),
					ethnic_case_studies_text( get_post_meta( $post_id, '_thegem_cf_services', true ) ),
				)
			)
		);

		$platforms = array();

		foreach ( array(
			'Magento'          => array( 'magento', 'adobe commerce', 'hyva' ),
			'Adobe Commerce'   => array( 'adobe commerce', 'adobe-commerce' ),
			'Shopify'          => array( 'shopify', 'shopify plus' ),
			'WooCommerce'      => array( 'woocommerce', 'woo commerce' ),
			'Headless Commerce'=> array( 'headless commerce', 'headless storefront', 'graphcommerce', 'composable commerce', 'next.js commerce', 'pwa storefront' ),
			'iOS'             => array( ' ios ', 'iphone', 'ipad', 'swift' ),
			'Android'         => array( ' android ', 'kotlin' ),
			'Flutter'         => array( 'flutter' ),
			'React Native'    => array( 'react native' ),
			'Cross-Platform'  => array( 'cross-platform', 'cross platform', 'hybrid app' ),
			'Web App'         => array( 'web app', 'portal', 'dashboard', 'workflow platform', 'platform', 'saas', 'onboarding' ),
			'Mobile App'      => array( 'mobile', ' app ' ),
		) as $platform => $keywords ) {
			foreach ( $keywords as $keyword ) {
				if ( false !== strpos( ' ' . $text . ' ', $keyword ) ) {
					$platforms[] = $platform;
					break;
				}
			}
		}

		return array_values( array_unique( array_filter( $platforms ) ) );
	}
}

if ( ! function_exists( 'ethnic_case_studies_existing_term_names' ) ) {
	function ethnic_case_studies_existing_term_names( $post_id, $taxonomy ) {
		$terms = get_the_terms( $post_id, $taxonomy );

		if ( is_wp_error( $terms ) || ! is_array( $terms ) ) {
			return array();
		}

		return array_values(
			array_filter(
				array_map(
					static function ( $term ) {
						return $term instanceof WP_Term ? ethnic_case_studies_text( $term->name ) : '';
					},
					$terms
				)
			)
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_get_industry_terms' ) ) {
	function ethnic_case_studies_get_industry_terms( $post_id ) {
		$taxonomies = ethnic_case_studies_taxonomies();
		$terms      = ethnic_case_studies_existing_term_names( $post_id, $taxonomies['industry'] );

		return ! empty( $terms ) ? $terms : ethnic_case_studies_infer_industry_terms( $post_id );
	}
}

if ( ! function_exists( 'ethnic_case_studies_get_category_terms' ) ) {
	function ethnic_case_studies_get_category_terms( $post_id ) {
		$taxonomies = ethnic_case_studies_taxonomies();
		$terms      = ethnic_case_studies_existing_term_names( $post_id, $taxonomies['category'] );

		return ! empty( $terms ) ? $terms : ethnic_case_studies_infer_category_terms( $post_id );
	}
}

if ( ! function_exists( 'ethnic_case_studies_get_service_terms' ) ) {
	function ethnic_case_studies_get_service_terms( $post_id ) {
		$taxonomies = ethnic_case_studies_taxonomies();
		$terms      = ethnic_case_studies_existing_term_names( $post_id, $taxonomies['service'] );

		return ! empty( $terms ) ? $terms : ethnic_case_studies_infer_service_terms( $post_id );
	}
}

if ( ! function_exists( 'ethnic_case_studies_get_platform_terms' ) ) {
	function ethnic_case_studies_get_platform_terms( $post_id ) {
		$taxonomies = ethnic_case_studies_taxonomies();
		$terms      = ethnic_case_studies_existing_term_names( $post_id, $taxonomies['platform'] );

		return ! empty( $terms ) ? $terms : ethnic_case_studies_infer_platform_terms( $post_id );
	}
}

if ( ! function_exists( 'ethnic_case_studies_category_term_by_slug' ) ) {
	function ethnic_case_studies_category_term_by_slug( $slug ) {
		$slug       = sanitize_title( (string) $slug );
		$taxonomies = ethnic_case_studies_taxonomies();

		if ( '' === $slug ) {
			return null;
		}

		$term = get_term_by( 'slug', $slug, $taxonomies['category'] );

		return $term instanceof WP_Term ? $term : null;
	}
}

if ( ! function_exists( 'ethnic_case_studies_current_category_term' ) ) {
	function ethnic_case_studies_current_category_term() {
		static $term = false;

		if ( false !== $term ) {
			return $term instanceof WP_Term ? $term : null;
		}

		$term = ethnic_case_studies_category_term_by_slug( ethnic_case_studies_current_archive_variant() );

		return $term instanceof WP_Term ? $term : null;
	}
}

if ( ! function_exists( 'ethnic_case_studies_primary_category_term' ) ) {
	function ethnic_case_studies_primary_category_term( $post ) {
		$post       = get_post( $post );
		$taxonomies = ethnic_case_studies_taxonomies();

		if ( ! ( $post instanceof WP_Post ) ) {
			return null;
		}

		$terms = wp_get_object_terms(
			$post->ID,
			$taxonomies['category'],
			array(
				'orderby' => 'name',
				'order'   => 'ASC',
			)
		);

		if ( is_wp_error( $terms ) || empty( $terms ) ) {
			return null;
		}

		foreach ( $terms as $term ) {
			if ( $term instanceof WP_Term ) {
				return $term;
			}
		}

		return null;
	}
}

if ( ! function_exists( 'ethnic_case_studies_category_archive_url' ) ) {
	function ethnic_case_studies_category_archive_url( $term, $filters = array(), $page = 1 ) {
		$term = $term instanceof WP_Term ? $term : ethnic_case_studies_category_term_by_slug( $term );

		if ( ! ( $term instanceof WP_Term ) ) {
			return ethnic_case_studies_archive_url( $filters, $page );
		}

		return ethnic_case_studies_archive_url( $filters, $page, $term->slug );
	}
}

if ( ! function_exists( 'ethnic_case_studies_get_summary' ) ) {
	function ethnic_case_studies_get_summary( $post_id ) {
		$post_id = (int) $post_id;
		$post    = get_post( $post_id );

		if ( ! ( $post instanceof WP_Post ) ) {
			return '';
		}

		$excerpt = has_excerpt( $post_id ) ? get_the_excerpt( $post_id ) : '';
		$excerpt = ethnic_case_studies_text( $excerpt );

		if ( '' !== $excerpt && ! ethnic_case_studies_is_placeholder( $excerpt ) ) {
			return ethnic_case_studies_trim_text( $excerpt, 28 );
		}

		foreach ( array( 'outcome', '_outcome', 'project_outcome', '_project_outcome', 'solution', '_solution', 'challenge', '_challenge' ) as $meta_key ) {
			$meta_value = ethnic_case_studies_text( get_post_meta( $post_id, $meta_key, true ) );

			if ( '' !== $meta_value && ! ethnic_case_studies_is_placeholder( $meta_value ) ) {
				return ethnic_case_studies_trim_text( $meta_value, 28 );
			}
		}

		$content = ethnic_case_studies_text( $post->post_content );

		if ( '' !== $content ) {
			return ethnic_case_studies_trim_text( $content, 28 );
		}

		return 'Outcome-focused delivery example covering product quality, implementation clarity, and measurable business impact.';
	}
}

if ( ! function_exists( 'ethnic_case_studies_app_service_slugs' ) ) {
	function ethnic_case_studies_app_service_slugs() {
		return array(
			'app-development',
			'mobile-app-development',
			'web-app-development',
			'android-app-development',
			'ios-app-development',
			'flutter-app-development',
			'react-native-app-development',
			'app-modernization',
			'workflow-platform',
			'digital-onboarding',
			'custom-software-development',
			'app-maintenance-support',
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_app_platform_slugs' ) ) {
	function ethnic_case_studies_app_platform_slugs() {
		return array(
			'ios',
			'android',
			'flutter',
			'react-native',
			'cross-platform',
			'web-app',
			'mobile-app',
			'saas',
			'custom-app',
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_is_app_related_terms' ) ) {
	function ethnic_case_studies_is_app_related_terms( $services, $platforms, $title = '', $summary = '' ) {
		$service_slugs  = array_map( 'sanitize_title', array_filter( (array) $services ) );
		$platform_slugs = array_map( 'sanitize_title', array_filter( (array) $platforms ) );

		if ( array_intersect( ethnic_case_studies_app_service_slugs(), $service_slugs ) ) {
			return true;
		}

		if ( array_intersect( ethnic_case_studies_app_platform_slugs(), $platform_slugs ) ) {
			return true;
		}

		$text = strtolower(
			implode(
				' ',
				array_filter(
					array(
						ethnic_case_studies_text( $title ),
						ethnic_case_studies_text( $summary ),
						implode( ' ', (array) $services ),
						implode( ' ', (array) $platforms ),
					)
				)
			)
		);

		foreach ( array( 'mobile app', 'web app', 'saas', 'workflow platform', 'client portal', 'dashboard', 'cross-platform', 'cross platform', 'react native', 'flutter', 'ios', 'android', 'app modernization', 'custom app', 'internal tool' ) as $keyword ) {
			if ( false !== strpos( $text, $keyword ) ) {
				return true;
			}
		}

		return false;
	}
}

if ( ! function_exists( 'ethnic_case_studies_is_app_related_post' ) ) {
	function ethnic_case_studies_is_app_related_post( $post ) {
		$post = get_post( $post );

		if ( ! ( $post instanceof WP_Post ) ) {
			return false;
		}

		return ethnic_case_studies_is_app_related_terms(
			ethnic_case_studies_get_service_terms( $post->ID ),
			ethnic_case_studies_get_platform_terms( $post->ID ),
			get_the_title( $post ),
			ethnic_case_studies_get_summary( $post->ID )
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_single_url' ) ) {
	function ethnic_case_studies_single_url( $post, $variant = '' ) {
		$post = get_post( $post );

		if ( ! ( $post instanceof WP_Post ) ) {
			return '';
		}

		$variant = sanitize_title( (string) $variant );

		if ( '' === $variant ) {
			$primary_category = ethnic_case_studies_primary_category_term( $post );

			if ( $primary_category instanceof WP_Term ) {
				$variant = $primary_category->slug;
			} elseif ( ethnic_case_studies_is_app_related_post( $post ) ) {
				$variant = ethnic_case_studies_app_archive_variant();
			}
		}

		if ( '' !== $variant ) {
			return home_url( '/' . trim( ethnic_case_studies_archive_variant_slug( $variant ), '/' ) . '/' . $post->post_name . '/' );
		}

		return get_permalink( $post );
	}
}

if ( ! function_exists( 'ethnic_case_studies_build_post_payload' ) ) {
	function ethnic_case_studies_build_post_payload( $post ) {
		$post = get_post( $post );

		if ( ! ( $post instanceof WP_Post ) || ethnic_case_studies_is_demo_post( $post ) ) {
			return array();
		}

		$image      = ethnic_case_studies_cover_image( $post->ID );
		$services   = ethnic_case_studies_get_service_terms( $post->ID );
		$platforms  = ethnic_case_studies_get_platform_terms( $post->ID );
		$industries = ethnic_case_studies_get_industry_terms( $post->ID );
		$categories = ethnic_case_studies_get_category_terms( $post->ID );

		return array(
			'id'         => (int) $post->ID,
			'title'      => ethnic_case_studies_text( get_the_title( $post ) ),
			'url'        => ethnic_case_studies_single_url( $post ),
			'summary'    => ethnic_case_studies_get_summary( $post->ID ),
			'categories' => $categories,
			'services'   => $services,
			'platforms'  => $platforms,
			'industries' => $industries,
			'image_url'  => $image['url'],
			'image_alt'  => $image['alt'],
			'featured'   => (bool) get_post_meta( $post->ID, ethnic_case_studies_featured_meta_key(), true ),
			'date'       => get_the_date( 'c', $post ),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_service_page_available_posts' ) ) {
	function ethnic_case_studies_service_page_available_posts() {
		static $posts = null;

		if ( null !== $posts ) {
			return $posts;
		}

		$posts = get_posts(
			ethnic_case_studies_build_query_args(
				array(),
				array(
					'posts_per_page'         => -1,
					'update_post_meta_cache' => false,
					'update_post_term_cache' => false,
					'no_found_rows'          => true,
				)
			)
		);

		return is_array( $posts ) ? $posts : array();
	}
}

if ( ! function_exists( 'ethnic_case_studies_service_page_selected_ids' ) ) {
	function ethnic_case_studies_service_page_selected_ids( $page_id = 0, $limit = 0 ) {
		$page_id = (int) $page_id;

		if ( $page_id < 1 ) {
			return array();
		}

		$selected_ids = get_post_meta( $page_id, ethnic_case_studies_service_page_case_study_ids_meta_key(), true );
		$selected_ids = is_array( $selected_ids ) ? $selected_ids : array();
		$selected_ids = array_values(
			array_filter(
				array_unique(
					array_map( 'intval', $selected_ids )
				),
				static function ( $post_id ) {
					return $post_id > 0 && ETHNIC_CASE_STUDIES_POST_TYPE === get_post_type( $post_id ) && 'publish' === get_post_status( $post_id );
				}
			)
		);

		if ( $limit > 0 ) {
			$selected_ids = array_slice( $selected_ids, 0, $limit );
		}

		return $selected_ids;
	}
}

if ( ! function_exists( 'ethnic_case_studies_service_page_parse_content_sections' ) ) {
	function ethnic_case_studies_service_page_parse_content_sections( $post_id ) {
		static $cache = array();

		$post_id = (int) $post_id;

		if ( $post_id < 1 ) {
			return array();
		}

		if ( isset( $cache[ $post_id ] ) ) {
			return $cache[ $post_id ];
		}

		$content = (string) get_post_field( 'post_content', $post_id );
		$content = preg_replace( '/<\/p>/i', "</p>\n", $content );
		$content = preg_replace( '/<br\s*\/?>/i', "\n", $content );
		$content = html_entity_decode( wp_strip_all_tags( $content ), ENT_QUOTES, get_bloginfo( 'charset' ) );
		$content = preg_replace( '/\s+/', ' ', trim( (string) $content ) );
		$parts   = array();

		if ( preg_match_all( '/(Challenge|Solution|Outcome)\s*:\s*(.+?)(?=(?:Challenge|Solution|Outcome)\s*:|$)/i', $content, $matches, PREG_SET_ORDER ) ) {
			foreach ( $matches as $match ) {
				$key = strtolower( ethnic_case_studies_text( $match[1] ) );

				if ( '' === $key ) {
					continue;
				}

				$parts[ $key ] = ethnic_case_studies_text( $match[2] );
			}
		}

		$cache[ $post_id ] = $parts;

		return $cache[ $post_id ];
	}
}

if ( ! function_exists( 'ethnic_case_studies_service_page_card_copy' ) ) {
	function ethnic_case_studies_service_page_card_copy( $post_id, $type ) {
		$post_id = (int) $post_id;
		$type    = sanitize_key( (string) $type );

		if ( $post_id < 1 || '' === $type ) {
			return '';
		}

		$meta_candidates = array(
			'challenge' => array( 'challenge', '_challenge', 'project_challenge', '_project_challenge', 'case_study_challenge', '_case_study_challenge', 'brief', '_brief' ),
			'solution'  => array( 'solution', '_solution', 'project_solution', '_project_solution', 'case_study_solution', '_case_study_solution' ),
			'outcome'   => array( 'outcome', '_outcome', 'project_outcome', '_project_outcome', 'case_study_outcome', '_case_study_outcome', 'result', '_result' ),
		);

		if ( isset( $meta_candidates[ $type ] ) ) {
			foreach ( $meta_candidates[ $type ] as $meta_key ) {
				$value = ethnic_case_studies_text( get_post_meta( $post_id, $meta_key, true ) );

				if ( '' !== $value && ! ethnic_case_studies_is_placeholder( $value ) ) {
					return ethnic_case_studies_trim_text( $value, 24 );
				}
			}
		}

		if ( 'challenge' === $type ) {
			$value = ethnic_case_studies_single_custom_text( $post_id, 'challenge_intro' );

			if ( '' !== $value ) {
				return ethnic_case_studies_trim_text( $value, 24 );
			}

			$rows  = ethnic_case_studies_single_custom_rows( $post_id, 'challenges', array( 'title', 'description' ) );
			$value = ! empty( $rows[0]['description'] ) ? $rows[0]['description'] : ( ! empty( $rows[0]['title'] ) ? $rows[0]['title'] : '' );

			if ( '' !== $value ) {
				return ethnic_case_studies_trim_text( $value, 24 );
			}
		}

		if ( 'solution' === $type ) {
			$paragraphs = ethnic_case_studies_parse_paragraphs( get_post_meta( $post_id, ethnic_case_studies_content_meta_key( 'solution_paragraphs' ), true ) );
			$value      = ! empty( $paragraphs[0] ) ? $paragraphs[0] : '';

			if ( '' !== $value ) {
				return ethnic_case_studies_trim_text( $value, 24 );
			}

			$rows  = ethnic_case_studies_single_custom_rows( $post_id, 'solution_pillars', array( 'title', 'description' ) );
			$value = ! empty( $rows[0]['description'] ) ? $rows[0]['description'] : ( ! empty( $rows[0]['title'] ) ? $rows[0]['title'] : '' );

			if ( '' !== $value ) {
				return ethnic_case_studies_trim_text( $value, 24 );
			}
		}

		if ( 'outcome' === $type ) {
			$rows  = ethnic_case_studies_single_custom_rows( $post_id, 'impact_cards', array( 'title', 'description' ) );
			$value = ! empty( $rows[0]['description'] ) ? $rows[0]['description'] : ( ! empty( $rows[0]['title'] ) ? $rows[0]['title'] : '' );

			if ( '' !== $value ) {
				return ethnic_case_studies_trim_text( $value, 24 );
			}

			$rows  = ethnic_case_studies_single_custom_rows( $post_id, 'result_cards', array( 'value', 'label', 'description' ) );
			$value = ! empty( $rows[0]['description'] ) ? $rows[0]['description'] : ( ! empty( $rows[0]['label'] ) ? $rows[0]['label'] : '' );

			if ( '' !== $value ) {
				return ethnic_case_studies_trim_text( $value, 24 );
			}
		}

		$sections = ethnic_case_studies_service_page_parse_content_sections( $post_id );

		if ( ! empty( $sections[ $type ] ) ) {
			return ethnic_case_studies_trim_text( $sections[ $type ], 24 );
		}

		return ethnic_case_studies_trim_text( ethnic_case_studies_get_summary( $post_id ), 24 );
	}
}

if ( ! function_exists( 'ethnic_case_studies_service_page_card_from_post' ) ) {
	function ethnic_case_studies_service_page_card_from_post( $post ) {
		$payload = ethnic_case_studies_build_post_payload( $post );

		if ( empty( $payload ) || empty( $payload['id'] ) ) {
			return array();
		}

		$post_id  = (int) $payload['id'];
		$platform = ethnic_case_studies_first_value( $payload['platforms'], 'Custom Platform' );
		$industry = ethnic_case_studies_first_value( $payload['industries'], 'Case Study' );
		$service  = ethnic_case_studies_first_value( $payload['services'], 'Digital Product Delivery' );

		return array(
			'id'           => $post_id,
			'title'        => $payload['title'],
			'summary'      => $payload['summary'],
			'platform'     => $platform,
			'industry'     => $industry,
			'service'      => $service,
			'challenge'    => ethnic_case_studies_service_page_card_copy( $post_id, 'challenge' ),
			'solution'     => ethnic_case_studies_service_page_card_copy( $post_id, 'solution' ),
			'outcome'      => ethnic_case_studies_service_page_card_copy( $post_id, 'outcome' ),
			'url'          => $payload['url'],
			'image'        => $payload['image_url'],
			'image_alt'    => $payload['image_alt'],
			'technologies' => array_values(
				array_unique(
					array_filter(
						array(
							$platform,
							$industry,
							$service,
						)
					)
				)
			),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_service_page_cards' ) ) {
	function ethnic_case_studies_service_page_cards( $args = array() ) {
		$args = wp_parse_args(
			(array) $args,
			array(
				'page_id'        => 0,
				'limit'          => 3,
				'filters'        => array(),
				'fallback_items' => array(),
			)
		);

		$page_id       = (int) $args['page_id'];
		$limit         = max( 1, (int) $args['limit'] );
		$filters       = is_array( $args['filters'] ) ? $args['filters'] : array();
		$fallbacks     = is_array( $args['fallback_items'] ) ? $args['fallback_items'] : array();
		$taxonomies    = ethnic_case_studies_taxonomies();
		$selected_ids  = array();
		$items         = array();
		$seen_titles   = array();

		if ( $page_id < 1 && function_exists( 'get_queried_object_id' ) ) {
			$page_id = (int) get_queried_object_id();
		}

		if ( $page_id > 0 ) {
			$selected_ids = ethnic_case_studies_service_page_selected_ids( $page_id, $limit );
		}

		$is_service_page = $page_id > 0 && ethnic_case_studies_is_service_page( $page_id );

		if ( $is_service_page && empty( $selected_ids ) ) {
			return array();
		}

		foreach ( $selected_ids as $selected_id ) {
			$item = ethnic_case_studies_service_page_card_from_post( $selected_id );

			if ( empty( $item ) ) {
				continue;
			}

			$item_key = sanitize_title( $item['title'] );

			if ( isset( $seen_titles[ $item_key ] ) ) {
				continue;
			}

			$items[]                = $item;
			$seen_titles[ $item_key ] = true;
		}

		if ( $is_service_page ) {
			return array_slice( $items, 0, $limit );
		}

		if ( count( $items ) < $limit ) {
			$query_filters   = array();
			$extra_tax_query = array();

			foreach ( array( 'service', 'platform', 'industry' ) as $taxonomy_key ) {
				if ( ! empty( $filters[ $taxonomy_key ] ) ) {
					$query_filters[ $taxonomy_key ] = $filters[ $taxonomy_key ];
				}
			}

			if ( ! empty( $filters['category'] ) ) {
				$extra_tax_query[] = array(
					'taxonomy' => $taxonomies['category'],
					'field'    => 'slug',
					'terms'    => ethnic_case_studies_normalize_requested_slugs( $filters['category'] ),
					'operator' => 'IN',
				);
			}

			$query_args = ethnic_case_studies_build_query_args(
				$query_filters,
				array(
					'posts_per_page'         => max( $limit * 4, 6 ),
					'post__not_in'           => $selected_ids,
					'update_post_meta_cache' => true,
					'update_post_term_cache' => true,
					'no_found_rows'          => true,
				)
			);

			if ( ! empty( $extra_tax_query ) ) {
				if ( ! empty( $query_args['tax_query'] ) ) {
					$current_tax_query = (array) $query_args['tax_query'];
					unset( $query_args['tax_query'] );

					$query_args['tax_query'] = array_merge(
						array( 'relation' => 'AND' ),
						isset( $current_tax_query['relation'] ) ? array_values( array_filter( $current_tax_query, 'is_array' ) ) : $current_tax_query,
						$extra_tax_query
					);
				} else {
					$query_args['tax_query'] = 1 === count( $extra_tax_query ) ? $extra_tax_query : array_merge( array( 'relation' => 'AND' ), $extra_tax_query );
				}
			}

			foreach ( get_posts( $query_args ) as $case_study_post ) {
				$item = ethnic_case_studies_service_page_card_from_post( $case_study_post );

				if ( empty( $item ) ) {
					continue;
				}

				$item_key = sanitize_title( $item['title'] );

				if ( isset( $seen_titles[ $item_key ] ) ) {
					continue;
				}

				$items[]                  = $item;
				$seen_titles[ $item_key ] = true;

				if ( count( $items ) >= $limit ) {
					break;
				}
			}
		}

		foreach ( $fallbacks as $fallback ) {
			if ( count( $items ) >= $limit || ! is_array( $fallback ) ) {
				continue;
			}

			$title = isset( $fallback['title'] ) ? ethnic_case_studies_text( $fallback['title'] ) : '';

			if ( '' === $title ) {
				continue;
			}

			$item_key = sanitize_title( $title );

			if ( isset( $seen_titles[ $item_key ] ) ) {
				continue;
			}

			$items[] = array(
				'title'     => $title,
				'platform'  => isset( $fallback['platform'] ) ? ethnic_case_studies_text( $fallback['platform'], 'Custom Platform' ) : 'Custom Platform',
				'industry'  => isset( $fallback['industry'] ) ? ethnic_case_studies_text( $fallback['industry'], 'Case Study' ) : 'Case Study',
				'service'   => isset( $fallback['service'] ) ? ethnic_case_studies_text( $fallback['service'], 'Digital Product Delivery' ) : 'Digital Product Delivery',
				'challenge' => isset( $fallback['challenge'] ) ? ethnic_case_studies_text( $fallback['challenge'] ) : '',
				'solution'  => isset( $fallback['solution'] ) ? ethnic_case_studies_text( $fallback['solution'] ) : '',
				'outcome'   => isset( $fallback['outcome'] ) ? ethnic_case_studies_text( $fallback['outcome'] ) : '',
				'url'       => ! empty( $fallback['url'] ) ? esc_url_raw( $fallback['url'] ) : ethnic_case_studies_archive_url(),
			);

			$seen_titles[ $item_key ] = true;
		}

		return array_slice( $items, 0, $limit );
	}
}

if ( ! function_exists( 'ethnic_case_studies_result_highlights' ) ) {
	function ethnic_case_studies_result_highlights( $post_id ) {
		$service_text  = strtolower( implode( ' ', ethnic_case_studies_get_service_terms( $post_id ) ) );
		$platform_text = strtolower( implode( ' ', ethnic_case_studies_get_platform_terms( $post_id ) ) );
		$industry_text = strtolower( implode( ' ', ethnic_case_studies_get_industry_terms( $post_id ) ) );
		$results       = array();

		if ( false !== strpos( $industry_text, 'retail' ) || false !== strpos( $industry_text, 'fashion' ) ) {
			$results[] = 'Conversion support';
			$results[] = 'Customer experience';
		}

		if ( false !== strpos( $industry_text, 'logistics' ) || false !== strpos( $service_text, 'workflow' ) ) {
			$results[] = 'Workflow efficiency';
			$results[] = 'Operational visibility';
		}

		if ( false !== strpos( $industry_text, 'fintech' ) || false !== strpos( $service_text, 'onboarding' ) ) {
			$results[] = 'Journey clarity';
			$results[] = 'Scalable delivery';
		}

		if ( false !== strpos( $platform_text, 'web app' ) ) {
			$results[] = 'Platform performance';
		}

		if ( false !== strpos( $platform_text, 'mobile app' ) || false !== strpos( $platform_text, 'ios' ) || false !== strpos( $platform_text, 'android' ) ) {
			$results[] = 'Mobile readiness';
		}

		if ( false !== strpos( $service_text, 'modernization' ) ) {
			$results[] = 'Legacy simplification';
		}

		if ( empty( $results ) ) {
			$results = array(
				'Delivery quality',
				'Technical confidence',
				'Business alignment',
			);
		}

		return array_slice( array_values( array_unique( $results ) ), 0, 3 );
	}
}

if ( ! function_exists( 'ethnic_case_studies_placeholder_image_url' ) ) {
	function ethnic_case_studies_placeholder_image_url() {
		return content_url( 'uploads/2026/03/placeholder-1-768x512.png' );
	}
}

if ( ! function_exists( 'ethnic_case_studies_first_value' ) ) {
	function ethnic_case_studies_first_value( $values, $fallback = '' ) {
		foreach ( (array) $values as $value ) {
			$value = ethnic_case_studies_text( $value );

			if ( '' !== $value ) {
				return $value;
			}
		}

		return $fallback;
	}
}

if ( ! function_exists( 'ethnic_case_studies_content_meta_key' ) ) {
	function ethnic_case_studies_content_meta_key( $field ) {
		return 'ethnic_case_study_' . sanitize_key( (string) $field );
	}
}

if ( ! function_exists( 'ethnic_case_studies_single_custom_text' ) ) {
	function ethnic_case_studies_single_custom_text( $post_id, $field, $fallback = '' ) {
		return ethnic_case_studies_text( get_post_meta( $post_id, ethnic_case_studies_content_meta_key( $field ), true ), $fallback );
	}
}

if ( ! function_exists( 'ethnic_case_studies_parse_lines' ) ) {
	function ethnic_case_studies_parse_lines( $value ) {
		$value = is_scalar( $value ) ? trim( (string) $value ) : '';

		if ( '' === $value ) {
			return array();
		}

		$lines = preg_split( '/\r\n|\r|\n/', $value );
		$lines = is_array( $lines ) ? $lines : array();

		return array_values(
			array_filter(
				array_map(
					static function ( $line ) {
						return ethnic_case_studies_text( $line );
					},
					$lines
				)
			)
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_parse_paragraphs' ) ) {
	function ethnic_case_studies_parse_paragraphs( $value ) {
		$value = is_scalar( $value ) ? trim( (string) $value ) : '';

		if ( '' === $value ) {
			return array();
		}

		$paragraphs = preg_split( "/(?:\r\n|\r|\n){2,}/", $value );
		$paragraphs = is_array( $paragraphs ) ? $paragraphs : array();

		return array_values(
			array_filter(
				array_map(
					static function ( $paragraph ) {
						return ethnic_case_studies_text( preg_replace( "/(?:\r\n|\r|\n)+/", ' ', (string) $paragraph ) );
					},
					$paragraphs
				)
			)
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_parse_structured_rows' ) ) {
	function ethnic_case_studies_parse_structured_rows( $value, $keys ) {
		$keys = array_values( array_filter( array_map( 'sanitize_key', (array) $keys ) ) );

		if ( empty( $keys ) ) {
			return array();
		}

		$rows = array();

		foreach ( ethnic_case_studies_parse_lines( $value ) as $line ) {
			$parts = explode( '|', $line, count( $keys ) );
			$parts = array_map( 'trim', $parts );
			$parts = array_pad( $parts, count( $keys ), '' );
			$row   = array();

			foreach ( $keys as $index => $key ) {
				$row[ $key ] = ethnic_case_studies_text( $parts[ $index ] );
			}

			if ( array_filter( $row ) ) {
				$rows[] = $row;
			}
		}

		return $rows;
	}
}

if ( ! function_exists( 'ethnic_case_studies_single_custom_rows' ) ) {
	function ethnic_case_studies_single_custom_rows( $post_id, $field, $keys ) {
		return ethnic_case_studies_parse_structured_rows(
			get_post_meta( $post_id, ethnic_case_studies_content_meta_key( $field ), true ),
			$keys
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_single_custom_tech_stack' ) ) {
	function ethnic_case_studies_single_custom_tech_stack( $post_id ) {
		$rows   = ethnic_case_studies_single_custom_rows( $post_id, 'tech_stack', array( 'label', 'items' ) );
		$groups = array();

		foreach ( $rows as $row ) {
			$items = ethnic_case_studies_split_list( isset( $row['items'] ) ? $row['items'] : '' );

			if ( empty( $row['label'] ) || empty( $items ) ) {
				continue;
			}

			$groups[] = array(
				'label' => $row['label'],
				'items' => $items,
			);
		}

		return $groups;
	}
}

if ( ! function_exists( 'ethnic_case_studies_logo_library_posts' ) ) {
	function ethnic_case_studies_logo_library_posts( $post_status = array( 'publish' ) ) {
		return get_posts(
			array(
				'post_type'      => ETHNIC_CASE_STUDIES_LOGO_POST_TYPE,
				'post_status'    => $post_status,
				'orderby'        => array(
					'menu_order' => 'ASC',
					'title'      => 'ASC',
				),
				'numberposts'    => -1,
				'suppress_filters' => false,
			)
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_logo_image_url' ) ) {
	function ethnic_case_studies_logo_image_url( $post_id, $size = 'medium' ) {
		$post_id = (int) $post_id;

		if ( $post_id <= 0 ) {
			return '';
		}

		$image_id = (int) get_post_meta( $post_id, ethnic_case_studies_logo_image_id_meta_key(), true );
		$image_url = $image_id > 0 ? wp_get_attachment_image_url( $image_id, $size ) : '';

		if ( '' !== $image_url ) {
			return $image_url;
		}

		return esc_url_raw( get_post_meta( $post_id, ethnic_case_studies_logo_image_url_meta_key(), true ) );
	}
}

if ( ! function_exists( 'ethnic_case_studies_logo_image_alt' ) ) {
	function ethnic_case_studies_logo_image_alt( $post_id ) {
		$post_id = (int) $post_id;

		if ( $post_id <= 0 ) {
			return '';
		}

		$image_id = (int) get_post_meta( $post_id, ethnic_case_studies_logo_image_id_meta_key(), true );

		if ( $image_id > 0 ) {
			$alt = ethnic_case_studies_text( get_post_meta( $image_id, '_wp_attachment_image_alt', true ) );

			if ( '' !== $alt ) {
				return $alt;
			}
		}

		return ethnic_case_studies_text( get_the_title( $post_id ), 'Tech logo' ) . ' logo';
	}
}

if ( ! function_exists( 'ethnic_case_studies_selected_logo_ids' ) ) {
	function ethnic_case_studies_selected_logo_ids( $post_id ) {
		$stored = get_post_meta( $post_id, ethnic_case_studies_logo_selection_meta_key(), true );

		if ( is_string( $stored ) && '' !== $stored ) {
			$stored = explode( ',', $stored );
		}

		if ( ! is_array( $stored ) ) {
			return array();
		}

		return array_values(
			array_unique(
				array_filter(
					array_map( 'intval', $stored )
				)
			)
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_selected_logo_items' ) ) {
	function ethnic_case_studies_selected_logo_items( $post_id ) {
		$selected_ids = ethnic_case_studies_selected_logo_ids( $post_id );

		if ( empty( $selected_ids ) ) {
			return array();
		}

		$logo_posts = get_posts(
			array(
				'post_type'      => ETHNIC_CASE_STUDIES_LOGO_POST_TYPE,
				'post_status'    => 'publish',
				'post__in'       => $selected_ids,
				'orderby'        => 'post__in',
				'numberposts'    => -1,
				'suppress_filters' => false,
			)
		);

		$items = array();

		foreach ( $logo_posts as $logo_post ) {
			$label = ethnic_case_studies_text( get_the_title( $logo_post ) );

			if ( '' === $label ) {
				continue;
			}

			$src = ethnic_case_studies_logo_image_url( $logo_post->ID, 'medium' );

			$items[] = array(
				'slug'     => sanitize_title( $logo_post->post_name ? $logo_post->post_name : $label ),
				'label'    => $label,
				'group'    => '',
				'monogram' => ethnic_case_studies_stack_item_monogram( $label ),
				'src'      => $src,
				'alt'      => ethnic_case_studies_logo_image_alt( $logo_post->ID ),
				'mode'     => '' !== $src ? 'image' : 'monogram',
				'fg'       => '#2f6bff',
			);
		}

		return $items;
	}
}

if ( ! function_exists( 'ethnic_case_studies_stack_item_monogram' ) ) {
	function ethnic_case_studies_stack_item_monogram( $label ) {
		$label = ethnic_case_studies_text( $label );

		if ( '' === $label ) {
			return 'CS';
		}

		$words = preg_split( '/[^A-Za-z0-9]+/', $label );
		$words = array_values( array_filter( is_array( $words ) ? $words : array() ) );

		if ( empty( $words ) ) {
			return strtoupper( substr( preg_replace( '/[^A-Za-z0-9]/', '', $label ), 0, 2 ) );
		}

		if ( 1 === count( $words ) ) {
			return strtoupper( substr( $words[0], 0, min( 3, strlen( $words[0] ) ) ) );
		}

		$mark = '';

		foreach ( array_slice( $words, 0, 2 ) as $word ) {
			$mark .= strtoupper( substr( $word, 0, 1 ) );
		}

		return $mark;
	}
}

if ( ! function_exists( 'ethnic_case_studies_stack_logo_catalog' ) ) {
	function ethnic_case_studies_stack_logo_catalog() {
		return array(
			'magento' => array(
				'label' => 'Magento',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/magento.svg' ),
				'alt'   => 'Magento logo',
				'mode'  => 'image',
				'fg'    => '#f46c25',
			),
			'hyva' => array(
				'label' => 'Hyva',
				'src'   => 'https://ethnicinfotech.com/wp-content/uploads/2025/12/Hyva-logo-1-removebg-preview-e1767165459983.png',
				'alt'   => 'Hyva logo',
				'mode'  => 'image',
				'fg'    => '#111827',
			),
			'adobe-commerce' => array(
				'label' => 'Adobe Commerce',
				'src' => 'https://ethnicinfotech.com/wp-content/uploads/2025/01/43fd8695be7ce97bbfd0b2b1f743c98b-300x162.png',
				'alt' => 'Adobe Commerce logo',
				'mode' => 'image',
				'fg'  => '#f46c25',
			),
			'jquery' => array(
				'label' => 'jQuery',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/jquery.svg' ),
				'alt'   => 'jQuery logo',
				'mode'  => 'image',
				'fg'    => '#217bcc',
			),
			'shopify' => array(
				'label' => 'Shopify',
				'src' => content_url( 'uploads/2026/04/service-logos/shopify-site-icon-official.png' ),
				'alt' => 'Shopify logo',
				'mode' => 'image',
				'fg'  => '#5f8e28',
			),
			'docker' => array(
				'label' => 'Docker',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/docker.svg' ),
				'alt'   => 'Docker logo',
				'mode'  => 'image',
				'fg'    => '#1673f5',
			),
			'android' => array(
				'label' => 'Android',
				'src' => content_url( 'uploads/2026/04/service-logos/android-official.svg' ),
				'alt' => 'Android logo',
				'mode' => 'image',
				'fg'  => '#26b85b',
			),
			'openai' => array(
				'label' => 'OpenAI',
				'src' => content_url( 'uploads/2026/04/service-logos/openai-wordmark-official.webp' ),
				'alt' => 'OpenAI logo',
				'mode' => 'image',
				'fg'  => '#111827',
			),
			'knockout' => array(
				'label' => 'Knockout',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/knockout-logo.png' ),
				'alt'   => 'Knockout logo',
				'mode'  => 'image',
				'fg'    => '#c2255c',
			),
			'php' => array(
				'label' => 'PHP',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/php.svg' ),
				'alt'   => 'PHP logo',
				'mode'  => 'image',
				'fg'    => '#777bb4',
			),
			'product-catalog' => array(
				'label' => 'Product Catalog',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/package.svg' ),
				'mode'  => 'mask',
				'fg'    => '#2f6bff',
			),
			'advanced-filters' => array(
				'label' => 'Advanced Filters',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/filter.svg' ),
				'mode'  => 'mask',
				'fg'    => '#2f6bff',
			),
			'promotions' => array(
				'label' => 'Promotions',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/badge-percent.svg' ),
				'mode'  => 'mask',
				'fg'    => '#17833e',
			),
			'offbiz-product-data' => array(
				'label' => 'Offbiz Product Data',
				'src'   => 'https://ofbiz.apache.org/images/ofbiz_logo.png',
				'alt'   => 'Apache OFBiz logo',
				'mode'  => 'image',
				'fg'    => '#008e82',
			),
			'offbiz-customer-data' => array(
				'label' => 'Offbiz Customer Data',
				'src'   => 'https://ofbiz.apache.org/images/ofbiz_logo.png',
				'alt'   => 'Apache OFBiz logo',
				'mode'  => 'image',
				'fg'    => '#008e82',
			),
			'region-based-shipping' => array(
				'label' => 'Region-Based Shipping',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/truck.svg' ),
				'mode'  => 'mask',
				'fg'    => '#2f6bff',
			),
			'terrarium-options' => array(
				'label' => 'Terrarium Options',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/sliders-horizontal.svg' ),
				'mode'  => 'mask',
				'fg'    => '#5d46ff',
			),
			'rest-api' => array(
				'label' => 'REST API',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/database.svg' ),
				'mode'  => 'mask',
				'fg'    => '#2f6bff',
			),
			'ga4' => array(
				'label' => 'GA4',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/database.svg' ),
				'mode'  => 'mask',
				'fg'    => '#2f6bff',
			),
			'gtm' => array(
				'label' => 'GTM',
				'src'   => content_url( 'uploads/2026/04/case-study-stack-logos/database.svg' ),
				'mode'  => 'mask',
				'fg'    => '#2f6bff',
			),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_stack_logo_data' ) ) {
	function ethnic_case_studies_stack_logo_data( $item, $group_label = '' ) {
		$item       = ethnic_case_studies_text( $item );
		$group_label = ethnic_case_studies_text( $group_label );
		$slug       = sanitize_title( $item );
		$catalog    = ethnic_case_studies_stack_logo_catalog();
		$palettes   = array(
			array( 'fg' => '#2f6bff' ),
			array( 'fg' => '#008e82' ),
			array( 'fg' => '#f7672a' ),
			array( 'fg' => '#5d46ff' ),
			array( 'fg' => '#17833e' ),
			array( 'fg' => '#c2255c' ),
		);

		if ( isset( $catalog[ $slug ] ) ) {
			$data = $catalog[ $slug ];
		} else {
			$palette_index = abs( crc32( $slug ) ) % count( $palettes );
			$data          = $palettes[ $palette_index ];
		}

		$data['slug']      = $slug;
		$data['label']     = isset( $data['label'] ) && '' !== $data['label'] ? $data['label'] : $item;
		$data['group']     = $group_label;
		$data['monogram']  = isset( $data['monogram'] ) && '' !== $data['monogram'] ? $data['monogram'] : ethnic_case_studies_stack_item_monogram( $item );
		$data['src']       = isset( $data['src'] ) ? esc_url_raw( $data['src'] ) : '';
		$data['alt']       = isset( $data['alt'] ) && '' !== $data['alt'] ? $data['alt'] : $item . ' logo';
		$data['mode']      = isset( $data['mode'] ) ? $data['mode'] : ( '' !== $data['src'] ? 'image' : 'monogram' );
		$data['fg']        = isset( $data['fg'] ) ? $data['fg'] : '#2f6bff';

		return $data;
	}
}

if ( ! function_exists( 'ethnic_case_studies_prepare_tech_stack_items' ) ) {
	function ethnic_case_studies_prepare_tech_stack_items( $groups ) {
		$items = array();

		foreach ( (array) $groups as $group ) {
			$label = isset( $group['label'] ) ? ethnic_case_studies_text( $group['label'] ) : '';
			$list  = isset( $group['items'] ) && is_array( $group['items'] ) ? $group['items'] : array();

			foreach ( $list as $item ) {
				$item = ethnic_case_studies_text( $item );

				if ( '' === $item ) {
					continue;
				}

				$key = sanitize_title( $label . '-' . $item );

				if ( isset( $items[ $key ] ) ) {
					continue;
				}

				$items[ $key ] = ethnic_case_studies_stack_logo_data( $item, $label );
			}
		}

		return array_values( $items );
	}
}

if ( ! function_exists( 'ethnic_case_studies_media_type' ) ) {
	function ethnic_case_studies_media_type( $url ) {
		$extension = strtolower( pathinfo( (string) wp_parse_url( (string) $url, PHP_URL_PATH ), PATHINFO_EXTENSION ) );

		if ( in_array( $extension, array( 'mp4', 'webm', 'ogg', 'mov', 'm4v' ), true ) ) {
			return 'video';
		}

		return 'image';
	}
}

if ( ! function_exists( 'ethnic_case_studies_media_item' ) ) {
	function ethnic_case_studies_media_item( $media_url, $alt = '', $caption = '' ) {
		$media_url = esc_url_raw( $media_url );

		return array(
			'image_url'  => $media_url,
			'media_url'  => $media_url,
			'media_type' => ethnic_case_studies_media_type( $media_url ),
			'alt'        => ethnic_case_studies_text( $alt, 'Case study visual' ),
			'caption'    => ethnic_case_studies_text( $caption ),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_single_custom_gallery' ) ) {
	function ethnic_case_studies_single_custom_gallery( $post_id ) {
		$rows  = ethnic_case_studies_single_custom_rows( $post_id, 'gallery_items', array( 'image_url', 'alt', 'caption' ) );
		$items = array();

		foreach ( $rows as $row ) {
			$image_url = isset( $row['image_url'] ) ? esc_url_raw( $row['image_url'] ) : '';

			if ( '' === $image_url ) {
				continue;
			}

			$items[] = ethnic_case_studies_media_item(
				$image_url,
				isset( $row['alt'] ) ? $row['alt'] : '',
				isset( $row['caption'] ) ? $row['caption'] : ''
			);
		}

		return $items;
	}
}

if ( ! function_exists( 'ethnic_case_studies_single_custom_related_services' ) ) {
	function ethnic_case_studies_single_custom_related_services( $post_id ) {
		$rows     = ethnic_case_studies_single_custom_rows( $post_id, 'related_services', array( 'title', 'copy', 'url' ) );
		$services = array();

		foreach ( $rows as $row ) {
			$title = isset( $row['title'] ) ? $row['title'] : '';
			$copy  = isset( $row['copy'] ) ? $row['copy'] : '';
			$url   = isset( $row['url'] ) ? esc_url_raw( $row['url'] ) : '';

			if ( '' === $title || '' === $url ) {
				continue;
			}

			$services[] = array(
				'title' => $title,
				'copy'  => $copy,
				'url'   => $url,
			);
		}

		return $services;
	}
}

if ( ! function_exists( 'ethnic_case_studies_related_service_catalog' ) ) {
	function ethnic_case_studies_related_service_catalog() {
		return array(
			'app-development'           => array(
				'title' => 'App Development',
				'copy'  => 'Plan and deliver custom application experiences built for usability, scale, and long-term maintainability.',
				'url'   => home_url( '/services/app-development/' ),
			),
			'mobile-app-development'    => array(
				'title' => 'Mobile App Development',
				'copy'  => 'Create product-ready mobile experiences with clearer journeys, stronger performance, and release confidence.',
				'url'   => home_url( '/services/mobile-app-development/' ),
			),
			'web-app-development'       => array(
				'title' => 'Web App Development',
				'copy'  => 'Build portals, internal tools, and customer-facing platforms that support growth without adding delivery friction.',
				'url'   => home_url( '/services/web-app-development/' ),
			),
			'ios-app-development'       => array(
				'title' => 'iOS App Development',
				'copy'  => 'Design and engineer iOS experiences with premium UX, maintainable code, and launch-ready quality standards.',
				'url'   => home_url( '/services/app-development/ios-app-development/' ),
			),
			'android-app-development'   => array(
				'title' => 'Android App Development',
				'copy'  => 'Ship Android products with cleaner architecture, better device readiness, and stronger release stability.',
				'url'   => home_url( '/services/app-development/android-app-development/' ),
			),
			'flutter-app-development'   => array(
				'title' => 'Flutter App Development',
				'copy'  => 'Use Flutter for efficient cross-platform delivery without compromising quality, consistency, or future scalability.',
				'url'   => home_url( '/services/app-development/flutter-app-development/' ),
			),
			'ecommerce-development'     => array(
				'title' => 'eCommerce Development',
				'copy'  => 'Support storefront delivery, modernization, and commerce-focused customer experiences tied to business growth.',
				'url'   => home_url( '/services/' ),
			),
			'ui-ux-design'              => array(
				'title' => 'UI/UX Design',
				'copy'  => 'Improve journey clarity, task completion, and product confidence through research-led interface design.',
				'url'   => home_url( '/services/' ),
			),
			'integrations'              => array(
				'title' => 'Integrations',
				'copy'  => 'Connect the tools, systems, and data flows that keep operational delivery aligned behind the scenes.',
				'url'   => home_url( '/services/' ),
			),
			'support-maintenance'       => array(
				'title' => 'Support & Maintenance',
				'copy'  => 'Keep product delivery stable with iterative improvements, monitoring, optimization, and release support.',
				'url'   => home_url( '/services/' ),
			),
			'devops'                    => array(
				'title' => 'DevOps',
				'copy'  => 'Strengthen infrastructure, release workflows, and observability for teams that need dependable delivery.',
				'url'   => home_url( '/services/' ),
			),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_related_services' ) ) {
	function ethnic_case_studies_related_services( $payload ) {
		$catalog = ethnic_case_studies_related_service_catalog();
		$keys    = array();

		foreach ( isset( $payload['services'] ) ? (array) $payload['services'] : array() as $service ) {
			$service_slug = sanitize_title( $service );

			switch ( $service_slug ) {
				case 'app-development':
					$keys[] = 'app-development';
					break;
				case 'mobile-app-development':
					$keys[] = 'mobile-app-development';
					break;
				case 'web-app-development':
					$keys[] = 'web-app-development';
					break;
				case 'app-modernization':
					$keys[] = 'app-development';
					$keys[] = 'support-maintenance';
					break;
				case 'workflow-platform':
				case 'digital-onboarding':
					$keys[] = 'web-app-development';
					$keys[] = 'integrations';
					break;
				case 'ecommerce-development':
					$keys[] = 'ecommerce-development';
					break;
				case 'devops':
					$keys[] = 'devops';
					break;
			}
		}

		foreach ( isset( $payload['platforms'] ) ? (array) $payload['platforms'] : array() as $platform ) {
			$platform_slug = sanitize_title( $platform );

			switch ( $platform_slug ) {
				case 'mobile-app':
					$keys[] = 'mobile-app-development';
					break;
				case 'web-app':
					$keys[] = 'web-app-development';
					break;
				case 'cross-platform':
					$keys[] = 'flutter-app-development';
					break;
				case 'ios':
					$keys[] = 'ios-app-development';
					break;
				case 'android':
					$keys[] = 'android-app-development';
					break;
				case 'flutter':
					$keys[] = 'flutter-app-development';
					break;
				case 'react-native':
					$keys[] = 'mobile-app-development';
					break;
			}
		}

		$keys = array_merge(
			$keys,
			array(
				'ui-ux-design',
				'integrations',
				'support-maintenance',
			)
		);

		$keys    = array_values( array_unique( array_filter( $keys ) ) );
		$related = array();

		foreach ( $keys as $key ) {
			if ( isset( $catalog[ $key ] ) ) {
				$related[] = $catalog[ $key ];
			}

			if ( count( $related ) >= 4 ) {
				break;
			}
		}

		return $related;
	}
}

if ( ! function_exists( 'ethnic_case_studies_single_gallery_items' ) ) {
	function ethnic_case_studies_single_gallery_items( $post_id, $payload ) {
		$post_id      = (int) $post_id;
		$thumbnail_id = (int) get_post_thumbnail_id( $post_id );
		$attachments  = get_attached_media( 'image', $post_id );
		$image_ids    = array();
		$items        = array();
		$captions     = array(
			'Primary experience view',
			'Delivery and workflow detail',
			'Responsive interface snapshot',
		);
		$fallback_url = ! empty( $payload['image_url'] ) ? $payload['image_url'] : ethnic_case_studies_placeholder_image_url();
		$fallback_alt = ethnic_case_studies_first_value(
			array(
				isset( $payload['image_alt'] ) ? $payload['image_alt'] : '',
				isset( $payload['title'] ) ? $payload['title'] : '',
			),
			'Case study visual'
		);

		if ( $thumbnail_id > 0 ) {
			$image_ids[] = $thumbnail_id;
		}

		if ( is_array( $attachments ) ) {
			foreach ( $attachments as $attachment ) {
				if ( $attachment instanceof WP_Post ) {
					$image_ids[] = (int) $attachment->ID;
				}
			}
		}

		$image_ids = array_values( array_unique( array_filter( $image_ids ) ) );

		foreach ( array_slice( $image_ids, 0, 3 ) as $index => $image_id ) {
			$image_url = wp_get_attachment_image_url( $image_id, 'large' );

			if ( ! $image_url ) {
				continue;
			}

			$items[] = ethnic_case_studies_media_item(
				$image_url,
				ethnic_case_studies_text( get_post_meta( $image_id, '_wp_attachment_image_alt', true ), $fallback_alt ),
				$captions[ $index ]
			);
		}

		while ( count( $items ) < 3 ) {
			$items[] = ethnic_case_studies_media_item(
				$fallback_url,
				$fallback_alt,
				$captions[ count( $items ) ]
			);
		}

		return $items;
	}
}

if ( ! function_exists( 'ethnic_case_studies_rendered_post_content' ) ) {
	function ethnic_case_studies_rendered_post_content( $post_id ) {
		$content_post = get_post( $post_id );

		if ( ! ( $content_post instanceof WP_Post ) ) {
			return '';
		}

		$raw_content = trim( (string) $content_post->post_content );

		if ( '' === trim( wp_strip_all_tags( $raw_content ) ) ) {
			return '';
		}

		global $post;
		$previous_post = $post;
		$post          = $content_post;

		setup_postdata( $content_post );
		$content = apply_filters( 'the_content', $content_post->post_content );
		wp_reset_postdata();

		$post = $previous_post;

		return trim( (string) $content );
	}
}

if ( ! function_exists( 'ethnic_case_studies_single_context' ) ) {
	function ethnic_case_studies_single_context( $post = null ) {
		$post = get_post( $post );

		if ( ! ( $post instanceof WP_Post ) ) {
			return array();
		}

		$payload = ethnic_case_studies_build_post_payload( $post );

		if ( empty( $payload ) ) {
			$image = ethnic_case_studies_cover_image( $post->ID, 'full' );

			$payload = array(
				'id'         => (int) $post->ID,
				'title'      => ethnic_case_studies_text( get_the_title( $post ) ),
				'url'        => get_permalink( $post ),
				'summary'    => ethnic_case_studies_get_summary( $post->ID ),
				'services'   => ethnic_case_studies_get_service_terms( $post->ID ),
				'platforms'  => ethnic_case_studies_get_platform_terms( $post->ID ),
				'industries' => ethnic_case_studies_get_industry_terms( $post->ID ),
				'image_url'  => $image['url'],
				'image_alt'  => $image['alt'],
				'featured'   => (bool) get_post_meta( $post->ID, ethnic_case_studies_featured_meta_key(), true ),
				'date'       => get_the_date( 'c', $post ),
			);
		}

		$service             = ethnic_case_studies_first_value( $payload['services'], 'Digital Product Delivery' );
		$platform            = ethnic_case_studies_first_value( $payload['platforms'], 'Custom Platform' );
		$industry            = ethnic_case_studies_first_value( $payload['industries'], 'Digital Services' );
		$is_app_related      = ethnic_case_studies_is_app_related_terms( $payload['services'], $payload['platforms'], $payload['title'], $payload['summary'] );
		$title_haystack      = strtolower( implode( ' ', array( $payload['title'], $payload['summary'], $service, $platform, $industry ) ) );
		$is_retail           = false !== strpos( strtolower( $industry ), 'retail' );
		$is_logistics        = false !== strpos( strtolower( $industry ), 'logistics' );
		$is_fintech          = false !== strpos( strtolower( $industry ), 'fintech' );
		$is_modernization    = false !== strpos( strtolower( $service ), 'modernization' ) || false !== strpos( $title_haystack, 'modernization' );
		$is_workflow         = false !== strpos( strtolower( $service ), 'workflow' ) || false !== strpos( $title_haystack, 'workflow' );
		$is_portal           = false !== strpos( strtolower( $service ), 'onboarding' ) || false !== strpos( $title_haystack, 'portal' );
		$is_mobile           = false !== strpos( strtolower( $platform ), 'mobile' ) || false !== strpos( strtolower( $platform ), 'ios' ) || false !== strpos( strtolower( $platform ), 'android' ) || false !== strpos( strtolower( $platform ), 'flutter' ) || false !== strpos( strtolower( $platform ), 'react native' );
		$is_web              = false !== strpos( strtolower( $platform ), 'web' ) || false !== strpos( $title_haystack, 'portal' ) || false !== strpos( $title_haystack, 'platform' );
		$project_type        = 'Digital Transformation';
		$client_name         = ethnic_case_studies_text( get_post_meta( $post->ID, '_thegem_cf_client', true ) );
		$content_summary     = ethnic_case_studies_text( wp_strip_all_tags( (string) $post->post_content ) );
		$hero_image_url      = ! empty( $payload['image_url'] ) ? $payload['image_url'] : ethnic_case_studies_placeholder_image_url();
		$hero_image_alt      = ethnic_case_studies_first_value( array( $payload['image_alt'], $payload['title'] ), 'Case study visual' );
		$hero_media_url      = $hero_image_url;
		$hero_media_type     = ethnic_case_studies_media_type( $hero_media_url );
		$hero_media_alt      = $hero_image_alt;
		$timeline_window     = '10-14 weeks';
		$engagement_model    = 'Phased delivery roadmap';
		$company_type        = 'Growth-focused digital business';
		$overview_paragraphs = array();
		$challenge_items     = array();
		$goals               = array();
		$solution_paragraphs = array();
		$solution_pillars    = array();
		$features            = array();
		$tech_stack          = array();
		$result_cards        = array();
		$impact_cards        = array();
		$back_link_label     = 'Back to Case Studies';
		$hero_eyebrow        = 'Case Study';
		$hero_overlay_kicker = 'Outcome Snapshot';
		$hero_primary_label  = 'Start a Similar Project';
		$hero_secondary_label = 'Talk to Our Team';
		$overview_kicker     = 'Client Overview';
		$overview_heading    = 'Who the client is and what shaped the project overview.';
		$overview_card_kicker = 'Client Snapshot';
		$challenge_kicker    = 'Business Challenge';
		$challenge_heading   = 'The blockers that were limiting delivery quality, clarity, or business momentum.';
		$goals_kicker        = 'Goals';
		$goals_heading       = 'The objectives that guided the engagement from planning through launch.';
		$solution_kicker     = 'Solution Delivered';
		$solution_heading    = 'The approach, execution model, and delivery decisions behind the solution delivered.';
		$features_kicker     = 'Features / Modules / Systems Built';
		$features_heading    = 'The core capabilities implemented across the product, platform, and operational flow.';
		$tech_stack_kicker   = 'Tech Stack';
		$tech_stack_heading  = 'The platform, systems, and delivery layers behind the implementation.';
		$timeline_kicker     = 'Timeline / Engagement Model';
		$timeline_heading    = 'How the project was delivered, phased, and supported.';
		$engagement_card_kicker = 'Engagement Summary';
		$results_kicker      = 'Results / Business Impact';
		$results_heading     = 'The outcomes, business impact, and platform readiness created through the engagement.';
		$gallery_kicker      = 'Screenshots / Visuals';
		$gallery_heading     = 'Selected visuals that support the project story and solution delivered.';
		$related_kicker      = 'Related Services';
		$related_heading     = 'Services connected to this case study and the next steps they can support.';
		$related_link_label  = 'Explore Service';
		$cta_kicker          = 'Start The Conversation';
		$cta_heading         = 'Need a similar solution for your business?';
		$cta_copy            = 'Let’s discuss your platform challenges, app idea, redesign, migration, integration, or support roadmap and shape the right next step together.';
		$cta_primary_label   = 'Start Your Project';
		$cta_secondary_label = 'Book a Free Consultation';

		if ( $is_modernization ) {
			$project_type = 'Transformation';
		} elseif ( $is_workflow ) {
			$project_type = 'Workflow Platform';
		} elseif ( $is_portal ) {
			$project_type = 'Client Portal';
		} elseif ( $is_mobile ) {
			$project_type = 'Mobile Product Build';
		} elseif ( $is_web ) {
			$project_type = 'Platform Build';
		}

		if ( '' === $client_name ) {
			if ( $is_retail ) {
				$client_name = 'Growing retail brand';
			} elseif ( $is_logistics ) {
				$client_name = 'Field operations and logistics team';
			} elseif ( $is_fintech ) {
				$client_name = 'Digital finance product team';
			} else {
				$client_name = 'Growth-focused digital product team';
			}
		}

		if ( $is_retail ) {
			$company_type     = 'Omnichannel retail business';
			$timeline_window  = '12-16 weeks';
			$engagement_model = 'Transformation roadmap with phased delivery';
		} elseif ( $is_logistics ) {
			$company_type     = 'Operations and workflow-driven business';
			$timeline_window  = '10-14 weeks';
			$engagement_model = 'Platform build with rollout planning';
		} elseif ( $is_fintech ) {
			$company_type     = 'Digital financial services platform';
			$timeline_window  = '12-14 weeks';
			$engagement_model = 'Product roadmap with staged release planning';
		} elseif ( $is_mobile ) {
			$company_type    = 'Product-led mobile-first business';
			$timeline_window = '12-16 weeks';
		}

		$custom_client_name     = ethnic_case_studies_single_custom_text( $post->ID, 'client_name' );
		$custom_service_terms   = ethnic_case_studies_split_list( get_post_meta( $post->ID, ethnic_case_studies_content_meta_key( 'service_override' ), true ) );
		$custom_platform_terms  = ethnic_case_studies_split_list( get_post_meta( $post->ID, ethnic_case_studies_content_meta_key( 'platform_override' ), true ) );
		$custom_industry_terms  = ethnic_case_studies_split_list( get_post_meta( $post->ID, ethnic_case_studies_content_meta_key( 'industry_override' ), true ) );
		$custom_project_type    = ethnic_case_studies_single_custom_text( $post->ID, 'project_type_override' );
		$custom_hero_subtitle   = ethnic_case_studies_single_custom_text( $post->ID, 'hero_subtitle' );
		$custom_hero_media_url  = ethnic_case_studies_single_custom_text( $post->ID, 'hero_media_url' );

		if ( ! empty( $custom_service_terms ) ) {
			$payload['services'] = $custom_service_terms;
			$service             = ethnic_case_studies_first_value( $payload['services'], $service );
		}

		if ( ! empty( $custom_platform_terms ) ) {
			$payload['platforms'] = $custom_platform_terms;
			$platform             = ethnic_case_studies_first_value( $payload['platforms'], $platform );
		}

		if ( ! empty( $custom_industry_terms ) ) {
			$payload['industries'] = $custom_industry_terms;
			$industry              = ethnic_case_studies_first_value( $payload['industries'], $industry );
		}

		if ( '' !== $custom_client_name ) {
			$client_name = $custom_client_name;
		}

		if ( '' !== $custom_project_type ) {
			$project_type = $custom_project_type;
		}

		$hero_subtitle = '' !== $custom_hero_subtitle ? $custom_hero_subtitle : $payload['summary'];

		if ( '' !== $custom_hero_media_url ) {
			$hero_media_url  = esc_url_raw( $custom_hero_media_url );
			$hero_media_type = ethnic_case_studies_media_type( $hero_media_url );
		}

		if ( '' !== $content_summary && ! ethnic_case_studies_is_placeholder( $content_summary ) ) {
			$content_summary = ethnic_case_studies_trim_text( $content_summary, 42 );
		} else {
			$content_summary = '';
		}

		$overview_paragraphs[] = sprintf(
			'%1$s is positioned in the %2$s space and needed a delivery partner that could translate business goals into a clearer product direction. This case study covers a %3$s engagement centered on %4$s, with the work shaped around usability, execution quality, and long-term maintainability.',
			$client_name,
			strtolower( $industry ),
			strtolower( $project_type ),
			strtolower( $service )
		);

		$overview_paragraphs[] = '' !== $content_summary
			? $content_summary
			: sprintf(
				'The engagement focused on creating a more dependable digital foundation, reducing avoidable delivery friction, and giving the internal team a stronger platform for growth, optimization, and future change.',
			);

		if ( $is_retail ) {
			$challenge_items = array(
				array(
					'title'       => 'Fragmented customer journeys',
					'description' => 'The existing experience made it harder to move cleanly between discovery, engagement, and repeat-purchase moments across key touchpoints.',
				),
				array(
					'title'       => 'Operational complexity behind the scenes',
					'description' => 'Admin teams were working around disconnected flows and manual coordination steps that slowed day-to-day execution.',
				),
				array(
					'title'       => 'Legacy structure limiting change',
					'description' => 'The previous setup was harder to evolve, making new features, promotions, and experience improvements more expensive to deliver.',
				),
				array(
					'title'       => 'Scalability and performance concerns',
					'description' => 'Growth plans required a cleaner foundation that could support future campaigns, integrations, and experience improvements with more confidence.',
				),
			);
		} elseif ( $is_logistics ) {
			$challenge_items = array(
				array(
					'title'       => 'Workflow visibility gaps',
					'description' => 'Core activities were spread across disconnected steps, making dispatch, status tracking, and coordination harder than they should be.',
				),
				array(
					'title'       => 'Manual operational overhead',
					'description' => 'Internal teams were spending too much time on follow-up work that should have been supported by clearer product logic and tooling.',
				),
				array(
					'title'       => 'Inconsistent delivery data',
					'description' => 'Reporting, communication, and operational decisions were limited by fragmented information across the workflow.',
				),
				array(
					'title'       => 'Difficult future scalability',
					'description' => 'The business needed a platform approach that would be easier to extend as process complexity and team requirements grew.',
				),
			);
		} elseif ( $is_fintech ) {
			$challenge_items = array(
				array(
					'title'       => 'Low onboarding clarity',
					'description' => 'Users were not getting enough product confidence during important setup steps, which created friction early in the journey.',
				),
				array(
					'title'       => 'Product structure that felt fragmented',
					'description' => 'Key information and actions were not presented with enough hierarchy, making the overall experience harder to trust and navigate.',
				),
				array(
					'title'       => 'Internal handling inefficiencies',
					'description' => 'Supporting the onboarding flow required avoidable manual work and clearer operational handoffs across the team.',
				),
				array(
					'title'       => 'Need for a more scalable product base',
					'description' => 'The next phase of the product required a stronger structure for future features, workflow expansion, and platform evolution.',
				),
			);
		} else {
			$challenge_items = array(
				array(
					'title'       => 'Experience friction in critical journeys',
					'description' => 'Important user and admin flows needed to be simplified so the product could support business goals more reliably.',
				),
				array(
					'title'       => 'Disconnected systems and handoffs',
					'description' => 'The previous setup created unnecessary context-switching, manual coordination, and operational drag behind the interface.',
				),
				array(
					'title'       => 'Hard-to-maintain technical structure',
					'description' => 'The delivery model needed a cleaner foundation that would be easier to improve, support, and extend after launch.',
				),
				array(
					'title'       => 'Scale readiness concerns',
					'description' => 'Future features and growth plans depended on a platform that could support change without compounding complexity.',
				),
			);
		}

		$goals = array(
			array(
				'title'       => 'Improve user experience',
				'description' => 'Make core journeys easier to understand, complete, and manage across the product lifecycle.',
			),
			array(
				'title'       => 'Modernize delivery foundations',
				'description' => 'Reduce technical drag and support a cleaner, more maintainable platform structure.',
			),
			array(
				'title'       => 'Streamline internal workflows',
				'description' => 'Cut down avoidable manual effort and give teams stronger visibility into the work they manage every day.',
			),
			array(
				'title'       => 'Support scalability',
				'description' => 'Prepare the product for new modules, integrations, and operational complexity without forcing a full rebuild later.',
			),
			array(
				'title'       => 'Align product and business outcomes',
				'description' => 'Keep the solution tied to delivery quality, adoption confidence, and the next stage of business growth.',
			),
		);

		$solution_paragraphs = array(
			'The solution began with a focused discovery and planning phase to map the most important user journeys, operational friction points, and delivery dependencies. That allowed the team to prioritize the work in the right order instead of treating UX, engineering, and process needs as separate tracks.',
			sprintf(
				'From there, the delivery combined product thinking, interface refinement, engineering execution, and integration planning around a %1$s implementation model. The goal was to make %2$s workflows clearer for users and easier for internal teams to support, while keeping the platform stable enough for future change.',
				strtolower( $platform ),
				strtolower( $industry )
			),
			'The engagement was structured as a practical roadmap, balancing visible improvements with the technical work required underneath. That meant the business could move toward a better product experience and stronger operating model without losing control of quality, release confidence, or longer-term maintainability.',
		);

		$solution_pillars = array(
			array(
				'title'       => 'Discovery and prioritization',
				'description' => 'Clarified the right sequence for UX, engineering, and business-critical improvements.',
			),
			array(
				'title'       => 'Experience and workflow design',
				'description' => 'Simplified key journeys for both customer-facing and internal operational use cases.',
			),
			array(
				'title'       => 'Engineering, integration, and launch readiness',
				'description' => 'Built a cleaner technical base with release planning and support considerations included from the start.',
			),
		);

		if ( $is_retail ) {
			$features = array(
				array(
					'title'       => 'Omnichannel journey improvements',
					'description' => 'Refined the experience across important browsing, engagement, and retention touchpoints so the platform felt more coherent end to end.',
				),
				array(
					'title'       => 'Mobile-first interface refinement',
					'description' => 'Improved layout hierarchy and task flow to support better usability across the devices most important to the audience.',
				),
				array(
					'title'       => 'Admin-side merchandising controls',
					'description' => 'Created a cleaner structure for handling updates, campaigns, and product-related operations without unnecessary friction.',
				),
				array(
					'title'       => 'Connected operational workflows',
					'description' => 'Reduced fragmented handoffs by organizing the supporting data and process flows around clearer execution paths.',
				),
				array(
					'title'       => 'Performance and readiness improvements',
					'description' => 'Addressed underlying quality and stability needs so the platform would be easier to improve and scale over time.',
				),
				array(
					'title'       => 'Launch and optimization support',
					'description' => 'Prepared the rollout with QA, coordination, and a clearer path for post-launch iteration.',
				),
			);
		} elseif ( $is_logistics ) {
			$features = array(
				array(
					'title'       => 'Field workflow dashboard',
					'description' => 'Created a clearer working environment for status updates, coordination, and activity visibility across the delivery process.',
				),
				array(
					'title'       => 'Operational status tracking',
					'description' => 'Brought essential data points into a cleaner structure so teams could understand progress and blockers faster.',
				),
				array(
					'title'       => 'Role-aware team interactions',
					'description' => 'Supported more practical day-to-day collaboration by organizing information around how different teams actually work.',
				),
				array(
					'title'       => 'Reporting and visibility layer',
					'description' => 'Improved the way progress, updates, and decisions could be reviewed without depending on fragmented tools.',
				),
				array(
					'title'       => 'Integration-ready platform logic',
					'description' => 'Prepared the foundation for connected systems, cleaner data flows, and future process expansion.',
				),
				array(
					'title'       => 'Delivery QA and rollout planning',
					'description' => 'Rounded out the implementation with launch preparation, validation, and support-ready structure.',
				),
			);
		} elseif ( $is_fintech ) {
			$features = array(
				array(
					'title'       => 'Digital onboarding flow redesign',
					'description' => 'Reworked the most important setup stages so product value, clarity, and trust were stronger from the first interaction.',
				),
				array(
					'title'       => 'Client portal experience layer',
					'description' => 'Organized account-facing information into a more coherent workspace that supported confidence and easier task completion.',
				),
				array(
					'title'       => 'Internal review and handoff logic',
					'description' => 'Improved the way onboarding information moved between product, operations, and support steps behind the scenes.',
				),
				array(
					'title'       => 'Structured content and messaging hierarchy',
					'description' => 'Clarified what users needed to know, when they needed it, and how the experience should reinforce product trust.',
				),
				array(
					'title'       => 'Integration and platform readiness',
					'description' => 'Kept the implementation ready for future platform growth, system connections, and additional feature layers.',
				),
				array(
					'title'       => 'Quality assurance and release planning',
					'description' => 'Supported the rollout with validation, issue review, and a cleaner foundation for future optimization.',
				),
			);
		} else {
			$features = array(
				array(
					'title'       => 'Core experience redesign',
					'description' => 'Improved the structure of key journeys so users could move through the product with less friction and more confidence.',
				),
				array(
					'title'       => 'Workflow and admin improvements',
					'description' => 'Reduced day-to-day operational drag through more practical controls, clearer states, and better internal visibility.',
				),
				array(
					'title'       => 'Integration support layer',
					'description' => 'Prepared the product for connected systems, data flows, and business processes that matter beyond the interface alone.',
				),
				array(
					'title'       => 'Responsive product readiness',
					'description' => 'Kept the experience usable and consistent across the screen sizes and contexts that matter most to the audience.',
				),
				array(
					'title'       => 'Platform quality improvements',
					'description' => 'Focused on maintainability, stability, and technical confidence so future work would be easier to plan and deliver.',
				),
				array(
					'title'       => 'Launch support and follow-through',
					'description' => 'Included validation, release coordination, and the foundations for ongoing optimization after launch.',
				),
			);
		}

		$tech_stack = array(
			array(
				'label' => 'Platform',
				'items' => array_filter( array( $platform, $project_type ) ),
			),
			array(
				'label' => 'Frontend',
				'items' => $is_mobile
					? array( 'Mobile-first UI architecture', 'Component-driven interface patterns' )
					: array( 'Responsive interface layer', 'Component-driven frontend patterns' ),
			),
			array(
				'label' => 'Backend',
				'items' => array( 'PHP application services', 'API-ready business logic' ),
			),
			array(
				'label' => 'Database',
				'items' => array( 'MySQL data layer' ),
			),
			array(
				'label' => 'Integrations',
				'items' => array( 'REST API', 'CRM / ERP handoffs', 'Notification workflows' ),
			),
			array(
				'label' => 'Hosting / Infrastructure',
				'items' => array( 'AWS-ready deployment', 'Container-friendly setup', 'Monitoring-conscious release flow' ),
			),
			array(
				'label' => 'Analytics / Tracking',
				'items' => array( 'GA4', 'GTM', 'Custom event tracking' ),
			),
		);

		$result_cards = array(
			array(
				'value' => $is_retail ? 'Stronger' : ( $is_logistics ? 'Better' : ( $is_fintech ? 'Clearer' : 'Stronger' ) ),
				'label' => $is_retail ? 'conversion readiness' : ( $is_logistics ? 'operational visibility' : ( $is_fintech ? 'onboarding clarity' : 'delivery confidence' ) ),
				'copy'  => 'The delivery created a more dependable foundation for the next stage of product improvement and business growth.',
			),
			array(
				'value' => 'Faster',
				'label' => $is_logistics ? 'team coordination' : 'workflow execution',
				'copy'  => 'Teams could move through important tasks with fewer blockers, less manual overhead, and better day-to-day flow.',
			),
			array(
				'value' => 'Cleaner',
				'label' => $is_fintech ? 'user trust signals' : 'core user journeys',
				'copy'  => 'Important product moments were clarified so the experience was easier to understand, manage, and improve over time.',
			),
			array(
				'value' => 'Scalable',
				'label' => 'platform foundation',
				'copy'  => 'The technical and operational base is better prepared for future features, integrations, and broader delivery needs.',
			),
		);

		$impact_cards = array(
			array(
				'title'       => 'Improved product confidence',
				'description' => 'The overall solution gave users and internal teams a more dependable experience around the work that matters most.',
			),
			array(
				'title'       => 'Reduced avoidable complexity',
				'description' => 'Cleaner flows, better structure, and stronger handoffs helped lower the friction created by the previous setup.',
			),
			array(
				'title'       => 'Better readiness for change',
				'description' => 'The final delivery was shaped to support future improvements without forcing the business back into reactive rebuild cycles.',
			),
		);

		$custom_hero_highlights = ethnic_case_studies_parse_lines( get_post_meta( $post->ID, ethnic_case_studies_content_meta_key( 'hero_highlights' ), true ) );
		$custom_overview_heading = ethnic_case_studies_single_custom_text( $post->ID, 'overview_heading' );
		$custom_overview_paragraphs = ethnic_case_studies_parse_paragraphs( get_post_meta( $post->ID, ethnic_case_studies_content_meta_key( 'overview_paragraphs' ), true ) );
		$custom_overview_facts = ethnic_case_studies_single_custom_rows( $post->ID, 'overview_facts', array( 'label', 'value' ) );
		$custom_challenge_heading = ethnic_case_studies_single_custom_text( $post->ID, 'challenge_heading' );
		$custom_challenge_intro = ethnic_case_studies_single_custom_text( $post->ID, 'challenge_intro' );
		$custom_challenges = ethnic_case_studies_single_custom_rows( $post->ID, 'challenges', array( 'title', 'description' ) );
		$custom_goals_heading = ethnic_case_studies_single_custom_text( $post->ID, 'goals_heading' );
		$custom_goals = ethnic_case_studies_single_custom_rows( $post->ID, 'goals', array( 'title', 'description' ) );
		$custom_solution_heading = ethnic_case_studies_single_custom_text( $post->ID, 'solution_heading' );
		$custom_solution_paragraphs = ethnic_case_studies_parse_paragraphs( get_post_meta( $post->ID, ethnic_case_studies_content_meta_key( 'solution_paragraphs' ), true ) );
		$custom_solution_pillars = ethnic_case_studies_single_custom_rows( $post->ID, 'solution_pillars', array( 'title', 'description' ) );
		$custom_features_heading = ethnic_case_studies_single_custom_text( $post->ID, 'features_heading' );
		$custom_features = ethnic_case_studies_single_custom_rows( $post->ID, 'features', array( 'title', 'description' ) );
		$custom_stack_heading = ethnic_case_studies_single_custom_text( $post->ID, 'tech_stack_heading' );
		$custom_tech_stack = ethnic_case_studies_single_custom_tech_stack( $post->ID );
		$custom_timeline_heading = ethnic_case_studies_single_custom_text( $post->ID, 'timeline_heading' );
		$custom_timeline = ethnic_case_studies_single_custom_rows( $post->ID, 'timeline', array( 'title', 'description' ) );
		$custom_engagement_summary = ethnic_case_studies_single_custom_rows( $post->ID, 'engagement_summary', array( 'label', 'value' ) );
		$custom_results_heading = ethnic_case_studies_single_custom_text( $post->ID, 'results_heading' );
		$custom_result_cards = ethnic_case_studies_single_custom_rows( $post->ID, 'result_cards', array( 'value', 'label', 'copy' ) );
		$custom_impact_cards = ethnic_case_studies_single_custom_rows( $post->ID, 'impact_cards', array( 'title', 'description' ) );
		$custom_gallery_heading = ethnic_case_studies_single_custom_text( $post->ID, 'gallery_heading' );
		$custom_gallery = ethnic_case_studies_single_custom_gallery( $post->ID );
		$custom_related_heading = ethnic_case_studies_single_custom_text( $post->ID, 'related_services_heading' );
		$custom_related_services = ethnic_case_studies_single_custom_related_services( $post->ID );
		$custom_back_link_label = ethnic_case_studies_single_custom_text( $post->ID, 'back_link_label' );
		$custom_hero_eyebrow = ethnic_case_studies_single_custom_text( $post->ID, 'hero_eyebrow' );
		$custom_hero_overlay_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'hero_overlay_kicker' );
		$custom_hero_primary_label = ethnic_case_studies_single_custom_text( $post->ID, 'hero_primary_label' );
		$custom_hero_secondary_label = ethnic_case_studies_single_custom_text( $post->ID, 'hero_secondary_label' );
		$custom_overview_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'overview_kicker' );
		$custom_overview_card_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'overview_card_kicker' );
		$custom_challenge_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'challenge_kicker' );
		$custom_goals_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'goals_kicker' );
		$custom_solution_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'solution_kicker' );
		$custom_features_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'features_kicker' );
		$custom_tech_stack_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'tech_stack_kicker' );
		$custom_timeline_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'timeline_kicker' );
		$custom_engagement_card_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'engagement_card_kicker' );
		$custom_results_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'results_kicker' );
		$custom_gallery_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'gallery_kicker' );
		$custom_related_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'related_kicker' );
		$custom_related_link_label = ethnic_case_studies_single_custom_text( $post->ID, 'related_link_label' );
		$custom_cta_kicker = ethnic_case_studies_single_custom_text( $post->ID, 'cta_kicker' );
		$custom_cta_heading = ethnic_case_studies_single_custom_text( $post->ID, 'cta_heading' );
		$custom_cta_copy = ethnic_case_studies_single_custom_text( $post->ID, 'cta_copy' );
		$custom_cta_primary_label = ethnic_case_studies_single_custom_text( $post->ID, 'cta_primary_label' );
		$custom_cta_secondary_label = ethnic_case_studies_single_custom_text( $post->ID, 'cta_secondary_label' );

		if ( '' !== $custom_overview_heading ) {
			$overview_heading = $custom_overview_heading;
		}

		if ( ! empty( $custom_overview_paragraphs ) ) {
			$overview_paragraphs = $custom_overview_paragraphs;
		}

		if ( ! empty( $custom_overview_facts ) ) {
			$overview_facts = $custom_overview_facts;
		} else {
			$overview_facts = array(
				array(
					'label' => 'Industry',
					'value' => $industry,
				),
				array(
					'label' => 'Company Type',
					'value' => $company_type,
				),
				array(
					'label' => 'Services Delivered',
					'value' => implode( ', ', array_filter( $payload['services'] ) ),
				),
				array(
					'label' => 'Engagement Type',
					'value' => $engagement_model,
				),
			);
		}

		if ( '' !== $custom_challenge_heading ) {
			$challenge_heading = $custom_challenge_heading;
		}

		if ( '' !== $custom_challenge_intro ) {
			$challenge_intro = $custom_challenge_intro;
		} else {
			$challenge_intro = 'The project was initiated to remove the barriers that were slowing usability, delivery quality, and long-term business confidence.';
		}

		if ( ! empty( $custom_challenges ) ) {
			$challenge_items = $custom_challenges;
		}

		if ( '' !== $custom_goals_heading ) {
			$goals_heading = $custom_goals_heading;
		}

		if ( ! empty( $custom_goals ) ) {
			$goals = $custom_goals;
		}

		if ( '' !== $custom_solution_heading ) {
			$solution_heading = $custom_solution_heading;
		}

		if ( ! empty( $custom_solution_paragraphs ) ) {
			$solution_paragraphs = $custom_solution_paragraphs;
		}

		if ( ! empty( $custom_solution_pillars ) ) {
			$solution_pillars = $custom_solution_pillars;
		}

		if ( '' !== $custom_features_heading ) {
			$features_heading = $custom_features_heading;
		}

		if ( ! empty( $custom_features ) ) {
			$features = $custom_features;
		}

		if ( '' !== $custom_stack_heading ) {
			$tech_stack_heading = $custom_stack_heading;
		}

		if ( ! empty( $custom_tech_stack ) ) {
			$tech_stack = $custom_tech_stack;
		}

		if ( '' !== $custom_timeline_heading ) {
			$timeline_heading = $custom_timeline_heading;
		}

		if ( ! empty( $custom_timeline ) ) {
			$timeline = $custom_timeline;
		}

		if ( ! empty( $custom_engagement_summary ) ) {
			$engagement_summary = $custom_engagement_summary;
		} else {
			$engagement_summary = array(
				array(
					'label' => 'Timeline',
					'value' => $timeline_window,
				),
				array(
					'label' => 'Engagement Model',
					'value' => $engagement_model,
				),
				array(
					'label' => 'Collaboration',
					'value' => 'Weekly planning, review cycles, and shared delivery checkpoints',
				),
				array(
					'label' => 'Support',
					'value' => 'Launch coordination plus optimization-ready backlog planning',
				),
			);
		}

		if ( '' !== $custom_results_heading ) {
			$results_heading = $custom_results_heading;
		}

		if ( ! empty( $custom_result_cards ) ) {
			$result_cards = $custom_result_cards;
		}

		if ( ! empty( $custom_impact_cards ) ) {
			$impact_cards = $custom_impact_cards;
		}

		if ( '' !== $custom_gallery_heading ) {
			$gallery_heading = $custom_gallery_heading;
		}

		$gallery = ! empty( $custom_gallery ) ? $custom_gallery : ethnic_case_studies_single_gallery_items( $post->ID, $payload );

		if ( '' !== $custom_related_heading ) {
			$related_heading = $custom_related_heading;
		}

		$related_services = ! empty( $custom_related_services ) ? $custom_related_services : ethnic_case_studies_related_services( $payload );

		if ( '' !== $custom_hero_primary_label ) {
			$hero_primary_label = $custom_hero_primary_label;
		}

		if ( '' !== $custom_hero_secondary_label ) {
			$hero_secondary_label = $custom_hero_secondary_label;
		}

		if ( '' !== $custom_back_link_label ) {
			$back_link_label = $custom_back_link_label;
		}

		if ( '' !== $custom_hero_eyebrow ) {
			$hero_eyebrow = $custom_hero_eyebrow;
		}

		if ( '' !== $custom_hero_overlay_kicker ) {
			$hero_overlay_kicker = $custom_hero_overlay_kicker;
		}

		if ( '' !== $custom_overview_kicker ) {
			$overview_kicker = $custom_overview_kicker;
		}

		if ( '' !== $custom_overview_card_kicker ) {
			$overview_card_kicker = $custom_overview_card_kicker;
		}

		if ( '' !== $custom_challenge_kicker ) {
			$challenge_kicker = $custom_challenge_kicker;
		}

		if ( '' !== $custom_goals_kicker ) {
			$goals_kicker = $custom_goals_kicker;
		}

		if ( '' !== $custom_solution_kicker ) {
			$solution_kicker = $custom_solution_kicker;
		}

		if ( '' !== $custom_features_kicker ) {
			$features_kicker = $custom_features_kicker;
		}

		if ( '' !== $custom_tech_stack_kicker ) {
			$tech_stack_kicker = $custom_tech_stack_kicker;
		}

		if ( '' !== $custom_timeline_kicker ) {
			$timeline_kicker = $custom_timeline_kicker;
		}

		if ( '' !== $custom_engagement_card_kicker ) {
			$engagement_card_kicker = $custom_engagement_card_kicker;
		}

		if ( '' !== $custom_results_kicker ) {
			$results_kicker = $custom_results_kicker;
		}

		if ( '' !== $custom_gallery_kicker ) {
			$gallery_kicker = $custom_gallery_kicker;
		}

		if ( '' !== $custom_related_kicker ) {
			$related_kicker = $custom_related_kicker;
		}

		if ( '' !== $custom_related_link_label ) {
			$related_link_label = $custom_related_link_label;
		}

		if ( '' !== $custom_cta_kicker ) {
			$cta_kicker = $custom_cta_kicker;
		}

		if ( '' !== $custom_cta_heading ) {
			$cta_heading = $custom_cta_heading;
		}

		if ( '' !== $custom_cta_copy ) {
			$cta_copy = $custom_cta_copy;
		}

		if ( '' !== $custom_cta_primary_label ) {
			$cta_primary_label = $custom_cta_primary_label;
		}

		if ( '' !== $custom_cta_secondary_label ) {
			$cta_secondary_label = $custom_cta_secondary_label;
		}

		$archive_url = ethnic_case_studies_archive_url();
		$archive_category = ethnic_case_studies_current_category_term();

		if ( ! ( $archive_category instanceof WP_Term ) ) {
			$archive_category = ethnic_case_studies_primary_category_term( $post );
		}

		if ( $archive_category instanceof WP_Term ) {
			$archive_url = ethnic_case_studies_category_archive_url( $archive_category );

			if ( ethnic_case_studies_is_app_archive_variant( $archive_category->slug ) ) {
				$back_link_label = 'Back to App Development Case Studies';
			} else {
				$back_link_label = 'Back to ' . ethnic_case_studies_text( $archive_category->name, 'Category' ) . ' Case Studies';
			}
		}

		if ( $is_app_related && ! ( $archive_category instanceof WP_Term ) ) {
			$archive_url     = ethnic_case_studies_archive_url( array(), 1, ethnic_case_studies_app_archive_variant() );
			$back_link_label = 'Back to App Development Case Studies';
		}

		$selected_logo_items = ethnic_case_studies_selected_logo_items( $post->ID );

		return array(
			'post_id'             => (int) $post->ID,
			'title'               => $payload['title'],
			'subtitle'            => $hero_subtitle,
			'client_name'         => $client_name,
			'service'             => $service,
			'platform'            => $platform,
			'industry'            => $industry,
			'project_type'        => $project_type,
			'metadata'            => array(
				array(
					'label' => 'Service',
					'value' => $service,
				),
				array(
					'label' => 'Platform',
					'value' => $platform,
				),
				array(
					'label' => 'Industry',
					'value' => $industry,
				),
				array(
					'label' => 'Project Type',
					'value' => $project_type,
				),
			),
			'hero_image_url'      => $hero_image_url,
			'hero_image_alt'      => $hero_image_alt,
			'hero_media_url'      => $hero_media_url,
			'hero_media_type'     => $hero_media_type,
			'hero_media_alt'      => $hero_media_alt,
			'hero_highlights'     => ! empty( $custom_hero_highlights ) ? $custom_hero_highlights : ethnic_case_studies_result_highlights( $post->ID ),
			'back_link_label'     => $back_link_label,
			'hero_eyebrow'        => $hero_eyebrow,
			'hero_overlay_kicker' => $hero_overlay_kicker,
			'hero_primary_label'  => $hero_primary_label,
			'hero_secondary_label' => $hero_secondary_label,
			'overview_kicker'     => $overview_kicker,
			'overview_heading'    => $overview_heading,
			'overview_card_kicker' => $overview_card_kicker,
			'overview_paragraphs' => $overview_paragraphs,
			'overview_facts'      => $overview_facts,
			'challenge_kicker'    => $challenge_kicker,
			'challenge_heading'   => $challenge_heading,
			'challenge_intro'     => $challenge_intro,
			'challenges'          => $challenge_items,
			'goals_kicker'        => $goals_kicker,
			'goals_heading'       => $goals_heading,
			'goals'               => $goals,
			'solution_kicker'     => $solution_kicker,
			'solution_heading'    => $solution_heading,
			'solution_paragraphs' => $solution_paragraphs,
			'solution_pillars'    => $solution_pillars,
			'features_kicker'     => $features_kicker,
			'features_heading'    => $features_heading,
			'features'            => $features,
			'tech_stack_kicker'   => $tech_stack_kicker,
			'tech_stack_heading'  => $tech_stack_heading,
			'tech_stack'          => $tech_stack,
			'tech_stack_items'    => ! empty( $selected_logo_items ) ? $selected_logo_items : ethnic_case_studies_prepare_tech_stack_items( $tech_stack ),
			'timeline_kicker'     => $timeline_kicker,
			'timeline_heading'    => $timeline_heading,
			'timeline'            => ! empty( $custom_timeline ) ? $custom_timeline : array(
				array(
					'title'       => 'Discovery',
					'description' => 'Clarified goals, business constraints, user needs, and the delivery priorities that would shape the roadmap.',
				),
				array(
					'title'       => 'Planning',
					'description' => 'Defined scope, phased sequencing, and the most practical route through the design and engineering work.',
				),
				array(
					'title'       => 'Design',
					'description' => 'Refined key journeys, structure, and interface hierarchy so the product direction was easier to validate early.',
				),
				array(
					'title'       => 'Development',
					'description' => 'Built the core product logic, supporting workflows, and platform improvements that delivered the main solution.',
				),
				array(
					'title'       => 'QA',
					'description' => 'Validated flows, edge cases, and release readiness so the rollout could happen with stronger confidence.',
				),
				array(
					'title'       => 'Launch',
					'description' => 'Coordinated the release with a focus on stability, visibility, and practical handoff for the internal team.',
				),
				array(
					'title'       => 'Ongoing Support',
					'description' => 'Prepared the platform for optimization, further iteration, and future roadmap priorities after the initial release.',
				),
			),
			'engagement_card_kicker' => $engagement_card_kicker,
			'engagement_summary'  => $engagement_summary,
			'results_kicker'      => $results_kicker,
			'results_heading'     => $results_heading,
			'result_cards'        => $result_cards,
			'impact_cards'        => $impact_cards,
			'gallery_kicker'      => $gallery_kicker,
			'gallery_heading'     => $gallery_heading,
			'gallery'             => $gallery,
			'editor_content'      => ethnic_case_studies_rendered_post_content( $post->ID ),
			'related_kicker'      => $related_kicker,
			'related_heading'     => $related_heading,
			'related_services'    => $related_services,
			'related_link_label'  => $related_link_label,
			'cta_kicker'          => $cta_kicker,
			'cta_heading'         => $cta_heading,
			'cta_copy'            => $cta_copy,
			'cta_primary_label'   => $cta_primary_label,
			'cta_secondary_label' => $cta_secondary_label,
			'archive_url'         => $archive_url,
			'contact_project_url' => ethnic_case_studies_contact_url( array( 'intent' => 'similar-project' ) ),
			'contact_team_url'    => ethnic_case_studies_contact_url( array( 'intent' => 'consultation' ) ),
			'contact_quote_url'   => ethnic_case_studies_contact_url( array( 'intent' => 'quote' ) ),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_demo_post_ids' ) ) {
	function ethnic_case_studies_demo_post_ids() {
		static $post_ids = null;

		if ( null !== $post_ids ) {
			return $post_ids;
		}

		$post_ids = array();

		$ids = get_posts(
			array(
				'post_type'              => ETHNIC_CASE_STUDIES_POST_TYPE,
				'post_status'            => 'publish',
				'posts_per_page'         => -1,
				'fields'                 => 'ids',
				'ignore_sticky_posts'    => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'no_found_rows'          => true,
			)
		);

		foreach ( $ids as $post_id ) {
			if ( ethnic_case_studies_is_demo_post( $post_id ) ) {
				$post_ids[] = (int) $post_id;
			}
		}

		return $post_ids;
	}
}

if ( ! function_exists( 'ethnic_case_studies_build_query_args' ) ) {
	function ethnic_case_studies_build_query_args( $filters = array(), $args = array() ) {
		$definitions = ethnic_case_studies_filter_definitions();
		$tax_query   = array();
		$defaults    = array(
			'post_type'           => ETHNIC_CASE_STUDIES_POST_TYPE,
			'post_status'         => 'publish',
			'ignore_sticky_posts' => true,
			'orderby'             => array(
				'menu_order' => 'ASC',
				'date'       => 'DESC',
			),
		);

		foreach ( $definitions as $key => $definition ) {
			if ( empty( $filters[ $key ] ) ) {
				continue;
			}

			$tax_query[] = array(
				'taxonomy' => $definition['taxonomy'],
				'field'    => 'slug',
				'terms'    => ethnic_case_studies_normalize_requested_slugs( $filters[ $key ] ),
				'operator' => 'IN',
			);
		}

		if ( count( $tax_query ) > 1 ) {
			$defaults['tax_query'] = array_merge( array( 'relation' => 'AND' ), $tax_query );
		} elseif ( 1 === count( $tax_query ) ) {
			$defaults['tax_query'] = $tax_query;
		}

		if ( ! empty( $args['tax_query'] ) ) {
			$existing_tax_query = (array) $args['tax_query'];
			unset( $args['tax_query'] );

			if ( ! empty( $defaults['tax_query'] ) ) {
				$default_tax_query = (array) $defaults['tax_query'];
				unset( $defaults['tax_query'] );

				$args['tax_query'] = array_merge(
					array( 'relation' => 'AND' ),
					isset( $default_tax_query['relation'] ) ? array_values( array_filter( $default_tax_query, 'is_array' ) ) : $default_tax_query,
					isset( $existing_tax_query['relation'] ) ? array_values( array_filter( $existing_tax_query, 'is_array' ) ) : $existing_tax_query
				);
			} else {
				$args['tax_query'] = $existing_tax_query;
			}
		}

		$exclude_ids = ethnic_case_studies_demo_post_ids();

		if ( ! empty( $exclude_ids ) ) {
			$defaults['post__not_in'] = $exclude_ids;
		}

		if ( ! empty( $args['post__not_in'] ) ) {
			$args['post__not_in'] = array_values(
				array_unique(
					array_merge(
						! empty( $defaults['post__not_in'] ) ? $defaults['post__not_in'] : array(),
						array_map( 'intval', (array) $args['post__not_in'] )
					)
				)
			);
			unset( $defaults['post__not_in'] );
		}

		return array_merge( $defaults, $args );
	}
}

if ( ! function_exists( 'ethnic_case_studies_app_archive_posts' ) ) {
	function ethnic_case_studies_app_archive_posts() {
		static $posts = null;

		if ( null !== $posts ) {
			return $posts;
		}

		$posts = array();
		$items = get_posts(
			ethnic_case_studies_build_query_args(
				array(),
				array(
					'posts_per_page'         => -1,
					'update_post_meta_cache' => true,
					'update_post_term_cache' => true,
					'no_found_rows'          => true,
				)
			)
		);

		foreach ( $items as $post ) {
			if ( $post instanceof WP_Post && ethnic_case_studies_is_app_related_post( $post ) ) {
				$posts[] = $post;
			}
		}

		return $posts;
	}
}

if ( ! function_exists( 'ethnic_case_studies_archive_variant_config' ) ) {
	function ethnic_case_studies_archive_variant_config( $variant = '' ) {
		$variant    = sanitize_title( (string) $variant );
		$category_term = ethnic_case_studies_category_term_by_slug( $variant );
		$contact_url = ethnic_case_studies_contact_url( array( 'intent' => 'consultation' ) );

		$defaults = array(
			'variant'                  => '',
			'archive_url'              => ethnic_case_studies_archive_url(),
			'hero_eyebrow'             => 'Case Studies',
			'hero_title'               => 'Case Studies',
			'hero_copy'                => 'Browse real client success stories and solution-led delivery examples that show how we solve complex business challenges through strategy, design, development, integrations, and scalable digital execution.',
			'hero_primary_label'       => 'Start Your Project',
			'hero_primary_url'         => ethnic_case_studies_contact_url( array( 'intent' => 'project' ) ),
			'hero_secondary_label'     => 'Talk to Our Team',
			'hero_secondary_url'       => $contact_url,
			'hero_points'              => array(
				'Real client success stories with outcome-focused delivery context',
				'eCommerce development projects, app development case studies, and custom solution builds',
				'Strategy, design, development, integration, and growth support in one delivery model',
			),
			'hero_badge_primary'       => 'Digital project portfolio',
			'hero_badge_secondary'     => 'Strategy to scale',
			'intro_kicker'             => 'Why This Page Matters',
			'intro_heading'            => 'A central case studies hub built for credibility, SEO, and faster shortlisting.',
			'intro_paragraphs'         => array(
				'These case studies give prospects a clearer view of how we approach digital project portfolio work, from business challenge framing to execution quality and post-launch stability. They help teams compare technical capability, delivery thinking, and solution fit before starting a conversation.',
				'Across eCommerce development projects, app development case studies, web platforms, and integration-led builds, this hub is designed to make browsing easier while reinforcing trust through real project context, cleaner categorization, and stronger paths into deeper proof.',
			),
			'intro_highlights'         => array(
				array(
					'title' => 'Multi-industry experience',
					'copy'  => 'Retail, logistics, fintech, healthcare, and growing B2B delivery contexts.',
				),
				array(
					'title' => 'End-to-end delivery',
					'copy'  => 'Strategy, UX, development, integrations, QA, launch planning, and support.',
				),
				array(
					'title' => 'Results-focused execution',
					'copy'  => 'Built around business outcomes, clearer workflows, and scalable platform decisions.',
				),
			),
			'featured_kicker'          => 'Featured Projects',
			'featured_heading'         => 'Selected case studies with stronger delivery impact and clearer business outcomes.',
			'listing_kicker'           => 'All Projects',
			'listing_heading'          => 'Browse case studies by service, platform, and industry.',
			'listing_heading_filtered' => 'Matching case studies.',
			'show_filters'             => true,
			'empty_title'              => 'No case studies found',
			'empty_copy'               => 'We could not find any case studies in this view yet. Return to the full archive to browse everything currently published.',
			'empty_button_label'       => 'View All Case Studies',
			'cta_kicker'               => 'Start The Conversation',
			'cta_heading'              => 'Have a project in mind?',
			'cta_copy'                 => 'Let’s discuss your product, platform, or modernization roadmap and shape the next delivery step together.',
			'cta_primary_label'        => 'Book a Consultation',
			'cta_primary_url'          => $contact_url,
			'cta_secondary_label'      => 'Get a Free Quote',
			'cta_secondary_url'        => ethnic_case_studies_contact_url( array( 'intent' => 'quote' ) ),
			'seo_title'                => ethnic_case_studies_archive_seo_title(),
			'seo_description'          => ethnic_case_studies_archive_meta_description(),
			'page_title'               => 'Case Studies',
		);

		if ( '' === $variant || ! ( $category_term instanceof WP_Term ) ) {
			return $defaults;
		}

		if ( ethnic_case_studies_is_app_archive_variant( $variant ) ) {
			return array_merge(
				$defaults,
				array(
					'variant'                  => ethnic_case_studies_app_archive_variant(),
					'archive_url'              => ethnic_case_studies_archive_url( array(), 1, ethnic_case_studies_app_archive_variant() ),
					'hero_eyebrow'             => 'App Development Case Studies',
					'hero_title'               => 'App Development Case Studies',
					'hero_copy'                => 'Explore real mobile app, web app, and custom software success stories that show how we turn product ideas, workflow challenges, and platform goals into launch-ready digital experiences.',
					'hero_points'              => array(
						'Mobile and web app success stories',
						'Scalable custom app solutions',
						'From strategy to launch and support',
					),
					'hero_badge_primary'       => 'App product showcase',
					'hero_badge_secondary'     => 'From idea to launch',
					'intro_kicker'             => 'App Delivery Focus',
					'intro_heading'            => 'A focused case study library for mobile apps, web apps, SaaS products, and custom software builds.',
					'intro_paragraphs'         => array(
						'These app development case studies focus specifically on product delivery work such as mobile apps, web apps, internal tools, SaaS platforms, and cross-platform builds. They show how execution quality, architecture choices, and launch planning come together in real projects.',
						'The goal is to make it easier to review real-world app problem solving, product thinking, and measurable outcomes before starting a similar engagement with our team.',
					),
					'intro_highlights'         => array(
						array(
							'title' => 'Mobile and web product delivery',
							'copy'  => 'iOS, Android, Flutter, React Native, web app, and custom platform examples.',
						),
						array(
							'title' => 'Execution built around launch',
							'copy'  => 'Discovery, UX, engineering, QA, rollout planning, and post-launch support.',
						),
						array(
							'title' => 'Outcome-focused app projects',
							'copy'  => 'Built around usability, adoption, workflow improvements, and scalable technical foundations.',
						),
					),
					'featured_kicker'          => 'Featured App Projects',
					'featured_heading'         => 'Selected app development case studies spanning mobile products, workflow platforms, and custom software delivery.',
					'listing_kicker'           => 'App Projects',
					'listing_heading'          => 'Browse app development case studies across mobile apps, web apps, SaaS products, and internal platforms.',
					'listing_heading_filtered' => 'Matching app development case studies.',
					'show_filters'             => false,
					'empty_title'              => 'No app development case studies found',
					'empty_copy'               => 'We could not find any app-focused case studies in this view yet. Return to the full archive to explore all available work.',
					'empty_button_label'       => 'View All Case Studies',
					'cta_heading'              => 'Planning a Custom App Project?',
					'cta_copy'                 => 'Let’s discuss your mobile app, web app, SaaS product, internal tool, cross-platform build, or app modernization roadmap and shape the right next step together.',
					'cta_primary_label'        => 'Start Your Project',
					'cta_primary_url'          => ethnic_case_studies_contact_url( array( 'intent' => 'project' ) ),
					'cta_secondary_label'      => 'Book a Free Consultation',
					'cta_secondary_url'        => $contact_url,
					'seo_title'                => 'App Development Case Studies | Mobile, Web & Custom App Success Stories',
					'seo_description'          => 'Explore app development case studies across mobile apps, web apps, SaaS platforms, Flutter, React Native, iOS, Android, and custom software projects.',
					'page_title'               => 'App Development Case Studies',
				)
			);
		}

		$term_name = ethnic_case_studies_text( $category_term->name, 'Case Study Category' );
		$term_copy = ethnic_case_studies_text( $category_term->description );

		return array_merge(
			$defaults,
			array(
				'variant'                  => $category_term->slug,
				'archive_url'              => ethnic_case_studies_category_archive_url( $category_term ),
				'hero_eyebrow'             => 'Case Study Category',
				'hero_title'               => $term_name . ' Case Studies',
				'hero_copy'                => '' !== $term_copy ? $term_copy : sprintf( 'Explore %s-related case studies that show how we solve delivery, product, and platform challenges through clearer execution, practical engineering, and business-focused outcomes.', strtolower( $term_name ) ),
				'hero_points'              => array(
					'Category-specific client success stories',
					'Real project delivery context and outcomes',
					'Built to help teams shortlist relevant work faster',
				),
				'hero_badge_primary'       => $term_name . ' delivery examples',
				'hero_badge_secondary'     => 'Focused proof for buyers',
				'intro_kicker'             => 'Category Overview',
				'intro_heading'            => $term_name . ' projects collected in one focused browsing experience.',
				'intro_paragraphs'         => array(
					sprintf( 'This category page brings together case studies tagged under %s so teams can review closely related delivery examples without scanning the full archive.', $term_name ),
					sprintf( 'Use it to compare execution quality, business context, and solution fit across projects that connect naturally to %s work.', strtolower( $term_name ) ),
				),
				'intro_highlights'         => array(
					array(
						'title' => 'Focused proof',
						'copy'  => 'Projects grouped by category so visitors can find relevant evidence faster.',
					),
					array(
						'title' => 'Comparable delivery stories',
						'copy'  => 'Challenge, solution, and outcome context shown across similar work.',
					),
					array(
						'title' => 'Clear next step',
						'copy'  => 'A stronger path from proof to conversation when the fit looks right.',
					),
				),
				'featured_kicker'          => 'Featured ' . $term_name . ' Projects',
				'featured_heading'         => 'Selected case studies from this category with stronger delivery context and clearer business outcomes.',
				'listing_kicker'           => $term_name . ' Projects',
				'listing_heading'          => 'Browse case studies in this category.',
				'listing_heading_filtered' => 'Matching case studies in this category.',
				'empty_title'              => 'No case studies found in this category',
				'empty_copy'               => 'There are no case studies available in this category yet. Return to the full archive to browse everything currently published.',
				'empty_button_label'       => 'View All Case Studies',
				'cta_heading'              => 'Looking for a similar delivery partner?',
				'cta_copy'                 => 'Let’s discuss your product, platform, workflow, or modernization goals and shape the right next step together.',
				'cta_primary_label'        => 'Book a Consultation',
				'cta_secondary_url'        => $contact_url,
				'seo_title'                => $term_name . ' Case Studies | Client Success Stories & Project Outcomes',
				'seo_description'          => '' !== $term_copy ? wp_trim_words( $term_copy, 26, '…' ) : sprintf( 'Explore %s case studies and client success stories with project context, delivery outcomes, and solution-led implementation examples.', strtolower( $term_name ) ),
				'page_title'               => $term_name . ' Case Studies',
			)
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_archive_context' ) ) {
	function ethnic_case_studies_archive_context() {
		static $context = null;

		if ( null !== $context ) {
			return $context;
		}

		$variant       = ethnic_case_studies_current_archive_variant();
		$category_term = ethnic_case_studies_current_category_term();
		$config        = ethnic_case_studies_archive_variant_config( $variant );
		$filters       = ethnic_case_studies_is_app_archive_variant( $variant ) ? array(
			'service'  => array(),
			'platform' => array(),
			'industry' => array(),
		) : ethnic_case_studies_selected_filters();
		$paged         = max( 1, (int) get_query_var( 'paged' ) );
		$featured_meta = array(
			array(
				'key'     => ethnic_case_studies_featured_meta_key(),
				'value'   => '1',
				'compare' => '=',
			),
		);

		$featured_posts = array();
		$grid_query     = null;

		$filter_terms = array();

		if ( ethnic_case_studies_is_app_archive_variant( $variant ) ) {
			if ( $category_term instanceof WP_Term ) {
				$app_posts = get_posts(
					ethnic_case_studies_build_query_args(
						array(),
						array(
							'posts_per_page'         => -1,
							'tax_query'              => array(
								array(
									'taxonomy' => ethnic_case_studies_taxonomies()['category'],
									'field'    => 'slug',
									'terms'    => array( $category_term->slug ),
									'operator' => 'IN',
								),
							),
							'update_post_meta_cache' => true,
							'update_post_term_cache' => true,
							'no_found_rows'          => true,
						)
					)
				);

				if ( empty( $app_posts ) ) {
					$app_posts = ethnic_case_studies_app_archive_posts();
				}
			} else {
				$app_posts = ethnic_case_studies_app_archive_posts();
			}

			$app_post_ids  = array_map( 'intval', wp_list_pluck( $app_posts, 'ID' ) );
			$featured_pool = array();

			foreach ( $app_posts as $post ) {
				if ( get_post_meta( $post->ID, ethnic_case_studies_featured_meta_key(), true ) ) {
					$featured_pool[] = $post;
				}
			}

			if ( empty( $featured_pool ) ) {
				$featured_pool = $app_posts;
			}

			$featured_posts = array_slice( $featured_pool, 0, 4 );
			$grid_query     = new WP_Query(
				ethnic_case_studies_build_query_args(
					array(),
					array(
						'post__in'            => ! empty( $app_post_ids ) ? $app_post_ids : array( 0 ),
						'orderby'             => 'post__in',
						'posts_per_page'      => -1,
						'ignore_sticky_posts' => true,
					)
				)
			);
		} else {
			$category_tax_query = array();

			if ( $category_term instanceof WP_Term ) {
				$taxonomies         = ethnic_case_studies_taxonomies();
				$category_tax_query = array(
					array(
						'taxonomy' => $taxonomies['category'],
						'field'    => 'slug',
						'terms'    => array( $category_term->slug ),
						'operator' => 'IN',
					),
				);
			}

			$featured_posts = get_posts(
				ethnic_case_studies_build_query_args(
					$filters,
					array(
						'posts_per_page'         => 3,
						'meta_query'             => $featured_meta,
						'tax_query'              => $category_tax_query,
						'no_found_rows'          => true,
						'update_post_term_cache' => true,
						'update_post_meta_cache' => true,
					)
				)
			);

			if ( empty( $featured_posts ) && empty( array_filter( $filters ) ) ) {
				$featured_posts = get_posts(
					ethnic_case_studies_build_query_args(
						$filters,
						array(
							'posts_per_page'         => 3,
							'tax_query'              => $category_tax_query,
							'no_found_rows'          => true,
							'update_post_term_cache' => true,
							'update_post_meta_cache' => true,
						)
					)
				);
			}

			$grid_query = new WP_Query(
				ethnic_case_studies_build_query_args(
					$filters,
					array(
						'posts_per_page' => 9,
						'paged'          => $paged,
						'tax_query'      => $category_tax_query,
					)
				)
			);

			foreach ( ethnic_case_studies_filter_definitions() as $key => $definition ) {
				$filter_terms[ $key ] = get_terms(
					array(
						'taxonomy'   => $definition['taxonomy'],
						'hide_empty' => true,
						'orderby'    => 'name',
						'order'      => 'ASC',
					)
				);
			}
		}

		$context = array(
			'variant'        => $variant,
			'current_category_term' => $category_term,
			'category_terms' => get_terms(
				array(
					'taxonomy'   => ethnic_case_studies_taxonomies()['category'],
					'hide_empty' => true,
					'orderby'    => 'name',
					'order'      => 'ASC',
				)
			),
			'config'         => $config,
			'archive_url'    => $config['archive_url'],
			'filters'        => $filters,
			'paged'          => $paged,
			'featured_posts' => $featured_posts,
			'featured_ids'   => array_map(
				'intval',
				wp_list_pluck( $featured_posts, 'ID' )
			),
			'grid_query'     => $grid_query,
			'filter_terms'   => $filter_terms,
			'result_count'   => (int) $grid_query->found_posts,
			'has_filters'    => ! empty( array_filter( $filters ) ) && ! empty( $config['show_filters'] ),
		);

		return $context;
	}
}

if ( ! function_exists( 'ethnic_case_studies_register_taxonomies' ) ) {
	function ethnic_case_studies_register_taxonomies() {
		$taxonomies = ethnic_case_studies_taxonomies();

		foreach ( array(
			$taxonomies['category'] => array(
				'name'          => 'Categories',
				'singular_name' => 'Category',
				'hierarchical'  => true,
			),
			$taxonomies['service']  => array(
				'name'          => 'Services',
				'singular_name' => 'Service',
				'hierarchical'  => false,
			),
			$taxonomies['platform'] => array(
				'name'          => 'Platforms',
				'singular_name' => 'Platform',
				'hierarchical'  => false,
			),
			$taxonomies['industry'] => array(
				'name'          => 'Industries',
				'singular_name' => 'Industry',
				'hierarchical'  => false,
			),
		) as $taxonomy => $labels ) {
			register_taxonomy(
				$taxonomy,
				ETHNIC_CASE_STUDIES_POST_TYPE,
				array(
					'hierarchical'      => ! empty( $labels['hierarchical'] ),
					'labels'            => array(
						'name'              => $labels['name'],
						'singular_name'     => $labels['singular_name'],
						'search_items'      => 'Search ' . $labels['name'],
						'all_items'         => 'All ' . $labels['name'],
						'edit_item'         => 'Edit ' . $labels['singular_name'],
						'update_item'       => 'Update ' . $labels['singular_name'],
						'add_new_item'      => 'Add New ' . $labels['singular_name'],
						'new_item_name'     => 'New ' . $labels['singular_name'] . ' Name',
						'menu_name'         => $labels['name'],
					),
					'show_ui'           => true,
					'show_admin_column' => true,
					'show_in_rest'      => true,
					'public'            => false,
					'publicly_queryable'=> false,
					'query_var'         => false,
					'rewrite'           => false,
				)
			);
		}
	}
	add_action( 'init', 'ethnic_case_studies_register_taxonomies', 12 );
}

if ( ! function_exists( 'ethnic_case_studies_register_featured_meta' ) ) {
	function ethnic_case_studies_register_featured_meta() {
		register_post_meta(
			ETHNIC_CASE_STUDIES_POST_TYPE,
			ethnic_case_studies_featured_meta_key(),
			array(
				'single'            => true,
				'type'              => 'boolean',
				'default'           => false,
				'show_in_rest'      => true,
				'auth_callback'     => static function () {
					return current_user_can( 'edit_posts' );
				},
				'sanitize_callback' => static function ( $value ) {
					return ! empty( $value );
				},
			)
		);
	}
	add_action( 'init', 'ethnic_case_studies_register_featured_meta', 20 );
}

if ( ! function_exists( 'ethnic_case_studies_register_logo_post_type' ) ) {
	function ethnic_case_studies_register_logo_post_type() {
		register_post_type(
			ETHNIC_CASE_STUDIES_LOGO_POST_TYPE,
			array(
				'labels' => array(
					'name'               => 'Tech Logos',
					'singular_name'      => 'Tech Logo',
					'menu_name'          => 'Tech Logos',
					'name_admin_bar'     => 'Tech Logo',
					'add_new'            => 'Add New',
					'add_new_item'       => 'Add New Tech Logo',
					'new_item'           => 'New Tech Logo',
					'edit_item'          => 'Edit Tech Logo',
					'view_item'          => 'View Tech Logo',
					'all_items'          => 'All Tech Logos',
					'search_items'       => 'Search Tech Logos',
					'not_found'          => 'No tech logos found.',
					'not_found_in_trash' => 'No tech logos found in Trash.',
				),
				'public'             => false,
				'publicly_queryable' => false,
				'show_ui'            => true,
				'show_in_menu'       => 'edit.php?post_type=' . ETHNIC_CASE_STUDIES_POST_TYPE,
				'show_in_rest'       => true,
				'rewrite'            => false,
				'query_var'          => false,
				'menu_icon'          => 'dashicons-format-image',
				'supports'           => array( 'title', 'page-attributes' ),
			)
		);
	}
	add_action( 'init', 'ethnic_case_studies_register_logo_post_type', 21 );
}

if ( ! function_exists( 'ethnic_case_studies_filter_post_type_args' ) ) {
	function ethnic_case_studies_filter_post_type_args( $args, $post_type ) {
		if ( ETHNIC_CASE_STUDIES_POST_TYPE !== $post_type ) {
			return $args;
		}

		$rewrite               = isset( $args['rewrite'] ) && is_array( $args['rewrite'] ) ? $args['rewrite'] : array();
		$rewrite['slug']       = ethnic_case_studies_archive_slug();
		$rewrite['with_front'] = false;

		$args['labels'] = array(
			'name'               => 'Case Studies',
			'singular_name'      => 'Case Study',
			'menu_name'          => 'Case Studies',
			'name_admin_bar'     => 'Case Study',
			'add_new'            => 'Add New',
			'add_new_item'       => 'Add New Case Study',
			'new_item'           => 'New Case Study',
			'edit_item'          => 'Edit Case Study',
			'view_item'          => 'View Case Study',
			'all_items'          => 'All Case Studies',
			'search_items'       => 'Search Case Studies',
			'not_found'          => 'No case studies found.',
			'not_found_in_trash' => 'No case studies found in Trash.',
		);
		$args['rewrite']      = $rewrite;
		$args['has_archive']  = ethnic_case_studies_archive_slug();
		$args['show_in_rest'] = true;
		$args['taxonomies']   = array_values(
			array_unique(
				array_merge(
					isset( $args['taxonomies'] ) ? (array) $args['taxonomies'] : array(),
					array_values( ethnic_case_studies_taxonomies() )
				)
			)
		);

		return $args;
	}
	add_filter( 'register_post_type_args', 'ethnic_case_studies_filter_post_type_args', 10, 2 );
}

if ( ! function_exists( 'ethnic_case_studies_filter_legacy_taxonomy_args' ) ) {
	function ethnic_case_studies_filter_legacy_taxonomy_args( $args, $taxonomy ) {
		if ( 'thegem_portfolios' !== $taxonomy ) {
			return $args;
		}

		$args['labels']['name']          = 'Legacy Portfolio Categories';
		$args['labels']['singular_name'] = 'Legacy Portfolio Category';
		$args['labels']['menu_name']     = 'Legacy Categories';
		$args['public']                  = false;
		$args['publicly_queryable']      = false;
		$args['query_var']               = false;
		$args['rewrite']                 = false;
		$args['show_tagcloud']           = false;
		$args['show_in_nav_menus']       = false;

		return $args;
	}
	add_filter( 'register_taxonomy_args', 'ethnic_case_studies_filter_legacy_taxonomy_args', 10, 2 );
}

if ( ! function_exists( 'ethnic_case_studies_content_meta_sections' ) ) {
	function ethnic_case_studies_content_meta_sections() {
		return array(
			'labels'   => array(
				'title'       => 'Template Labels',
				'description' => 'Short labels used across the reusable template. Leave any field empty to use the built-in default copy.',
				'fields'      => array(
					array(
						'key'         => 'back_link_label',
						'label'       => 'Back link label',
						'type'        => 'text',
						'description' => 'Example: Back to Case Studies',
					),
					array(
						'key'         => 'hero_eyebrow',
						'label'       => 'Hero eyebrow',
						'type'        => 'text',
						'description' => 'Small label above the case study title.',
					),
					array(
						'key'         => 'hero_overlay_kicker',
						'label'       => 'Hero overlay label',
						'type'        => 'text',
						'description' => 'Example: Outcome Snapshot',
					),
					array(
						'key'         => 'overview_kicker',
						'label'       => 'Overview section label',
						'type'        => 'text',
						'description' => 'Example: Client Overview',
					),
					array(
						'key'         => 'overview_card_kicker',
						'label'       => 'Overview summary card label',
						'type'        => 'text',
						'description' => 'Example: Client Snapshot',
					),
					array(
						'key'         => 'challenge_kicker',
						'label'       => 'Challenge section label',
						'type'        => 'text',
						'description' => 'Example: Business Challenge',
					),
					array(
						'key'         => 'goals_kicker',
						'label'       => 'Goals section label',
						'type'        => 'text',
					),
					array(
						'key'         => 'solution_kicker',
						'label'       => 'Solution section label',
						'type'        => 'text',
					),
					array(
						'key'         => 'features_kicker',
						'label'       => 'Features section label',
						'type'        => 'text',
					),
					array(
						'key'         => 'tech_stack_kicker',
						'label'       => 'Tech stack section label',
						'type'        => 'text',
					),
					array(
						'key'         => 'timeline_kicker',
						'label'       => 'Timeline section label',
						'type'        => 'text',
					),
					array(
						'key'         => 'engagement_card_kicker',
						'label'       => 'Engagement summary card label',
						'type'        => 'text',
					),
					array(
						'key'         => 'results_kicker',
						'label'       => 'Results section label',
						'type'        => 'text',
					),
					array(
						'key'         => 'gallery_kicker',
						'label'       => 'Gallery section label',
						'type'        => 'text',
					),
					array(
						'key'         => 'related_kicker',
						'label'       => 'Related services section label',
						'type'        => 'text',
					),
					array(
						'key'         => 'related_link_label',
						'label'       => 'Related service link label',
						'type'        => 'text',
						'description' => 'Example: Explore Service',
					),
					array(
						'key'         => 'cta_kicker',
						'label'       => 'Bottom CTA label',
						'type'        => 'text',
					),
				),
			),
			'hero'     => array(
				'title'       => 'Hero And Metadata',
				'description' => 'Controls the top of the case study page. Taxonomy-based service, platform, and industry still work, but you can override the visible values here if needed.',
				'fields'      => array(
					array(
						'key'         => 'hero_subtitle',
						'label'       => 'Hero subtitle',
						'type'        => 'textarea',
						'rows'        => 3,
						'description' => 'Short summary below the H1.',
					),
					array(
						'key'         => 'hero_highlights',
						'label'       => 'Hero highlight pills',
						'type'        => 'textarea',
						'rows'        => 4,
						'description' => 'One highlight per line.',
					),
					array(
						'key'         => 'hero_media_url',
						'label'       => 'Hero media URL',
						'type'        => 'text',
						'description' => 'Optional image or hosted MP4 URL for the hero visual.',
					),
					array(
						'key'         => 'hero_primary_label',
						'label'       => 'Primary hero button label',
						'type'        => 'text',
					),
					array(
						'key'         => 'hero_secondary_label',
						'label'       => 'Secondary hero button label',
						'type'        => 'text',
					),
					array(
						'key'         => 'client_name',
						'label'       => 'Client name',
						'type'        => 'text',
					),
					array(
						'key'         => 'project_type_override',
						'label'       => 'Project type override',
						'type'        => 'text',
						'description' => 'Example: eCommerce Transformation, Mobile Product Build, Client Portal',
					),
					array(
						'key'         => 'service_override',
						'label'       => 'Service override',
						'type'        => 'text',
						'description' => 'Comma-separated values shown in the template metadata.',
					),
					array(
						'key'         => 'platform_override',
						'label'       => 'Platform override',
						'type'        => 'text',
						'description' => 'Comma-separated values shown in the template metadata.',
					),
					array(
						'key'         => 'industry_override',
						'label'       => 'Industry override',
						'type'        => 'text',
						'description' => 'Comma-separated values shown in the template metadata.',
					),
				),
			),
			'overview' => array(
				'title'       => 'Client Overview',
				'description' => 'Use the editor/Elementor content for freeform content blocks. Use these fields to control the structured overview block on the reusable template.',
				'fields'      => array(
					array(
						'key'         => 'overview_heading',
						'label'       => 'Overview heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'overview_paragraphs',
						'label'       => 'Overview paragraphs',
						'type'        => 'textarea',
						'rows'        => 6,
						'description' => 'Separate paragraphs with a blank line.',
					),
					array(
						'key'         => 'overview_facts',
						'label'       => 'Overview facts',
						'type'        => 'textarea',
						'rows'        => 5,
						'description' => 'One row per line using: Label | Value',
					),
				),
			),
			'challenge' => array(
				'title'       => 'Business Challenge',
				'description' => 'Describe the blockers, gaps, and business pressure that triggered the project.',
				'fields'      => array(
					array(
						'key'         => 'challenge_heading',
						'label'       => 'Challenge heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'challenge_intro',
						'label'       => 'Challenge intro',
						'type'        => 'textarea',
						'rows'        => 4,
						'description' => 'Short paragraph above the challenge cards.',
					),
					array(
						'key'         => 'challenges',
						'label'       => 'Challenge cards',
						'type'        => 'textarea',
						'rows'        => 7,
						'description' => 'One row per line using: Title | Description',
					),
				),
			),
			'goals'    => array(
				'title'       => 'Goals',
				'description' => 'Define the delivery objectives that guided the project.',
				'fields'      => array(
					array(
						'key'         => 'goals_heading',
						'label'       => 'Goals heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'goals',
						'label'       => 'Goal cards',
						'type'        => 'textarea',
						'rows'        => 7,
						'description' => 'One row per line using: Title | Description',
					),
				),
			),
			'solution' => array(
				'title'       => 'Solution Delivered',
				'description' => 'Control the core narrative about how the work was planned, executed, and delivered.',
				'fields'      => array(
					array(
						'key'         => 'solution_heading',
						'label'       => 'Solution heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'solution_paragraphs',
						'label'       => 'Solution paragraphs',
						'type'        => 'textarea',
						'rows'        => 7,
						'description' => 'Separate paragraphs with a blank line.',
					),
					array(
						'key'         => 'solution_pillars',
						'label'       => 'Solution pillar cards',
						'type'        => 'textarea',
						'rows'        => 5,
						'description' => 'One row per line using: Title | Description',
					),
				),
			),
			'features' => array(
				'title'       => 'Features, Modules, And Systems',
				'description' => 'List the modules, feature sets, or systems that were built or improved.',
				'fields'      => array(
					array(
						'key'         => 'features_heading',
						'label'       => 'Features heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'features',
						'label'       => 'Feature cards',
						'type'        => 'textarea',
						'rows'        => 8,
						'description' => 'One row per line using: Title | Description',
					),
				),
			),
			'stack'    => array(
				'title'       => 'Tech Stack',
				'description' => 'Show the platform, integrations, and delivery systems used in the project. Select one or more Tech Logos below to power the frontend logo strip. If you leave the logo picker empty, the legacy grouped field will still be used.',
				'fields'      => array(
					array(
						'key'         => 'tech_stack_heading',
						'label'       => 'Tech stack heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'tech_stack_logos',
						'label'       => 'Tech logos',
						'type'        => 'logo_multiselect',
						'description' => 'Choose multiple reusable logos from the library. Manage or add more logos in Case Studies -> Tech Logos.',
					),
					array(
						'key'         => 'tech_stack',
						'label'       => 'Tech stack groups',
						'type'        => 'textarea',
						'rows'        => 7,
						'description' => 'One row per line using: Group Label | Item 1, Item 2, Item 3',
					),
				),
			),
			'delivery' => array(
				'title'       => 'Timeline And Engagement',
				'description' => 'Map the timeline phases and the engagement summary shown beside them.',
				'fields'      => array(
					array(
						'key'         => 'timeline_heading',
						'label'       => 'Timeline heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'timeline',
						'label'       => 'Timeline steps',
						'type'        => 'textarea',
						'rows'        => 8,
						'description' => 'One row per line using: Phase | Description',
					),
					array(
						'key'         => 'engagement_summary',
						'label'       => 'Engagement summary rows',
						'type'        => 'textarea',
						'rows'        => 6,
						'description' => 'One row per line using: Label | Value',
					),
				),
			),
			'results'  => array(
				'title'       => 'Results And Impact',
				'description' => 'Set the measurable outcomes and the supporting impact cards.',
				'fields'      => array(
					array(
						'key'         => 'results_heading',
						'label'       => 'Results heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'result_cards',
						'label'       => 'Result stat cards',
						'type'        => 'textarea',
						'rows'        => 7,
						'description' => 'One row per line using: Value | Label | Description',
					),
					array(
						'key'         => 'impact_cards',
						'label'       => 'Impact cards',
						'type'        => 'textarea',
						'rows'        => 6,
						'description' => 'One row per line using: Title | Description',
					),
				),
			),
			'gallery'  => array(
				'title'       => 'Gallery And Related Services',
				'description' => 'Add screenshots, captions, and service links that connect this case study to the rest of the site.',
				'fields'      => array(
					array(
						'key'         => 'gallery_heading',
						'label'       => 'Gallery heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'gallery_items',
						'label'       => 'Gallery items',
						'type'        => 'textarea',
						'rows'        => 6,
						'description' => 'One row per line using: Media URL | Alt text | Caption. Hosted MP4 URLs are supported.',
					),
					array(
						'key'         => 'related_services_heading',
						'label'       => 'Related services heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'related_services',
						'label'       => 'Related services',
						'type'        => 'textarea',
						'rows'        => 6,
						'description' => 'One row per line using: Title | Description | URL',
					),
				),
			),
			'cta'      => array(
				'title'       => 'Bottom CTA',
				'description' => 'Final conversion block shown at the bottom of the case study page.',
				'fields'      => array(
					array(
						'key'         => 'cta_heading',
						'label'       => 'CTA heading',
						'type'        => 'text',
					),
					array(
						'key'         => 'cta_copy',
						'label'       => 'CTA copy',
						'type'        => 'textarea',
						'rows'        => 4,
					),
					array(
						'key'         => 'cta_primary_label',
						'label'       => 'Primary CTA button label',
						'type'        => 'text',
					),
					array(
						'key'         => 'cta_secondary_label',
						'label'       => 'Secondary CTA button label',
						'type'        => 'text',
					),
				),
			),
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_add_meta_box' ) ) {
	function ethnic_case_studies_add_meta_box() {
		add_meta_box(
			'ethnic-case-study-featured',
			'Case Study Settings',
			'ethnic_case_studies_render_meta_box',
			ETHNIC_CASE_STUDIES_POST_TYPE,
			'side',
			'high'
		);
		add_meta_box(
			'ethnic-case-study-content',
			'Case Study Page Content',
			'ethnic_case_studies_render_content_meta_box',
			ETHNIC_CASE_STUDIES_POST_TYPE,
			'normal',
			'high'
		);
		add_meta_box(
			'ethnic-case-study-logo-asset',
			'Logo Asset',
			'ethnic_case_studies_render_logo_asset_meta_box',
			ETHNIC_CASE_STUDIES_LOGO_POST_TYPE,
			'normal',
			'high'
		);
	}
	add_action( 'add_meta_boxes', 'ethnic_case_studies_add_meta_box' );
}

if ( ! function_exists( 'ethnic_case_studies_service_page_add_meta_box' ) ) {
	function ethnic_case_studies_service_page_add_meta_box( $post ) {
		if ( ! ethnic_case_studies_is_service_page( $post ) ) {
			return;
		}

		add_meta_box(
			'ethnic-service-page-case-studies',
			'Service Page Case Studies',
			'ethnic_case_studies_render_service_page_meta_box',
			'page',
			'side',
			'default'
		);
	}
	add_action( 'add_meta_boxes_page', 'ethnic_case_studies_service_page_add_meta_box' );
}

if ( ! function_exists( 'ethnic_case_studies_render_meta_box' ) ) {
	function ethnic_case_studies_render_meta_box( $post ) {
		wp_nonce_field( 'ethnic_case_studies_settings_meta_box', 'ethnic_case_studies_settings_meta_box_nonce' );
		$value = (bool) get_post_meta( $post->ID, ethnic_case_studies_featured_meta_key(), true );
		?>
		<p>
			<label for="ethnic_case_study_featured_toggle">
				<input type="checkbox" id="ethnic_case_study_featured_toggle" name="ethnic_case_study_featured_toggle" value="1" <?php checked( $value ); ?> />
				Feature this case study on the archive page
			</label>
		</p>
		<?php
	}
}

if ( ! function_exists( 'ethnic_case_studies_render_content_meta_box' ) ) {
	function ethnic_case_studies_render_content_meta_box( $post ) {
		wp_nonce_field( 'ethnic_case_studies_content_meta_box', 'ethnic_case_studies_content_meta_box_nonce' );
		$sections = ethnic_case_studies_content_meta_sections();
		?>
		<div class="ethnic-case-study-admin">
			<style>
				.ethnic-case-study-admin__intro {
					margin: 0 0 18px;
					padding: 12px 14px;
					border: 1px solid #dbe4ff;
					border-radius: 12px;
					background: #f7f9ff;
				}
				.ethnic-case-study-admin__section {
					margin: 0 0 14px;
					border: 1px solid #d9dee8;
					border-radius: 14px;
					background: #fff;
				}
				.ethnic-case-study-admin__section summary {
					cursor: pointer;
					padding: 14px 16px;
					font-weight: 600;
				}
				.ethnic-case-study-admin__section-body {
					padding: 0 16px 16px;
				}
				.ethnic-case-study-admin__section-body > p.description {
					margin: 0 0 14px;
				}
				.ethnic-case-study-admin__grid {
					display: grid;
					grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
					gap: 14px 18px;
				}
				.ethnic-case-study-admin__field {
					margin: 0;
				}
				.ethnic-case-study-admin__field--full {
					grid-column: 1 / -1;
				}
				.ethnic-case-study-admin__logo-list {
					display: grid;
					grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
					gap: 10px;
				}
				.ethnic-case-study-admin__logo-option {
					display: flex;
					align-items: center;
					gap: 10px;
					padding: 10px 12px;
					border: 1px solid #d9dee8;
					border-radius: 12px;
					background: #fff;
				}
				.ethnic-case-study-admin__logo-option input {
					margin: 0;
				}
				.ethnic-case-study-admin__logo-thumb {
					display: inline-flex;
					align-items: center;
					justify-content: center;
					width: 40px;
					height: 40px;
					border-radius: 10px;
					background: #f6f8fc;
					flex: 0 0 40px;
					overflow: hidden;
				}
				.ethnic-case-study-admin__logo-thumb img {
					max-width: 28px;
					max-height: 28px;
					width: auto;
					height: auto;
				}
				.ethnic-case-study-admin__logo-thumb span {
					font-size: 12px;
					font-weight: 700;
					letter-spacing: 0.08em;
					color: #2f6bff;
				}
				.ethnic-case-study-admin__logo-title {
					font-weight: 600;
					line-height: 1.35;
				}
				.ethnic-case-study-admin__logo-actions {
					display: flex;
					flex-wrap: wrap;
					gap: 8px;
					margin-bottom: 12px;
				}
				.ethnic-case-study-admin__logo-empty {
					margin: 0;
					padding: 12px;
					border: 1px dashed #c9d3ea;
					border-radius: 12px;
					background: #f8faff;
					font-size: 12px;
					line-height: 1.6;
				}
				.ethnic-case-study-admin__field label {
					display: block;
					margin-bottom: 6px;
					font-weight: 600;
				}
			</style>
			<div class="ethnic-case-study-admin__intro">
				<p><strong>Use this box to control the reusable case study template.</strong> The main editor or Elementor area can still be used for flexible content blocks, while the fields below manage the structured sections like overview, challenge, goals, results, gallery, and CTA.</p>
				<p class="description">Leave a field empty to keep the default fallback copy. Featured image, excerpt, taxonomy terms, and the normal content editor remain editable in the standard WordPress panels.</p>
			</div>
			<?php
			$section_index = 0;
			foreach ( $sections as $section ) :
				$section_index++;
				?>
				<details class="ethnic-case-study-admin__section" <?php echo 1 === $section_index ? 'open' : ''; ?>>
					<summary><?php echo esc_html( $section['title'] ); ?></summary>
					<div class="ethnic-case-study-admin__section-body">
						<?php if ( ! empty( $section['description'] ) ) : ?>
							<p class="description"><?php echo esc_html( $section['description'] ); ?></p>
						<?php endif; ?>
						<div class="ethnic-case-study-admin__grid">
							<?php foreach ( $section['fields'] as $field ) : ?>
								<?php
								$key         = sanitize_key( $field['key'] );
								$meta_key    = ethnic_case_studies_content_meta_key( $key );
								$value       = get_post_meta( $post->ID, $meta_key, true );
								$type        = isset( $field['type'] ) ? $field['type'] : 'text';
								$field_id    = 'ethnic-case-study-field-' . $key;
								$field_class = 'ethnic-case-study-admin__field';

								if ( 'textarea' === $type || 'logo_multiselect' === $type ) {
									$field_class .= ' ethnic-case-study-admin__field--full';
								}
								?>
								<div class="<?php echo esc_attr( $field_class ); ?>">
									<label for="<?php echo esc_attr( $field_id ); ?>"><?php echo esc_html( $field['label'] ); ?></label>
									<?php if ( 'textarea' === $type ) : ?>
										<textarea class="widefat" id="<?php echo esc_attr( $field_id ); ?>" name="<?php echo esc_attr( $meta_key ); ?>" rows="<?php echo esc_attr( isset( $field['rows'] ) ? (int) $field['rows'] : 5 ); ?>"><?php echo esc_textarea( (string) $value ); ?></textarea>
									<?php elseif ( 'logo_multiselect' === $type ) : ?>
										<?php
										$selected_logo_ids = ethnic_case_studies_selected_logo_ids( $post->ID );
										$logo_posts        = ethnic_case_studies_logo_library_posts( array( 'publish', 'draft', 'private' ) );
										$manage_logo_url   = admin_url( 'edit.php?post_type=' . ETHNIC_CASE_STUDIES_LOGO_POST_TYPE );
										$new_logo_url      = admin_url( 'post-new.php?post_type=' . ETHNIC_CASE_STUDIES_LOGO_POST_TYPE );
										?>
										<div class="ethnic-case-study-admin__logo-actions">
											<a class="button button-secondary" href="<?php echo esc_url( $manage_logo_url ); ?>">Manage Tech Logos</a>
											<a class="button button-link" href="<?php echo esc_url( $new_logo_url ); ?>">Add New Logo</a>
										</div>
										<?php if ( empty( $logo_posts ) ) : ?>
											<p class="ethnic-case-study-admin__logo-empty">No tech logos found yet. Create a logo entry with a name and uploaded image, then come back here to select it.</p>
										<?php else : ?>
											<div class="ethnic-case-study-admin__logo-list" id="<?php echo esc_attr( $field_id ); ?>">
												<?php foreach ( $logo_posts as $logo_post ) : ?>
													<?php
													$logo_id    = (int) $logo_post->ID;
													$logo_label = ethnic_case_studies_text( get_the_title( $logo_post ), 'Tech Logo' );
													$logo_url   = ethnic_case_studies_logo_image_url( $logo_id, 'thumbnail' );
													?>
													<label class="ethnic-case-study-admin__logo-option" for="<?php echo esc_attr( $field_id . '-' . $logo_id ); ?>">
														<input id="<?php echo esc_attr( $field_id . '-' . $logo_id ); ?>" type="checkbox" name="ethnic_case_study_logo_ids[]" value="<?php echo esc_attr( $logo_id ); ?>" <?php checked( in_array( $logo_id, $selected_logo_ids, true ) ); ?> />
														<span class="ethnic-case-study-admin__logo-thumb" aria-hidden="true">
															<?php if ( '' !== $logo_url ) : ?>
																<img src="<?php echo esc_url( $logo_url ); ?>" alt="" loading="lazy" decoding="async" />
															<?php else : ?>
																<span><?php echo esc_html( ethnic_case_studies_stack_item_monogram( $logo_label ) ); ?></span>
															<?php endif; ?>
														</span>
														<span class="ethnic-case-study-admin__logo-title"><?php echo esc_html( $logo_label ); ?></span>
													</label>
												<?php endforeach; ?>
											</div>
										<?php endif; ?>
									<?php else : ?>
										<input class="widefat" id="<?php echo esc_attr( $field_id ); ?>" name="<?php echo esc_attr( $meta_key ); ?>" type="text" value="<?php echo esc_attr( (string) $value ); ?>" />
									<?php endif; ?>
									<?php if ( ! empty( $field['description'] ) ) : ?>
										<p class="description"><?php echo esc_html( $field['description'] ); ?></p>
									<?php endif; ?>
								</div>
							<?php endforeach; ?>
						</div>
					</div>
				</details>
			<?php endforeach; ?>
		</div>
		<?php
	}
}

if ( ! function_exists( 'ethnic_case_studies_render_service_page_meta_box' ) ) {
	function ethnic_case_studies_render_service_page_meta_box( $post ) {
		$post            = get_post( $post );
		$available_posts = ethnic_case_studies_service_page_available_posts();
		$selected_ids    = ethnic_case_studies_service_page_selected_ids( $post ? $post->ID : 0 );
		$slot_count      = ethnic_case_studies_service_page_selection_limit();
		$manage_url      = admin_url( 'edit.php?post_type=' . ETHNIC_CASE_STUDIES_POST_TYPE );

		if ( ! ( $post instanceof WP_Post ) ) {
			return;
		}

		wp_nonce_field( 'ethnic_case_studies_service_page_meta_box', 'ethnic_case_studies_service_page_meta_box_nonce' );
		?>
		<p>Select the case studies for this service page in display order. If you leave slots empty, the page will fall back to automatic/default case studies.</p>
		<?php for ( $slot = 0; $slot < $slot_count; $slot++ ) : ?>
			<?php $selected_id = isset( $selected_ids[ $slot ] ) ? (int) $selected_ids[ $slot ] : 0; ?>
			<p>
				<label for="ethnic_service_page_case_study_slot_<?php echo esc_attr( $slot + 1 ); ?>"><strong><?php echo esc_html( 'Slot ' . ( $slot + 1 ) ); ?></strong></label><br />
				<select
					id="ethnic_service_page_case_study_slot_<?php echo esc_attr( $slot + 1 ); ?>"
					name="ethnic_service_page_case_study_ids[]"
					style="width:100%;"
				>
					<option value="">Select a case study</option>
					<?php foreach ( $available_posts as $case_study_post ) : ?>
						<?php
						$case_study_post = get_post( $case_study_post );

						if ( ! ( $case_study_post instanceof WP_Post ) ) {
							continue;
						}

						$service  = ethnic_case_studies_first_value( ethnic_case_studies_get_service_terms( $case_study_post->ID ) );
						$platform = ethnic_case_studies_first_value( ethnic_case_studies_get_platform_terms( $case_study_post->ID ) );
						$suffix   = implode( ' / ', array_filter( array( $service, $platform ) ) );
						$label    = get_the_title( $case_study_post );

						if ( '' !== $suffix ) {
							$label .= ' - ' . $suffix;
						}
						?>
						<option value="<?php echo esc_attr( $case_study_post->ID ); ?>" <?php selected( $selected_id, $case_study_post->ID ); ?>>
							<?php echo esc_html( $label ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</p>
		<?php endfor; ?>
		<p class="description">Create or edit reusable case studies in <a href="<?php echo esc_url( $manage_url ); ?>">Case Studies</a>. The selected post links are used on the frontend.</p>
		<?php
	}
}

if ( ! function_exists( 'ethnic_case_studies_render_logo_selector_meta_box' ) ) {
	function ethnic_case_studies_render_logo_selector_meta_box( $post ) {
		wp_nonce_field( 'ethnic_case_studies_logo_selector_meta_box', 'ethnic_case_studies_logo_selector_meta_box_nonce' );

		$selected_ids = ethnic_case_studies_selected_logo_ids( $post->ID );
		$logo_posts   = ethnic_case_studies_logo_library_posts( array( 'publish', 'draft', 'private' ) );
		$manage_url   = admin_url( 'edit.php?post_type=' . ETHNIC_CASE_STUDIES_LOGO_POST_TYPE );
		$create_url   = admin_url( 'post-new.php?post_type=' . ETHNIC_CASE_STUDIES_LOGO_POST_TYPE );
		?>
		<div class="ethnic-case-study-logo-select">
			<style>
				.ethnic-case-study-logo-select__intro {
					margin: 0 0 12px;
					font-size: 12px;
					line-height: 1.55;
					color: #52607a;
				}
				.ethnic-case-study-logo-select__actions {
					display: flex;
					flex-wrap: wrap;
					gap: 8px;
					margin: 0 0 12px;
				}
				.ethnic-case-study-logo-select__list {
					display: grid;
					gap: 8px;
				}
				.ethnic-case-study-logo-select__item {
					display: flex;
					align-items: center;
					gap: 10px;
					padding: 8px;
					border: 1px solid #d9dee8;
					border-radius: 12px;
					background: #fff;
				}
				.ethnic-case-study-logo-select__item input {
					margin: 0;
				}
				.ethnic-case-study-logo-select__preview {
					display: inline-flex;
					align-items: center;
					justify-content: center;
					width: 40px;
					height: 40px;
					border-radius: 10px;
					background: #f6f8fc;
					flex: 0 0 40px;
					overflow: hidden;
				}
				.ethnic-case-study-logo-select__preview img {
					max-width: 28px;
					max-height: 28px;
					width: auto;
					height: auto;
				}
				.ethnic-case-study-logo-select__preview span {
					font-size: 12px;
					font-weight: 700;
					letter-spacing: 0.08em;
					color: #2f6bff;
				}
				.ethnic-case-study-logo-select__title {
					font-weight: 600;
					line-height: 1.35;
				}
				.ethnic-case-study-logo-select__empty {
					margin: 0;
					padding: 12px;
					border: 1px dashed #c9d3ea;
					border-radius: 12px;
					background: #f8faff;
					font-size: 12px;
					line-height: 1.6;
				}
			</style>
			<p class="ethnic-case-study-logo-select__intro">Select the reusable logos you want to show in the tech stack strip. If you leave this empty, the page will keep using the legacy Tech Stack groups below.</p>
			<div class="ethnic-case-study-logo-select__actions">
				<a class="button button-secondary" href="<?php echo esc_url( $manage_url ); ?>">Manage Tech Logos</a>
				<a class="button button-link" href="<?php echo esc_url( $create_url ); ?>">Add New Logo</a>
			</div>
			<?php if ( empty( $logo_posts ) ) : ?>
				<p class="ethnic-case-study-logo-select__empty">No tech logos found yet. Create a logo entry with a name and uploaded image, then come back here to select it.</p>
			<?php else : ?>
				<div class="ethnic-case-study-logo-select__list">
					<?php foreach ( $logo_posts as $logo_post ) : ?>
						<?php
						$logo_id    = (int) $logo_post->ID;
						$logo_label = ethnic_case_studies_text( get_the_title( $logo_post ), 'Tech Logo' );
						$logo_url   = ethnic_case_studies_logo_image_url( $logo_id, 'thumbnail' );
						?>
						<label class="ethnic-case-study-logo-select__item" for="ethnic-case-study-logo-<?php echo esc_attr( $logo_id ); ?>">
							<input id="ethnic-case-study-logo-<?php echo esc_attr( $logo_id ); ?>" type="checkbox" name="ethnic_case_study_logo_ids[]" value="<?php echo esc_attr( $logo_id ); ?>" <?php checked( in_array( $logo_id, $selected_ids, true ) ); ?> />
							<span class="ethnic-case-study-logo-select__preview" aria-hidden="true">
								<?php if ( '' !== $logo_url ) : ?>
									<img src="<?php echo esc_url( $logo_url ); ?>" alt="" loading="lazy" decoding="async" />
								<?php else : ?>
									<span><?php echo esc_html( ethnic_case_studies_stack_item_monogram( $logo_label ) ); ?></span>
								<?php endif; ?>
							</span>
							<span class="ethnic-case-study-logo-select__title"><?php echo esc_html( $logo_label ); ?></span>
						</label>
					<?php endforeach; ?>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}
}

if ( ! function_exists( 'ethnic_case_studies_render_logo_asset_meta_box' ) ) {
	function ethnic_case_studies_render_logo_asset_meta_box( $post ) {
		wp_nonce_field( 'ethnic_case_studies_logo_asset_meta_box', 'ethnic_case_studies_logo_asset_meta_box_nonce' );
		wp_enqueue_media();

		$image_id  = (int) get_post_meta( $post->ID, ethnic_case_studies_logo_image_id_meta_key(), true );
		$image_url = ethnic_case_studies_logo_image_url( $post->ID, 'medium' );
		?>
		<div class="ethnic-case-study-logo-asset">
			<style>
				.ethnic-case-study-logo-asset__preview {
					display: flex;
					align-items: center;
					justify-content: center;
					min-height: 140px;
					margin: 0 0 14px;
					padding: 20px;
					border: 1px dashed #ccd5e5;
					border-radius: 16px;
					background: linear-gradient(180deg, #fbfcff 0%, #f3f6fd 100%);
				}
				.ethnic-case-study-logo-asset__preview img {
					max-width: 240px;
					max-height: 90px;
					width: auto;
					height: auto;
				}
				.ethnic-case-study-logo-asset__empty {
					font-size: 13px;
					font-weight: 600;
					color: #6a7691;
				}
				.ethnic-case-study-logo-asset__actions {
					display: flex;
					flex-wrap: wrap;
					gap: 10px;
					margin: 0 0 12px;
				}
			</style>
			<div class="ethnic-case-study-logo-asset__preview" data-logo-preview>
				<?php if ( '' !== $image_url ) : ?>
					<img src="<?php echo esc_url( $image_url ); ?>" alt="" />
				<?php else : ?>
					<span class="ethnic-case-study-logo-asset__empty">Upload or paste a logo image.</span>
				<?php endif; ?>
			</div>
			<input type="hidden" id="ethnic-case-study-logo-image-id" name="<?php echo esc_attr( ethnic_case_studies_logo_image_id_meta_key() ); ?>" value="<?php echo esc_attr( $image_id ); ?>" />
			<p>
				<label for="ethnic-case-study-logo-image-url"><strong>Logo image URL</strong></label>
				<input class="widefat" id="ethnic-case-study-logo-image-url" name="<?php echo esc_attr( ethnic_case_studies_logo_image_url_meta_key() ); ?>" type="text" value="<?php echo esc_attr( $image_url ); ?>" />
			</p>
			<div class="ethnic-case-study-logo-asset__actions">
				<button type="button" class="button button-secondary" data-logo-upload>Choose Logo</button>
				<button type="button" class="button-link-delete" data-logo-remove>Remove Logo</button>
			</div>
			<p class="description">Use the post title for the logo name. Upload a transparent PNG, SVG, or WEBP when possible. This logo will become selectable from the case study editor.</p>
			<script>
				jQuery(function($) {
					var frame;
					var $idField = $('#ethnic-case-study-logo-image-id');
					var $urlField = $('#ethnic-case-study-logo-image-url');
					var $preview = $('[data-logo-preview]');
					var emptyMarkup = '<span class="ethnic-case-study-logo-asset__empty">Upload or paste a logo image.</span>';

					function updatePreview(url) {
						if (url) {
							$preview.html('<img src="' + url + '" alt="" />');
						} else {
							$preview.html(emptyMarkup);
						}
					}

					$('[data-logo-upload]').on('click', function(event) {
						event.preventDefault();

						if (frame) {
							frame.open();
							return;
						}

						frame = wp.media({
							title: 'Choose logo',
							button: {
								text: 'Use this logo'
							},
							multiple: false,
							library: {
								type: 'image'
							}
						});

						frame.on('select', function() {
							var attachment = frame.state().get('selection').first().toJSON();
							var url = attachment.sizes && attachment.sizes.medium ? attachment.sizes.medium.url : attachment.url;

							$idField.val(attachment.id || '');
							$urlField.val(attachment.url || '');
							updatePreview(url || attachment.url || '');
						});

						frame.open();
					});

					$('[data-logo-remove]').on('click', function(event) {
						event.preventDefault();
						$idField.val('');
						$urlField.val('');
						updatePreview('');
					});

					$urlField.on('input', function() {
						if (! $idField.val()) {
							updatePreview($(this).val());
						}
					});
				});
			</script>
		</div>
		<?php
	}
}

if ( ! function_exists( 'ethnic_case_studies_save_meta_box' ) ) {
	function ethnic_case_studies_save_meta_box( $post_id ) {
		$settings_nonce_valid = ! empty( $_POST['ethnic_case_studies_settings_meta_box_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ethnic_case_studies_settings_meta_box_nonce'] ) ), 'ethnic_case_studies_settings_meta_box' );
		$content_nonce_valid  = ! empty( $_POST['ethnic_case_studies_content_meta_box_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ethnic_case_studies_content_meta_box_nonce'] ) ), 'ethnic_case_studies_content_meta_box' );

		if ( ! $settings_nonce_valid && ! $content_nonce_valid ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if ( $settings_nonce_valid ) {
			if ( isset( $_POST['ethnic_case_study_featured_toggle'] ) ) {
				update_post_meta( $post_id, ethnic_case_studies_featured_meta_key(), 1 );
			} else {
				delete_post_meta( $post_id, ethnic_case_studies_featured_meta_key() );
			}
		}

		if ( $content_nonce_valid ) {
			$selected_logo_ids = isset( $_POST['ethnic_case_study_logo_ids'] ) ? (array) wp_unslash( $_POST['ethnic_case_study_logo_ids'] ) : array();
			$selected_logo_ids = array_values(
				array_unique(
					array_filter(
						array_map( 'intval', $selected_logo_ids )
					)
				)
			);

			if ( empty( $selected_logo_ids ) ) {
				delete_post_meta( $post_id, ethnic_case_studies_logo_selection_meta_key() );
			} else {
				update_post_meta( $post_id, ethnic_case_studies_logo_selection_meta_key(), $selected_logo_ids );
			}
			foreach ( ethnic_case_studies_content_meta_sections() as $section ) {
				foreach ( $section['fields'] as $field ) {
					$key = isset( $field['key'] ) ? sanitize_key( $field['key'] ) : '';

					if ( '' === $key ) {
						continue;
					}

					$meta_key = ethnic_case_studies_content_meta_key( $key );
					$type     = isset( $field['type'] ) ? $field['type'] : 'text';

					if ( ! isset( $_POST[ $meta_key ] ) ) {
						delete_post_meta( $post_id, $meta_key );
						continue;
					}

					$raw_value = wp_unslash( $_POST[ $meta_key ] );
					$value     = 'textarea' === $type ? sanitize_textarea_field( $raw_value ) : sanitize_text_field( $raw_value );

					if ( '' === trim( (string) $value ) ) {
						delete_post_meta( $post_id, $meta_key );
					} else {
						update_post_meta( $post_id, $meta_key, $value );
					}
				}
			}
	}
}
add_action( 'save_post_' . ETHNIC_CASE_STUDIES_POST_TYPE, 'ethnic_case_studies_save_meta_box' );

if ( ! function_exists( 'ethnic_case_studies_save_service_page_meta_box' ) ) {
	function ethnic_case_studies_save_service_page_meta_box( $post_id ) {
		$nonce_valid = ! empty( $_POST['ethnic_case_studies_service_page_meta_box_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ethnic_case_studies_service_page_meta_box_nonce'] ) ), 'ethnic_case_studies_service_page_meta_box' );

		if ( ! $nonce_valid ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) || ! ethnic_case_studies_is_service_page( $post_id ) ) {
			return;
		}

		$selected_ids = isset( $_POST['ethnic_service_page_case_study_ids'] ) ? (array) wp_unslash( $_POST['ethnic_service_page_case_study_ids'] ) : array();
		$selected_ids = array_slice( $selected_ids, 0, ethnic_case_studies_service_page_selection_limit() );
		$selected_ids = array_values(
			array_filter(
				array_unique(
					array_map( 'intval', $selected_ids )
				),
				static function ( $case_study_id ) {
					return $case_study_id > 0 && ETHNIC_CASE_STUDIES_POST_TYPE === get_post_type( $case_study_id );
				}
			)
		);

		if ( empty( $selected_ids ) ) {
			delete_post_meta( $post_id, ethnic_case_studies_service_page_case_study_ids_meta_key() );
		} else {
			update_post_meta( $post_id, ethnic_case_studies_service_page_case_study_ids_meta_key(), $selected_ids );
		}
	}
	add_action( 'save_post_page', 'ethnic_case_studies_save_service_page_meta_box' );
}
}

if ( ! function_exists( 'ethnic_case_studies_save_logo_asset_meta_box' ) ) {
	function ethnic_case_studies_save_logo_asset_meta_box( $post_id ) {
		$nonce_valid = ! empty( $_POST['ethnic_case_studies_logo_asset_meta_box_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ethnic_case_studies_logo_asset_meta_box_nonce'] ) ), 'ethnic_case_studies_logo_asset_meta_box' );

		if ( ! $nonce_valid ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		$image_id  = isset( $_POST[ ethnic_case_studies_logo_image_id_meta_key() ] ) ? (int) wp_unslash( $_POST[ ethnic_case_studies_logo_image_id_meta_key() ] ) : 0;
		$image_url = isset( $_POST[ ethnic_case_studies_logo_image_url_meta_key() ] ) ? esc_url_raw( wp_unslash( $_POST[ ethnic_case_studies_logo_image_url_meta_key() ] ) ) : '';

		if ( $image_id > 0 ) {
			update_post_meta( $post_id, ethnic_case_studies_logo_image_id_meta_key(), $image_id );
		} else {
			delete_post_meta( $post_id, ethnic_case_studies_logo_image_id_meta_key() );
		}

		if ( '' !== $image_url ) {
			update_post_meta( $post_id, ethnic_case_studies_logo_image_url_meta_key(), $image_url );
		} else {
			delete_post_meta( $post_id, ethnic_case_studies_logo_image_url_meta_key() );
		}
	}
	add_action( 'save_post_' . ETHNIC_CASE_STUDIES_LOGO_POST_TYPE, 'ethnic_case_studies_save_logo_asset_meta_box' );
}

if ( ! function_exists( 'ethnic_case_studies_seed_logo_library' ) ) {
	function ethnic_case_studies_seed_logo_library() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$seed_version = '20260422.1';

		if ( get_option( 'ethnic_case_studies_logo_library_seed_version' ) === $seed_version ) {
			return;
		}

		$catalog = ethnic_case_studies_stack_logo_catalog();
		$order   = 0;

		foreach ( $catalog as $slug => $item ) {
			$label = isset( $item['label'] ) ? ethnic_case_studies_text( $item['label'] ) : '';

			if ( '' === $label ) {
				continue;
			}

			$existing = get_page_by_path( $slug, OBJECT, ETHNIC_CASE_STUDIES_LOGO_POST_TYPE );
			$post_id  = $existing instanceof WP_Post ? (int) $existing->ID : 0;

			if ( $post_id <= 0 ) {
				$post_id = wp_insert_post(
					array(
						'post_type'   => ETHNIC_CASE_STUDIES_LOGO_POST_TYPE,
						'post_status' => 'publish',
						'post_title'  => $label,
						'post_name'   => $slug,
						'menu_order'  => $order,
					)
				);
			}

			if ( is_wp_error( $post_id ) || $post_id <= 0 ) {
				$order++;
				continue;
			}

			if ( '' === get_post_meta( $post_id, ethnic_case_studies_logo_image_url_meta_key(), true ) && ! empty( $item['src'] ) ) {
				update_post_meta( $post_id, ethnic_case_studies_logo_image_url_meta_key(), esc_url_raw( $item['src'] ) );
			}

			$order++;
		}

		update_option( 'ethnic_case_studies_logo_library_seed_version', $seed_version, false );
	}
	add_action( 'admin_init', 'ethnic_case_studies_seed_logo_library' );
}

if ( ! function_exists( 'ethnic_case_studies_logo_columns' ) ) {
	function ethnic_case_studies_logo_columns( $columns ) {
		$ordered = array();

		foreach ( $columns as $key => $label ) {
			if ( 'title' === $key ) {
				$ordered['ethnic_logo_preview'] = 'Logo';
			}

			$ordered[ $key ] = $label;
		}

		return $ordered;
	}
	add_filter( 'manage_' . ETHNIC_CASE_STUDIES_LOGO_POST_TYPE . '_posts_columns', 'ethnic_case_studies_logo_columns' );
}

if ( ! function_exists( 'ethnic_case_studies_render_logo_column' ) ) {
	function ethnic_case_studies_render_logo_column( $column, $post_id ) {
		if ( 'ethnic_logo_preview' !== $column ) {
			return;
		}

		$image_url = ethnic_case_studies_logo_image_url( $post_id, 'thumbnail' );

		if ( '' !== $image_url ) {
			printf(
				'<img src="%1$s" alt="" style="max-width:56px;max-height:32px;width:auto;height:auto;" />',
				esc_url( $image_url )
			);
			return;
		}

		echo '<span style="color:#6a7691;">No logo</span>';
	}
	add_action( 'manage_' . ETHNIC_CASE_STUDIES_LOGO_POST_TYPE . '_posts_custom_column', 'ethnic_case_studies_render_logo_column', 10, 2 );
}

if ( ! function_exists( 'ethnic_case_studies_ensure_logo_post' ) ) {
	function ethnic_case_studies_ensure_logo_post( $slug ) {
		$slug    = sanitize_title( (string) $slug );
		$catalog = ethnic_case_studies_stack_logo_catalog();

		if ( '' === $slug || empty( $catalog[ $slug ] ) ) {
			return 0;
		}

		$item  = $catalog[ $slug ];
		$label = isset( $item['label'] ) ? ethnic_case_studies_text( $item['label'] ) : '';

		if ( '' === $label ) {
			return 0;
		}

		$existing = get_page_by_path( $slug, OBJECT, ETHNIC_CASE_STUDIES_LOGO_POST_TYPE );
		$post_id  = $existing instanceof WP_Post ? (int) $existing->ID : 0;

		if ( $post_id <= 0 ) {
			$post_id = wp_insert_post(
				array(
					'post_type'   => ETHNIC_CASE_STUDIES_LOGO_POST_TYPE,
					'post_status' => 'publish',
					'post_title'  => $label,
					'post_name'   => $slug,
				)
			);
		}

		if ( is_wp_error( $post_id ) || $post_id <= 0 ) {
			return 0;
		}

		if ( ! empty( $item['src'] ) ) {
			update_post_meta( $post_id, ethnic_case_studies_logo_image_url_meta_key(), esc_url_raw( $item['src'] ) );
		}

		return (int) $post_id;
	}
}

if ( ! function_exists( 'ethnic_case_studies_sideload_remote_attachment' ) ) {
	function ethnic_case_studies_sideload_remote_attachment( $post_id, $source_url, $alt = '' ) {
		$post_id    = (int) $post_id;
		$source_url = esc_url_raw( $source_url );
		$alt        = sanitize_text_field( $alt );

		if ( $post_id <= 0 || '' === $source_url ) {
			return 0;
		}

		$existing_ids = get_posts(
			array(
				'post_type'              => 'attachment',
				'post_status'            => 'inherit',
				'posts_per_page'         => 1,
				'fields'                 => 'ids',
				'meta_query'             => array(
					array(
						'key'     => '_ethnic_case_study_source_url',
						'value'   => $source_url,
						'compare' => '=',
					),
				),
				'ignore_sticky_posts'    => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'no_found_rows'          => true,
			)
		);

		$attachment_id = ! empty( $existing_ids ) ? (int) $existing_ids[0] : 0;

		if ( $attachment_id <= 0 ) {
			if ( ! function_exists( 'download_url' ) ) {
				require_once ABSPATH . 'wp-admin/includes/file.php';
			}
			if ( ! function_exists( 'media_handle_sideload' ) ) {
				require_once ABSPATH . 'wp-admin/includes/media.php';
			}
			if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
				require_once ABSPATH . 'wp-admin/includes/image.php';
			}

			$temp_file = download_url( $source_url, 20 );

			if ( is_wp_error( $temp_file ) ) {
				return 0;
			}

			$filename   = wp_basename( (string) wp_parse_url( $source_url, PHP_URL_PATH ) );
			$file_array = array(
				'name'     => $filename ? $filename : 'case-study-visual',
				'tmp_name' => $temp_file,
			);

			$attachment_id = media_handle_sideload(
				$file_array,
				$post_id,
				null,
				array(
					'post_status' => 'inherit',
				)
			);

			if ( is_wp_error( $attachment_id ) ) {
				@unlink( $temp_file );
				return 0;
			}

			update_post_meta( $attachment_id, '_ethnic_case_study_source_url', $source_url );
		}

		if ( $attachment_id > 0 ) {
			wp_update_post(
				array(
					'ID'          => $attachment_id,
					'post_parent' => $post_id,
				)
			);

			if ( '' !== $alt ) {
				update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt );
			}
		}

		return (int) $attachment_id;
	}
}

if ( ! function_exists( 'ethnic_case_studies_assign_terms' ) ) {
	function ethnic_case_studies_assign_terms( $post_id, $taxonomy, $terms ) {
		$terms = array_values(
			array_filter(
				array_map(
					static function ( $term ) {
						return ethnic_case_studies_text( $term );
					},
					(array) $terms
				)
			)
		);

		if ( empty( $terms ) ) {
			return;
		}

		$term_ids = array();

		foreach ( $terms as $term_name ) {
			$existing = term_exists( $term_name, $taxonomy );

			if ( ! $existing ) {
				$existing = wp_insert_term( $term_name, $taxonomy );
			}

			if ( is_wp_error( $existing ) || empty( $existing ) ) {
				continue;
			}

			$term_ids[] = is_array( $existing ) ? (int) $existing['term_id'] : (int) $existing;
		}

		if ( ! empty( $term_ids ) ) {
			wp_set_object_terms( $post_id, $term_ids, $taxonomy, false );
		}
	}
}

if ( ! function_exists( 'ethnic_case_studies_seed_mica_lighting_case_study' ) ) {
	function ethnic_case_studies_seed_mica_lighting_case_study() {
		$seed_version = '20260501.3';

		if ( get_option( 'ethnic_case_studies_mica_lighting_seed_version' ) === $seed_version ) {
			return;
		}

		$post = get_page_by_path( 'omnichannel-retail-app-modernization', OBJECT, ETHNIC_CASE_STUDIES_POST_TYPE );

		if ( ! ( $post instanceof WP_Post ) ) {
			return;
		}

		$post_id        = (int) $post->ID;
		$services_url   = home_url( '/services/' );
		$retail_url     = home_url( '/industries/retail-ecommerce-solutions/' );
		$contact_url    = home_url( '/contact-us/' );
		$fusion5_video  = 'https://ethnicinfotech.com/wp-content/uploads/2025/10/fusion5-1.mp4';
		$fusion5_poster = content_url( 'uploads/2026/05/fusion5-poster.png' );

		$content_fields = array(
			'client_name'              => 'MICA Lighting',
			'hero_subtitle'            => 'Fusion5 is a Magento modernization project for MICA Lighting, focused on better product discovery, wholesale-direct commerce, and a smoother mobile shopping experience.',
			'hero_highlights'          => implode(
				"\n",
				array(
					'Magento migration',
					'Advanced catalog filtering',
					'B2C + B2B pricing support',
					'SEO and mobile optimization',
				)
			),
			'hero_media_url'           => $fusion5_video,
			'project_type_override'    => 'eCommerce Modernization',
			'service_override'         => 'eCommerce Development, Magento Development',
			'platform_override'        => 'Magento, Hyva',
			'industry_override'        => 'Retail, Wholesale Lighting',
			'overview_heading'         => 'Who MICA Lighting is and what the platform needed to support.',
			'overview_paragraphs'      => implode(
				"\n\n",
				array(
					'MICA Lighting is a trusted family-owned Australian business offering thousands of stylish and affordable lighting products for homeowners who want design-led options without losing value or practicality.',
					'As the catalog expanded, the storefront needed to support better discovery, stronger performance, and cleaner buying journeys for both direct retail customers and wholesale-oriented buyers.',
				)
			),
			'overview_facts'           => implode(
				"\n",
				array(
					'Region | Australia',
					'Industry | Retail and wholesale lighting',
					'Company Type | Family-owned lighting retailer',
					'Services Delivered | Magento migration, storefront customization, performance optimization',
					'Engagement Type | Growth-focused eCommerce modernization',
				)
			),
			'challenge_heading'        => 'The commerce experience needed to handle a complex lighting catalog without slowing down discovery or checkout.',
			'challenge_intro'          => 'The existing store had to do more than display products. It needed to make a large catalog easier to navigate, support different pricing expectations, and perform reliably across desktop and mobile.',
			'challenges'               => implode(
				"\n",
				array(
					'Complex product variations | Thousands of lighting products needed clear handling for size, finish, wattage, and other option combinations.',
					'Product discovery friction | Shoppers needed better navigation and filtering to reach the right fixtures faster across a broad catalog.',
					'Dual pricing expectations | The storefront had to support both B2C purchases and wholesale-direct pricing without creating confusion.',
					'Performance and mobile pressure | Slow pages and weaker responsive journeys risked hurting engagement, search visibility, and conversion.',
					'Operational scalability | The platform needed a stronger technical base for secure transactions, merchandising updates, and nationwide shipping flows.',
				)
			),
			'goals_heading'            => 'The objectives that shaped the Magento modernization from planning through launch.',
			'goals'                    => implode(
				"\n",
				array(
					'Improve product discovery | Make it easier for shoppers to browse, filter, compare, and choose the right lighting products.',
					'Support retail and wholesale journeys | Create a storefront structure that handles B2C and B2B pricing models more cleanly.',
					'Improve speed and responsiveness | Reduce friction with faster loading pages and a smoother mobile shopping experience.',
					'Strengthen commerce fundamentals | Support secure transactions, clearer checkout, and dependable shipping options across Australia.',
					'Build for growth | Deliver a Magento setup that stays flexible as the catalog, merchandising needs, and customer expectations evolve.',
				)
			),
			'solution_heading'         => 'How the Magento store was migrated, customized, and prepared for long-term commerce growth.',
			'solution_paragraphs'      => implode(
				"\n\n",
				array(
					'The engagement began with a focused review of catalog structure, shopper behavior, and the biggest friction points across browsing, filtering, pricing, and checkout. That surfaced where UX changes and platform improvements would create the most value first.',
					'We then migrated and customized Magento around the realities of a large lighting catalog. Product data was organized to better handle option-heavy SKUs, while navigation and advanced filtering were refined to shorten the path from discovery to purchase.',
					'Alongside storefront improvements, the delivery strengthened performance, mobile responsiveness, SEO readiness, secure transactions, and shipping flexibility so the business could serve both retail and wholesale buyers more effectively.',
				)
			),
			'solution_pillars'         => implode(
				"\n",
				array(
					'Magento migration and customization | Reworked the commerce foundation around catalog depth, pricing needs, and future scale.',
					'Discovery-led storefront UX | Improved navigation, filtering, and page structure so customers could find relevant products faster.',
					'Growth-focused optimization | Balanced performance, mobile usability, SEO, and checkout stability to support long-term conversion goals.',
				)
			),
			'features_heading'         => 'Core commerce capabilities delivered for catalog management, discovery, and checkout flow.',
			'features'                 => implode(
				"\n",
				array(
					'Large catalog product modeling | Structured product data to support lighting variations such as size, finish, and wattage more clearly.',
					'Advanced product filtering | Added smarter filtering and browsing paths to improve findability across a broad catalog.',
					'B2C and wholesale pricing support | Enabled a storefront experience that could better accommodate retail and wholesale-direct buying models.',
					'Mobile-responsive shopping experience | Refined layouts and interaction flows so key journeys worked more smoothly across devices.',
					'Checkout and transaction readiness | Strengthened secure purchase flows and reduced friction in the path to conversion.',
					'Shipping flexibility across Australia | Supported multiple shipping options to better serve nationwide fulfillment needs.',
					'SEO and performance improvements | Optimized storefront foundations to improve speed, visibility, and overall usability.',
				)
			),
			'tech_stack_heading'       => 'Platform and implementation layers used to modernize the MICA Lighting storefront.',
			'tech_stack'               => implode(
				"\n",
				array(
					'Commerce Platform | Magento, Hyva',
					'Frontend Experience | Responsive interface, Product catalog, Advanced filters',
					'Backend Services | PHP, REST API',
					'Analytics and Growth | GA4, GTM',
				)
			),
			'timeline_heading'         => 'How the engagement moved from storefront audit to launch-ready commerce improvements.',
			'timeline'                 => implode(
				"\n",
				array(
					'Discovery and audit | Reviewed catalog structure, current UX, pricing needs, and performance gaps across the Magento storefront.',
					'Commerce architecture planning | Prioritized product data handling, filtering logic, checkout flow, and wholesale support requirements.',
					'Magento customization | Implemented storefront, catalog, and pricing improvements tailored to lighting-specific commerce needs.',
					'UX and responsive refinement | Improved navigation, mobile usability, and on-page structure for smoother product discovery.',
					'Performance, SEO, and QA | Optimized speed, search visibility, and release stability before rollout.',
					'Launch and iteration support | Coordinated go-live readiness and prepared the store for continued commerce enhancement.',
				)
			),
			'engagement_summary'       => implode(
				"\n",
				array(
					'Timeline | Phased delivery aligned to migration, UX refinement, and launch readiness',
					'Engagement Model | Magento modernization and storefront customization',
					'Collaboration | Business requirements, UX review, engineering execution, and QA checkpoints',
					'Support | Launch coordination plus room for continued commerce optimization',
				)
			),
			'results_heading'          => 'The business outcomes created by the Magento modernization.',
			'result_cards'             => implode(
				"\n",
				array(
					'Feature-rich | commerce platform | Magento was tailored into a stronger foundation for a growing lighting business.',
					'Improved | usability | Cleaner navigation and shopping flows made the experience easier to use.',
					'Smarter | product discovery | Advanced search and filtering improved findability across thousands of SKUs.',
					'Faster | checkout flow | Reduced friction helped move shoppers more smoothly toward purchase.',
					'Scalable | operations | The platform is better prepared to support both retail and wholesale-direct growth.',
				)
			),
			'impact_cards'             => implode(
				"\n",
				array(
					'Better merchandising control | A clearer catalog and storefront structure made it easier to surface the right products to the right buyers.',
					'Stronger customer experience | Shoppers could browse, compare, and purchase lighting products with less confusion and fewer dead ends.',
					'Improved mobile readiness | The responsive experience supports discovery and checkout more reliably on smaller screens.',
					'More durable growth foundation | Magento, performance work, and structured pricing support created a better base for future expansion.',
				)
			),
			'gallery_heading'          => 'Selected visuals from the upgraded storefront experience.',
			'gallery_items'            => implode(
				"\n",
				array(
					$fusion5_video . ' | Fusion5 storefront walkthrough | Primary Fusion5 experience walkthrough',
					$fusion5_video . ' | Fusion5 product discovery flow | Product browsing and filtering motion preview',
					$fusion5_video . ' | Fusion5 responsive commerce view | Mobile-ready shopping and conversion flow',
				)
			),
			'related_services_heading' => 'Services connected to similar commerce modernization work.',
			'related_services'         => implode(
				"\n",
				array(
					'eCommerce Development | Build growth-ready storefronts with stronger merchandising, conversion paths, and operational alignment. | ' . $services_url,
					'Retail & eCommerce Solutions | Explore how we support modern retail platforms across experience, performance, and operational scale. | ' . $retail_url,
					'Support & Maintenance | Keep storefront releases, performance improvements, and post-launch optimization moving with the right support model. | ' . $contact_url,
				)
			),
			'cta_heading'              => 'Need a Magento or eCommerce modernization partner?',
			'cta_copy'                 => 'If you are planning a catalog migration, storefront redesign, B2B and B2C pricing rollout, or performance-focused commerce upgrade, we can help shape the right delivery path.',
			'cta_primary_label'        => 'Start Your Commerce Project',
			'cta_secondary_label'      => 'Book a Free Consultation',
		);

		foreach ( $content_fields as $field => $value ) {
			$meta_key = ethnic_case_studies_content_meta_key( $field );
			$value    = trim( (string) $value );

			if ( '' === $value ) {
				delete_post_meta( $post_id, $meta_key );
			} else {
				update_post_meta( $post_id, $meta_key, $value );
			}
		}

		update_post_meta( $post_id, '_thegem_cf_client', 'MICA Lighting' );

		$logo_ids = array_values(
			array_filter(
				array_map(
					'intval',
					array(
						ethnic_case_studies_ensure_logo_post( 'magento' ),
						ethnic_case_studies_ensure_logo_post( 'hyva' ),
					)
				)
			)
		);

		if ( empty( $logo_ids ) ) {
			delete_post_meta( $post_id, ethnic_case_studies_logo_selection_meta_key() );
		} else {
			update_post_meta( $post_id, ethnic_case_studies_logo_selection_meta_key(), $logo_ids );
		}

		$attachment_id = ethnic_case_studies_sideload_remote_attachment( $post_id, $fusion5_poster, 'Fusion5 video poster' );

		if ( $attachment_id > 0 ) {
			set_post_thumbnail( $post_id, $attachment_id );
		}

		wp_update_post(
			array(
				'ID'           => $post_id,
				'post_title'   => 'Fusion5',
				'post_excerpt' => 'Fusion5 is a Magento modernization project for an Australian lighting retailer, focused on advanced filtering, dual pricing support, and a faster shopping experience.',
				'post_content' => '<p><strong>Challenge:</strong> Fusion5 needed a Magento storefront that could handle a large lighting catalog, support complex product variations, and improve discovery for both retail and wholesale-oriented buyers.</p>
<p><strong>Solution:</strong> We migrated and customized Magento for MICA Lighting with stronger catalog handling, advanced filtering, responsive UX improvements, and better support for B2C and B2B pricing, performance, SEO, and shipping flexibility.</p>
<p><strong>Outcome:</strong> The result was a feature-rich commerce platform with better usability, smarter product discovery, a smoother checkout path, and a more scalable base for long-term growth.</p>',
			)
		);

		update_option( 'ethnic_case_studies_mica_lighting_seed_version', $seed_version, false );
	}
	add_action( 'init', 'ethnic_case_studies_seed_mica_lighting_case_study', 60 );
}

if ( ! function_exists( 'ethnic_case_studies_default_featured_slugs' ) ) {
	function ethnic_case_studies_default_featured_slugs() {
		return array(
			'omnichannel-retail-app-modernization',
			'field-operations-workflow-platform',
			'digital-onboarding-client-portal',
		);
	}
}

if ( ! function_exists( 'ethnic_case_studies_fill_excerpt_if_missing' ) ) {
	function ethnic_case_studies_fill_excerpt_if_missing( $post_id ) {
		$post = get_post( $post_id );

		if ( ! ( $post instanceof WP_Post ) || has_excerpt( $post ) ) {
			return;
		}

		$summary = ethnic_case_studies_get_summary( $post_id );

		if ( '' !== $summary ) {
			remove_action( 'save_post_' . ETHNIC_CASE_STUDIES_POST_TYPE, 'ethnic_case_studies_save_meta_box' );

			wp_update_post(
				array(
					'ID'           => $post_id,
					'post_excerpt' => $summary,
				)
			);

			add_action( 'save_post_' . ETHNIC_CASE_STUDIES_POST_TYPE, 'ethnic_case_studies_save_meta_box' );
		}
	}
}

if ( ! function_exists( 'ethnic_case_studies_fill_thumbnail_if_missing' ) ) {
	function ethnic_case_studies_fill_thumbnail_if_missing( $post_id ) {
		if ( has_post_thumbnail( $post_id ) ) {
			return;
		}

		$gallery_ids = get_post_meta( $post_id, 'thegem_portfolio_item_gallery_images', true );

		if ( empty( $gallery_ids ) ) {
			return;
		}

		$first_id = (int) current( array_filter( array_map( 'intval', explode( ',', (string) $gallery_ids ) ) ) );

		if ( $first_id > 0 ) {
			set_post_thumbnail( $post_id, $first_id );
		}
	}
}

if ( ! function_exists( 'ethnic_case_studies_migrate_content_model' ) ) {
	function ethnic_case_studies_migrate_content_model() {
		$lock_key = 'ethnic_case_studies_migration_lock';

		if ( get_transient( $lock_key ) ) {
			return;
		}

		set_transient( $lock_key, 1, 5 * MINUTE_IN_SECONDS );

		$taxonomies = ethnic_case_studies_taxonomies();
		$post_ids   = get_posts(
			array(
				'post_type'              => ETHNIC_CASE_STUDIES_POST_TYPE,
				'post_status'            => 'publish',
				'posts_per_page'         => -1,
				'fields'                 => 'ids',
				'orderby'                => array(
					'menu_order' => 'ASC',
					'date'       => 'DESC',
				),
				'ignore_sticky_posts'    => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'no_found_rows'          => true,
			)
		);

		foreach ( $post_ids as $post_id ) {
			if ( ethnic_case_studies_is_demo_post( $post_id ) ) {
				continue;
			}

			ethnic_case_studies_assign_terms( $post_id, $taxonomies['category'], ethnic_case_studies_infer_category_terms( $post_id ) );
			ethnic_case_studies_assign_terms( $post_id, $taxonomies['service'], ethnic_case_studies_infer_service_terms( $post_id ) );
			ethnic_case_studies_assign_terms( $post_id, $taxonomies['platform'], ethnic_case_studies_infer_platform_terms( $post_id ) );
			ethnic_case_studies_assign_terms( $post_id, $taxonomies['industry'], ethnic_case_studies_infer_industry_terms( $post_id ) );
			ethnic_case_studies_fill_excerpt_if_missing( $post_id );
			ethnic_case_studies_fill_thumbnail_if_missing( $post_id );
		}

		$featured_ids = get_posts(
			array(
				'post_type'              => ETHNIC_CASE_STUDIES_POST_TYPE,
				'post_status'            => 'publish',
				'posts_per_page'         => 3,
				'fields'                 => 'ids',
				'meta_query'             => array(
					array(
						'key'     => ethnic_case_studies_featured_meta_key(),
						'value'   => '1',
						'compare' => '=',
					),
				),
				'ignore_sticky_posts'    => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				'no_found_rows'          => true,
			)
		);

		if ( empty( $featured_ids ) ) {
			$featured_ids = array();

			foreach ( ethnic_case_studies_default_featured_slugs() as $slug ) {
				$post = get_page_by_path( $slug, OBJECT, ETHNIC_CASE_STUDIES_POST_TYPE );

				if ( $post instanceof WP_Post && ! ethnic_case_studies_is_demo_post( $post ) ) {
					$featured_ids[] = (int) $post->ID;
				}
			}

			if ( count( $featured_ids ) < 3 ) {
				$fallback_ids = get_posts(
					ethnic_case_studies_build_query_args(
						array(),
						array(
							'posts_per_page'         => 3,
							'fields'                 => 'ids',
							'update_post_meta_cache' => false,
							'update_post_term_cache' => false,
							'no_found_rows'          => true,
						)
					)
				);

				$featured_ids = array_values( array_unique( array_merge( $featured_ids, array_map( 'intval', $fallback_ids ) ) ) );
			}

			$featured_ids = array_slice( $featured_ids, 0, 3 );

			foreach ( $featured_ids as $featured_id ) {
				update_post_meta( $featured_id, ethnic_case_studies_featured_meta_key(), 1 );
			}
		}

		update_option( 'ethnic_case_studies_architecture_version', ETHNIC_CASE_STUDIES_VERSION );
		ethnic_case_studies_register_legacy_rewrites();
		flush_rewrite_rules( false );
		delete_transient( $lock_key );
	}
}

if ( ! function_exists( 'ethnic_case_studies_maybe_migrate' ) ) {
	function ethnic_case_studies_maybe_migrate() {
		if ( get_option( 'ethnic_case_studies_architecture_version' ) === ETHNIC_CASE_STUDIES_VERSION ) {
			return;
		}

		ethnic_case_studies_migrate_content_model();
	}
	add_action( 'init', 'ethnic_case_studies_maybe_migrate', 50 );
}

if ( ! function_exists( 'ethnic_case_studies_query_vars' ) ) {
	function ethnic_case_studies_query_vars( $vars ) {
		$vars[] = 'ethnic_case_study_legacy_slug';
		$vars[] = 'ethnic_case_study_legacy_archive';
		$vars[] = 'ethnic_case_study_archive_variant';

		return $vars;
	}
	add_filter( 'query_vars', 'ethnic_case_studies_query_vars' );
}

if ( ! function_exists( 'ethnic_case_studies_parse_request' ) ) {
	function ethnic_case_studies_parse_request( $wp ) {
		if ( ! ( $wp instanceof WP ) || is_admin() || wp_doing_ajax() ) {
			return;
		}

		$matched_single = ethnic_case_studies_match_single_request( isset( $wp->request ) ? $wp->request : '' );

		if ( ! empty( $matched_single ) ) {
			$query_vars = array(
				'post_type'                         => ETHNIC_CASE_STUDIES_POST_TYPE,
				'name'                              => $matched_single['name'],
				'ethnic_case_study_archive_variant' => $matched_single['variant'],
			);

			unset( $wp->query_vars['error'] );
			unset( $wp->query_vars['pagename'] );
			unset( $wp->query_vars['page_id'] );

			$wp->query_vars    = array_merge( $wp->query_vars, $query_vars );
			$wp->matched_rule  = 'ethnic-case-studies-direct-single-route';
			$wp->matched_query = http_build_query( $query_vars, '', '&' );

			return;
		}

		$matched_archive = ethnic_case_studies_match_archive_request( isset( $wp->request ) ? $wp->request : '' );

		if ( empty( $matched_archive ) ) {
			return;
		}

		$query_vars = array(
			'post_type'                         => ETHNIC_CASE_STUDIES_POST_TYPE,
			'ethnic_case_study_archive_variant' => $matched_archive['variant'],
		);

		if ( ! empty( $matched_archive['paged'] ) && (int) $matched_archive['paged'] > 1 ) {
			$query_vars['paged'] = (int) $matched_archive['paged'];
		}

		unset( $wp->query_vars['error'] );
		unset( $wp->query_vars['pagename'] );
		unset( $wp->query_vars['page_id'] );

		$wp->query_vars   = array_merge( $wp->query_vars, $query_vars );
		$wp->matched_rule = 'ethnic-case-studies-direct-route';
		$wp->matched_query = http_build_query( $query_vars, '', '&' );
	}
	add_action( 'parse_request', 'ethnic_case_studies_parse_request', 5 );
}

if ( ! function_exists( 'ethnic_case_studies_prime_archive_query' ) ) {
	function ethnic_case_studies_prime_archive_query( $wp_query, $variant, $paged = 1 ) {
		if ( ! ( $wp_query instanceof WP_Query ) ) {
			return;
		}

		$variant = ethnic_case_studies_resolve_archive_variant_slug( $variant );

		if ( '' === $variant ) {
			return;
		}

		$post_type_object = get_post_type_object( ETHNIC_CASE_STUDIES_POST_TYPE );

		$wp_query->is_404              = false;
		$wp_query->is_archive          = true;
		$wp_query->is_post_type_archive = true;
		$wp_query->is_home             = false;
		$wp_query->is_page             = false;
		$wp_query->is_singular         = false;
		$wp_query->is_single           = false;

		$wp_query->query_vars['post_type']                         = ETHNIC_CASE_STUDIES_POST_TYPE;
		$wp_query->query_vars['ethnic_case_study_archive_variant'] = $variant;
		$wp_query->query['post_type']                              = ETHNIC_CASE_STUDIES_POST_TYPE;
		$wp_query->query['ethnic_case_study_archive_variant']      = $variant;

		if ( $paged > 1 ) {
			$wp_query->query_vars['paged'] = (int) $paged;
			$wp_query->query['paged']      = (int) $paged;
		}

		$wp_query->queried_object    = $post_type_object;
		$wp_query->queried_object_id = 0;
	}
}

if ( ! function_exists( 'ethnic_case_studies_template_include' ) ) {
	function ethnic_case_studies_template_include( $template ) {
		if ( ! is_404() || is_admin() || wp_doing_ajax() ) {
			return $template;
		}

		$matched_archive = ethnic_case_studies_match_archive_request();

		if ( empty( $matched_archive ) ) {
			return $template;
		}

		global $wp_query;

		ethnic_case_studies_prime_archive_query( $wp_query, $matched_archive['variant'], $matched_archive['paged'] );
		status_header( 200 );

		$archive_template = locate_template(
			array(
				'archive-' . ETHNIC_CASE_STUDIES_POST_TYPE . '.php',
				'archive.php',
				'index.php',
			)
		);

		return '' !== $archive_template ? $archive_template : $template;
	}
	add_filter( 'template_include', 'ethnic_case_studies_template_include', 99 );
}

if ( ! function_exists( 'ethnic_case_studies_pre_handle_404' ) ) {
	function ethnic_case_studies_pre_handle_404( $preempt, $wp_query ) {
		if ( ! ( $wp_query instanceof WP_Query ) || ! $wp_query->is_main_query() ) {
			return $preempt;
		}

		$matched_archive = ethnic_case_studies_match_archive_request();

		if ( empty( $matched_archive ) ) {
			return $preempt;
		}

		ethnic_case_studies_prime_archive_query( $wp_query, $matched_archive['variant'], $matched_archive['paged'] );

		return true;
	}
	add_filter( 'pre_handle_404', 'ethnic_case_studies_pre_handle_404', 10, 2 );
}

if ( ! function_exists( 'ethnic_case_studies_register_legacy_rewrites' ) ) {
	function ethnic_case_studies_register_legacy_rewrites() {
		$category_term = null;
		$taxonomies    = ethnic_case_studies_taxonomies();
		$terms         = get_terms(
			array(
				'taxonomy'   => $taxonomies['category'],
				'hide_empty' => false,
				'orderby'    => 'name',
				'order'      => 'ASC',
			)
		);

		if ( is_array( $terms ) ) {
			foreach ( $terms as $term ) {
				if ( ! ( $term instanceof WP_Term ) ) {
					continue;
				}

				$slug = sanitize_title( $term->slug );

				if ( '' === $slug ) {
					continue;
				}

				add_rewrite_rule( '^case-studies/' . preg_quote( $slug, '/' ) . '/page/([0-9]+)/?$', 'index.php?post_type=' . ETHNIC_CASE_STUDIES_POST_TYPE . '&ethnic_case_study_archive_variant=' . $slug . '&paged=$matches[1]', 'top' );
				add_rewrite_rule( '^case-studies/' . preg_quote( $slug, '/' ) . '/([^/]+)/?$', 'index.php?post_type=' . ETHNIC_CASE_STUDIES_POST_TYPE . '&name=$matches[1]&ethnic_case_study_archive_variant=' . $slug, 'top' );
				add_rewrite_rule( '^case-studies/' . preg_quote( $slug, '/' ) . '/?$', 'index.php?post_type=' . ETHNIC_CASE_STUDIES_POST_TYPE . '&ethnic_case_study_archive_variant=' . $slug, 'top' );
			}
		}

		add_rewrite_rule( '^our-works/?$', 'index.php?ethnic_case_study_legacy_archive=1', 'top' );
		add_rewrite_rule( '^our-works/page/([0-9]+)/?$', 'index.php?ethnic_case_study_legacy_archive=1&paged=$matches[1]', 'top' );
		add_rewrite_rule( '^projects/?$', 'index.php?ethnic_case_study_legacy_archive=1', 'top' );
		add_rewrite_rule( '^projects/(?:.+/)?([^/]+)/?$', 'index.php?ethnic_case_study_legacy_slug=$matches[1]', 'top' );
	}
	add_action( 'init', 'ethnic_case_studies_register_legacy_rewrites', 30 );
}

if ( ! function_exists( 'ethnic_case_studies_flush_rewrite_rules' ) ) {
	function ethnic_case_studies_flush_rewrite_rules() {
		ethnic_case_studies_register_legacy_rewrites();
		flush_rewrite_rules( false );
	}
}

add_action( 'created_ethnic_case_study_category', 'ethnic_case_studies_flush_rewrite_rules' );
add_action( 'edited_ethnic_case_study_category', 'ethnic_case_studies_flush_rewrite_rules' );
add_action( 'delete_ethnic_case_study_category', 'ethnic_case_studies_flush_rewrite_rules' );

if ( ! function_exists( 'ethnic_case_studies_redirect_legacy_requests' ) ) {
	function ethnic_case_studies_redirect_legacy_requests() {
		if ( is_admin() || wp_doing_ajax() ) {
			return;
		}

		if ( is_post_type_archive( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			$selector_request = false;

			foreach ( array( 'service_selector', 'platform_selector', 'industry_selector' ) as $selector_key ) {
				if ( isset( $_GET[ $selector_key ] ) ) {
					$selector_request = true;
					break;
				}
			}

			if ( $selector_request ) {
				wp_safe_redirect( ethnic_case_studies_normalized_archive_url_from_request(), 302 );
				exit;
			}
		}

		$is_legacy_page = false;
		$old_page_id    = ethnic_case_studies_old_archive_page_id();

		if ( get_query_var( 'ethnic_case_study_legacy_archive' ) ) {
			$is_legacy_page = true;
		} elseif ( $old_page_id && is_page( $old_page_id ) ) {
			$is_legacy_page = true;
		}

		if ( $is_legacy_page ) {
			wp_safe_redirect( ethnic_case_studies_archive_url(), 301 );
			exit;
		}

		$legacy_slug = sanitize_title( (string) get_query_var( 'ethnic_case_study_legacy_slug' ) );

		if ( '' !== $legacy_slug ) {
			$post = get_page_by_path( $legacy_slug, OBJECT, ETHNIC_CASE_STUDIES_POST_TYPE );

			if ( $post instanceof WP_Post ) {
				wp_safe_redirect( ethnic_case_studies_single_url( $post ), 301 );
				exit;
			}
		}

		if ( is_singular( ETHNIC_CASE_STUDIES_POST_TYPE ) && ! is_preview() ) {
			$post = get_queried_object();

			if ( $post instanceof WP_Post ) {
				$preferred_url = ethnic_case_studies_single_url( $post );
				$current_path  = '/' . trim( (string) wp_parse_url( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '', PHP_URL_PATH ), '/' ) . '/';
				$preferred_path = '/' . trim( (string) wp_parse_url( $preferred_url, PHP_URL_PATH ), '/' ) . '/';

				if ( '' !== $preferred_url && $preferred_path !== $current_path ) {
					wp_safe_redirect( $preferred_url, 301 );
					exit;
				}
			}
		}
	}
	add_action( 'template_redirect', 'ethnic_case_studies_redirect_legacy_requests', 1 );
}

if ( ! function_exists( 'ethnic_case_studies_case_studies_title' ) ) {
	function ethnic_case_studies_case_studies_title() {
		$category_term = ethnic_case_studies_current_category_term();

		if ( ! ( $category_term instanceof WP_Term ) && ethnic_case_studies_is_app_archive_variant() ) {
			return 'App Development Case Studies';
		}

		if ( $category_term instanceof WP_Term ) {
			if ( ethnic_case_studies_is_app_archive_variant( $category_term->slug ) ) {
				return 'App Development Case Studies';
			}

			return ethnic_case_studies_text( $category_term->name, 'Case Studies' ) . ' Case Studies';
		}

		$filters = ethnic_case_studies_selected_filters();
		$parts   = array();

		foreach ( ethnic_case_studies_filter_definitions() as $key => $definition ) {
			if ( empty( $filters[ $key ] ) ) {
				continue;
			}

			$terms = get_terms(
				array(
					'taxonomy'   => $definition['taxonomy'],
					'hide_empty' => false,
					'slug'       => $filters[ $key ],
				)
			);

			if ( is_array( $terms ) ) {
				$parts = array_merge(
					$parts,
					array_map(
						static function ( $term ) {
							return $term instanceof WP_Term ? $term->name : '';
						},
						$terms
					)
				);
			}
		}

		$parts = array_values( array_filter( array_unique( $parts ) ) );

		if ( empty( $parts ) ) {
			return 'Case Studies';
		}

		return 'Case Studies: ' . implode( ', ', $parts );
	}
}

if ( ! function_exists( 'ethnic_case_studies_archive_seo_title' ) ) {
	function ethnic_case_studies_archive_seo_title( $variant = '' ) {
		$category_term = ethnic_case_studies_category_term_by_slug( $variant );

		if ( ethnic_case_studies_is_app_archive_variant( $variant ) ) {
			return 'App Development Case Studies | Mobile, Web & Custom App Success Stories';
		}

		if ( $category_term instanceof WP_Term ) {
			return ethnic_case_studies_text( $category_term->name, 'Case Studies' ) . ' Case Studies | Client Success Stories & Project Outcomes';
		}

		return 'Case Studies | eCommerce, App Development & Digital Project Success Stories';
	}
}

if ( ! function_exists( 'ethnic_case_studies_document_title' ) ) {
	function ethnic_case_studies_document_title( $title ) {
		if ( is_singular( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			$payload = ethnic_case_studies_build_post_payload( get_queried_object() );

			if ( ! empty( $payload['title'] ) ) {
				return $payload['title'] . ' Case Study | ' . get_bloginfo( 'name' );
			}

			return $title;
		}

		if ( ! is_post_type_archive( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			return $title;
		}

		$variant = ethnic_case_studies_current_archive_variant();

		if ( '' !== $variant ) {
			return ethnic_case_studies_archive_seo_title( $variant );
		}

		$filters = ethnic_case_studies_is_app_archive_variant( $variant ) ? array() : ethnic_case_studies_selected_filters();

		if ( empty( array_filter( $filters ) ) ) {
			return ethnic_case_studies_archive_seo_title( $variant );
		}

		return ethnic_case_studies_case_studies_title() . ' | ' . ethnic_case_studies_archive_seo_title( $variant );
	}
	add_filter( 'pre_get_document_title', 'ethnic_case_studies_document_title', 40 );
}

if ( ! function_exists( 'ethnic_case_studies_archive_meta_description' ) ) {
	function ethnic_case_studies_archive_meta_description( $variant = '' ) {
		$category_term = ethnic_case_studies_category_term_by_slug( $variant );

		if ( ethnic_case_studies_is_app_archive_variant( $variant ) ) {
			return 'Explore app development case studies across mobile apps, web apps, SaaS platforms, Flutter, React Native, iOS, Android, and custom software projects.';
		}

		if ( $category_term instanceof WP_Term ) {
			$description = ethnic_case_studies_text( $category_term->description );

			if ( '' !== $description ) {
				return wp_trim_words( $description, 26, '…' );
			}

			return sprintf( 'Explore %s case studies and client success stories with delivery context, outcomes, and solution-led implementation examples.', strtolower( ethnic_case_studies_text( $category_term->name, 'category' ) ) );
		}

		return 'Explore our case studies and client success stories across eCommerce, app development, web development, integrations, and digital transformation projects.';
	}
}

if ( ! function_exists( 'ethnic_case_studies_output_seo_head' ) ) {
	function ethnic_case_studies_output_seo_head() {
		if ( is_post_type_archive( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			$variant   = ethnic_case_studies_current_archive_variant();
			$canonical = ethnic_case_studies_normalized_archive_url_from_request();
			$context   = ethnic_case_studies_archive_context();
			$posts     = array_merge( $context['featured_posts'], $context['grid_query']->posts );
			$item_list = array();
			$seen_ids  = array();

			foreach ( $posts as $index => $post ) {
				if ( ! ( $post instanceof WP_Post ) || in_array( (int) $post->ID, $seen_ids, true ) ) {
					continue;
				}

				$seen_ids[] = (int) $post->ID;
				$payload = $post instanceof WP_Post ? ethnic_case_studies_build_post_payload( $post ) : array();

				$item_list[] = array(
					'@type'    => 'ListItem',
					'position' => count( $item_list ) + 1,
					'url'      => ! empty( $payload['url'] ) ? $payload['url'] : get_permalink( $post ),
					'name'     => ! empty( $payload['title'] ) ? $payload['title'] : get_the_title( $post ),
				);
			}

			echo "\n" . '<meta name="description" content="' . esc_attr( ethnic_case_studies_archive_meta_description( $variant ) ) . '" />' . "\n";
			echo '<link rel="canonical" href="' . esc_url( $canonical ) . '" />' . "\n";
			echo '<script type="application/ld+json">' . wp_json_encode(
				array(
					'@context'   => 'https://schema.org',
					'@type'      => 'CollectionPage',
					'name'       => ethnic_case_studies_case_studies_title(),
					'description'=> ethnic_case_studies_archive_meta_description( $variant ),
					'url'        => $canonical,
					'mainEntity' => array(
						'@type'           => 'ItemList',
						'itemListElement' => $item_list,
						'numberOfItems'   => count( $item_list ),
					),
				),
				JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
			) . '</script>' . "\n";

			return;
		}

		if ( is_singular( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			$post    = get_queried_object();
			$payload = $post instanceof WP_Post ? ethnic_case_studies_build_post_payload( $post ) : array();
			$detail  = $post instanceof WP_Post && function_exists( 'ethnic_case_studies_single_context' ) ? ethnic_case_studies_single_context( $post ) : array();

			if ( empty( $payload ) ) {
				return;
			}

			$description = ! empty( $detail['subtitle'] ) ? $detail['subtitle'] : $payload['summary'];

			echo "\n" . '<meta name="description" content="' . esc_attr( $description ) . '" />' . "\n";

			echo '<script type="application/ld+json">' . wp_json_encode(
				array(
					'@context'      => 'https://schema.org',
					'@type'         => 'CreativeWork',
					'headline'      => $payload['title'],
					'description'   => $description,
					'url'           => $payload['url'],
					'image'         => $payload['image_url'],
					'datePublished' => get_the_date( 'c', $post ),
					'dateModified'  => get_the_modified_date( 'c', $post ),
					'author'        => array(
						'@type' => 'Organization',
						'name'  => get_bloginfo( 'name' ),
					),
				),
				JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
			) . '</script>' . "\n";
		}
	}
	add_action( 'wp_head', 'ethnic_case_studies_output_seo_head', 6 );
}

if ( ! function_exists( 'ethnic_case_studies_filter_canonical_url' ) ) {
	function ethnic_case_studies_filter_canonical_url( $canonical_url, $post ) {
		if ( ! ( $post instanceof WP_Post ) || ETHNIC_CASE_STUDIES_POST_TYPE !== $post->post_type ) {
			return $canonical_url;
		}

		$payload = ethnic_case_studies_build_post_payload( $post );

		if ( ! empty( $payload['url'] ) ) {
			return $payload['url'];
		}

		return $canonical_url;
	}
	add_filter( 'get_canonical_url', 'ethnic_case_studies_filter_canonical_url', 10, 2 );
}

if ( ! function_exists( 'ethnic_case_studies_body_class' ) ) {
	function ethnic_case_studies_body_class( $classes ) {
		if ( is_post_type_archive( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			$classes[] = 'ethnic-case-studies-archive';

			if ( ethnic_case_studies_current_category_term() instanceof WP_Term ) {
				$classes[] = 'ethnic-case-studies-archive-category';
				$classes[] = 'ethnic-case-studies-archive-category-' . sanitize_html_class( ethnic_case_studies_current_archive_variant() );
			}

			if ( ethnic_case_studies_is_app_archive_variant() ) {
				$classes[] = 'ethnic-case-studies-archive-app-development';
			}
		}

		if ( is_singular( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			$classes[] = 'ethnic-case-study-single';

			if ( ethnic_case_studies_is_app_related_post( get_queried_object_id() ) ) {
				$classes[] = 'ethnic-case-study-single-app-development';
			}
		}

		return $classes;
	}
	add_filter( 'body_class', 'ethnic_case_studies_body_class' );
}

if ( ! function_exists( 'ethnic_case_studies_enqueue_assets' ) ) {
	function ethnic_case_studies_enqueue_assets() {
		if ( ! defined( 'THEGEM_THEME_URI' ) || ! defined( 'THEGEM_THEME_PATH' ) ) {
			return;
		}

		if ( is_post_type_archive( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			$archive_css_relative_path = '/css/ethnic-case-studies-archive.css';
			$archive_css_path          = THEGEM_THEME_PATH . $archive_css_relative_path;

			wp_enqueue_style(
				'ethnic-case-studies-archive',
				THEGEM_THEME_URI . $archive_css_relative_path,
				array(),
				file_exists( $archive_css_path ) ? filemtime( $archive_css_path ) : null
			);
		}

		if ( is_singular( ETHNIC_CASE_STUDIES_POST_TYPE ) ) {
			$single_css_relative_path = '/css/ethnic-case-study-single.css';
			$single_css_path          = THEGEM_THEME_PATH . $single_css_relative_path;

			wp_enqueue_style(
				'ethnic-case-study-single',
				THEGEM_THEME_URI . $single_css_relative_path,
				array(),
				file_exists( $single_css_path ) ? filemtime( $single_css_path ) : null
			);
		}
	}
	add_action( 'wp_enqueue_scripts', 'ethnic_case_studies_enqueue_assets', 40 );
}

if ( ! function_exists( 'ethnic_case_studies_menu_item_is_archive_link' ) ) {
	function ethnic_case_studies_menu_item_is_archive_link( $item ) {
		$url        = '';
		$archive_id = ethnic_case_studies_old_archive_page_id();

		if ( is_object( $item ) ) {
			$url = isset( $item->url ) ? (string) $item->url : '';

			if ( $archive_id && isset( $item->object_id ) && (int) $item->object_id === $archive_id ) {
				return true;
			}
		} elseif ( is_string( $item ) ) {
			$url = $item;
		}

		if ( '' === $url ) {
			return false;
		}

		$path = wp_parse_url( $url, PHP_URL_PATH );
		$path = '/' . trim( (string) $path, '/' ) . '/';

		return in_array( $path, array( '/our-works/', '/case-studies/' ), true );
	}
}

if ( ! function_exists( 'ethnic_case_studies_update_menu_link' ) ) {
	function ethnic_case_studies_update_menu_link( $atts, $item ) {
		if ( ethnic_case_studies_menu_item_is_archive_link( $item ) ) {
			$atts['href'] = ethnic_case_studies_archive_url();
		}

		return $atts;
	}
	add_filter( 'nav_menu_link_attributes', 'ethnic_case_studies_update_menu_link', 10, 2 );
}

if ( ! function_exists( 'ethnic_case_studies_update_menu_title' ) ) {
	function ethnic_case_studies_update_menu_title( $title, $item ) {
		if ( ethnic_case_studies_menu_item_is_archive_link( $item ) ) {
			return 'Case Studies';
		}

		return $title;
	}
	add_filter( 'nav_menu_item_title', 'ethnic_case_studies_update_menu_title', 10, 2 );
}

if ( ! function_exists( 'ethnic_case_studies_disable_legacy_archive_option' ) ) {
	function ethnic_case_studies_disable_legacy_archive_option() {
		return false;
	}
	add_filter( 'thegem_option_portfolio_archive_page', 'ethnic_case_studies_disable_legacy_archive_option' );
}

if ( ! function_exists( 'ethnic_case_studies_exclude_legacy_page_from_sitemap' ) ) {
	function ethnic_case_studies_exclude_legacy_page_from_sitemap( $args, $post_type ) {
		$archive_page_id = ethnic_case_studies_old_archive_page_id();

		if ( $archive_page_id && 'page' === $post_type ) {
			$args['post__not_in']   = isset( $args['post__not_in'] ) ? array_map( 'intval', (array) $args['post__not_in'] ) : array();
			$args['post__not_in'][] = $archive_page_id;
			$args['post__not_in']   = array_values( array_unique( $args['post__not_in'] ) );
		}

		return $args;
	}
	add_filter( 'wp_sitemaps_posts_query_args', 'ethnic_case_studies_exclude_legacy_page_from_sitemap', 10, 2 );
}

if ( ! function_exists( 'ethnic_case_studies_exclude_legacy_page_from_yoast_sitemap' ) ) {
	function ethnic_case_studies_exclude_legacy_page_from_yoast_sitemap( $post_ids ) {
		$archive_page_id = ethnic_case_studies_old_archive_page_id();

		if ( $archive_page_id ) {
			$post_ids[] = $archive_page_id;
		}

		return array_values( array_unique( array_map( 'intval', $post_ids ) ) );
	}
	add_filter( 'wpseo_exclude_from_sitemap_by_post_ids', 'ethnic_case_studies_exclude_legacy_page_from_yoast_sitemap' );
}

if ( ! function_exists( 'ethnic_case_studies_filter_shared_showcase_query_args' ) ) {
	function ethnic_case_studies_filter_shared_showcase_query_args( $args ) {
		$args['post__not_in'] = isset( $args['post__not_in'] ) ? (array) $args['post__not_in'] : array();
		$args['post__not_in'] = array_values(
			array_unique(
				array_merge(
					$args['post__not_in'],
					ethnic_case_studies_demo_post_ids()
				)
			)
		);

		return $args;
	}
	add_filter( 'ethnic_shared_case_studies_query_args', 'ethnic_case_studies_filter_shared_showcase_query_args', 10, 1 );
}