<?php
/**
 * Technicalistic — functions and definitions
 * Dark theme with cyan/purple/gold accents
 *
 * @package Technicalistic
 * @since 3.0.0
 */

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

define( 'TECHNICALISTIC_VERSION', '3.5.0' );
define( 'TECHNICALISTIC_DIR', get_template_directory() );
define( 'TECHNICALISTIC_URI', get_template_directory_uri() );

/**
 * Sets up theme defaults and registers support for various WordPress features.
 */
function technicalistic_setup() {
	add_theme_support( 'automatic-feed-links' );
	add_theme_support( 'title-tag' );
	add_theme_support( 'post-thumbnails' );
	add_theme_support( 'responsive-embeds' );
	add_theme_support( 'editor-styles' );
	add_theme_support(
		'html5',
		array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'style', 'script' )
	);
	add_theme_support( 'wp-block-styles' );
	add_theme_support( 'align-wide' );

	register_nav_menus(
		array(
			'primary' => __( 'Primary Navigation', 'technicalistic' ),
			'footer'  => __( 'Footer Navigation', 'technicalistic' ),
		)
	);
}
add_action( 'after_setup_theme', 'technicalistic_setup' );

/**
 * Enqueue scripts and styles.
 */
function technicalistic_scripts() {
	wp_enqueue_style(
		'technicalistic-style',
		get_stylesheet_uri(),
		array(),
		TECHNICALISTIC_VERSION
	);

	wp_enqueue_style(
		'technicalistic-custom',
		TECHNICALISTIC_URI . '/assets/css/custom.css',
		array( 'technicalistic-style' ),
		TECHNICALISTIC_VERSION
	);

	wp_enqueue_script(
		'technicalistic-scripts',
		TECHNICALISTIC_URI . '/assets/js/theme.js',
		array(),
		TECHNICALISTIC_VERSION,
		true
	);
}
add_action( 'wp_enqueue_scripts', 'technicalistic_scripts' );

/**
 * Enqueue editor styles for dark theme.
 */
function technicalistic_editor_styles() {
	add_editor_style( 'assets/css/custom.css' );
}
add_action( 'after_setup_theme', 'technicalistic_editor_styles' );

/**
 * Register block pattern categories.
 */
function technicalistic_register_pattern_category() {
	register_block_pattern_category(
		'technicalistic',
		array(
			'label'       => __( 'Technicalistic', 'technicalistic' ),
			'description' => __( 'Custom patterns for the Technicalistic theme', 'technicalistic' ),
		)
	);

	register_block_pattern_category(
		'technicalistic-hero',
		array( 'label' => __( 'Hero Sections', 'technicalistic' ) )
	);

	register_block_pattern_category(
		'technicalistic-services',
		array( 'label' => __( 'Services', 'technicalistic' ) )
	);

	register_block_pattern_category(
		'technicalistic-portfolio',
		array( 'label' => __( 'Portfolio', 'technicalistic' ) )
	);

	register_block_pattern_category(
		'technicalistic-cta',
		array( 'label' => __( 'Call to Action', 'technicalistic' ) )
	);

	register_block_pattern_category(
		'technicalistic-coming-soon',
		array( 'label' => __( 'Coming Soon', 'technicalistic' ) )
	);
}
add_action( 'init', 'technicalistic_register_pattern_category' );

/**
 * Register block styles for core blocks.
 */
function technicalistic_register_block_styles() {
	register_block_style(
		'core/button',
		array(
			'name'  => 'technicalistic-gradient',
			'label' => __( 'Gradient', 'technicalistic' ),
		)
	);

	register_block_style(
		'core/group',
		array(
			'name'  => 'technicalistic-glassmorphism',
			'label' => __( 'Glassmorphism', 'technicalistic' ),
		)
	);

	register_block_style(
		'core/image',
		array(
			'name'  => 'technicalistic-glow',
			'label' => __( 'Glow Effect', 'technicalistic' ),
		)
	);
}
add_action( 'init', 'technicalistic_register_block_styles' );

/**
 * Custom excerpt length.
 */
function technicalistic_excerpt_length( $length ) {
	return 30;
}
add_filter( 'excerpt_length', 'technicalistic_excerpt_length' );

/**
 * Custom excerpt more text.
 */
function technicalistic_excerpt_more( $more ) {
	return '&hellip;';
}
add_filter( 'excerpt_more', 'technicalistic_excerpt_more' );

/**
 * Add custom image sizes.
 */
function technicalistic_custom_image_sizes() {
	add_image_size( 'technicalistic-hero', 1920, 800, true );
	add_image_size( 'technicalistic-portfolio', 600, 450, true );
	add_image_size( 'technicalistic-card', 400, 300, true );
}
add_action( 'after_setup_theme', 'technicalistic_custom_image_sizes' );

/**
 * Return a theme image URL from the Customizer, or fall back to the bundled default.
 *
 * @param string $setting      The theme_mod setting name.
 * @param string $default_file The default filename inside assets/images/.
 * @return string Escaped image URL.
 */
function technicalistic_get_theme_image( $setting, $default_file ) {
	$url = get_theme_mod( $setting, '' );
	if ( $url ) {
		return esc_url( $url );
	}
	return esc_url( get_template_directory_uri() . '/assets/images/' . $default_file );
}

/**
 * Register Customizer settings for theme splash images.
 *
 * @param WP_Customize_Manager $wp_customize Customizer manager.
 */
function technicalistic_customize_register( $wp_customize ) {
	$wp_customize->add_section( 'technicalistic_images', array(
		'title'    => __( 'Theme Images', 'technicalistic' ),
		'priority' => 90,
	) );

	$images = array(
		'technicalistic_hero_image'      => array(
			'label'       => __( 'Hero Image (Home Page)', 'technicalistic' ),
			'description' => __( 'The main image in the hero section on the front page.', 'technicalistic' ),
		),
		'technicalistic_portfolio_image' => array(
			'label'       => __( 'Profile Image (Portfolio)', 'technicalistic' ),
			'description' => __( 'The profile photo shown in the portfolio page header.', 'technicalistic' ),
		),
		'technicalistic_art_image'       => array(
			'label'       => __( 'Header Image (Art)', 'technicalistic' ),
			'description' => __( 'The featured image in the art page header.', 'technicalistic' ),
		),
		'technicalistic_blog_image'      => array(
			'label'       => __( 'Header Image (Blog)', 'technicalistic' ),
			'description' => __( 'The featured image in the blog page header.', 'technicalistic' ),
		),
	);

	foreach ( $images as $setting_id => $args ) {
		$wp_customize->add_setting( $setting_id, array(
			'default'           => '',
			'sanitize_callback' => 'esc_url_raw',
		) );

		$wp_customize->add_control( new WP_Customize_Image_Control(
			$wp_customize,
			$setting_id,
			array(
				'label'       => $args['label'],
				'description' => $args['description'],
				'section'     => 'technicalistic_images',
			)
		) );
	}
}
add_action( 'customize_register', 'technicalistic_customize_register' );

/**
 * Sanitize checkbox values for the Customizer.
 *
 * @param mixed $checked The checkbox value.
 * @return bool
 */
function technicalistic_sanitize_checkbox( $checked ) {
	return ( isset( $checked ) && true == $checked ) ? true : false;
}

/**
 * Register Customizer settings for theme links and toggles.
 *
 * @param WP_Customize_Manager $wp_customize Customizer manager.
 */
function technicalistic_customize_links( $wp_customize ) {
	$wp_customize->add_section( 'technicalistic_links', array(
		'title'    => __( 'Theme Links', 'technicalistic' ),
		'priority' => 91,
	) );

	$wp_customize->add_setting( 'technicalistic_show_view_services', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_view_services', array(
		'label'   => __( 'Show "View Services" button (Hero)', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_view_services_url', array(
		'default'           => '/portfolio/',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_view_services_url', array(
		'label'       => __( '"View Services" Button URL', 'technicalistic' ),
		'description' => __( 'Primary CTA button in the hero section.', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );

	$wp_customize->add_setting( 'technicalistic_show_get_in_touch', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_get_in_touch', array(
		'label'   => __( 'Show "Get in Touch" button (Hero)', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_get_in_touch_url', array(
		'default'           => '/contact/',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_get_in_touch_url', array(
		'label'       => __( '"Get in Touch" Button URL', 'technicalistic' ),
		'description' => __( 'Secondary CTA button in the hero section.', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );

	$wp_customize->add_setting( 'technicalistic_show_schedule_consultation', array(
		'default'           => false,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_schedule_consultation', array(
		'label'   => __( 'Show "Schedule a Consultation" button (CTA)', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_schedule_consultation_url', array(
		'default'           => '/contact/',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_schedule_consultation_url', array(
		'label'       => __( '"Schedule a Consultation" URL', 'technicalistic' ),
		'description' => __( 'URL for the consultation CTA button.', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );

	$wp_customize->add_setting( 'technicalistic_show_explore_services', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_explore_services', array(
		'label'   => __( 'Show "Explore Services" button (CTA)', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_explore_services_url', array(
		'default'           => '/portfolio/',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_explore_services_url', array(
		'label'       => __( '"Explore Services" Button URL', 'technicalistic' ),
		'description' => __( 'CTA button at the bottom of the home page.', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );

	$wp_customize->add_setting( 'technicalistic_show_shop_link', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_shop_link', array(
		'label'   => __( 'Show "Visit Shop" link (Art page)', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_shop_url', array(
		'default'           => '/store',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_shop_url', array(
		'label'       => __( 'Shop URL', 'technicalistic' ),
		'description' => __( '"Visit Shop" link on the Art page header. Default: /store', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );

	$wp_customize->add_setting( 'technicalistic_show_art_subscribe', array(
		'default'           => false,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_art_subscribe', array(
		'label'   => __( 'Show "Subscribe to Art Updates" link', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_art_subscribe_url', array(
		'default'           => '',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_art_subscribe_url', array(
		'label'       => __( 'Art Subscribe/RSS URL', 'technicalistic' ),
		'description' => __( 'RSS feed or signup page for art updates.', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );

	$wp_customize->add_setting( 'technicalistic_show_request_portfolio', array(
		'default'           => false,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_request_portfolio', array(
		'label'   => __( 'Show "Request Portfolio" button (Art page)', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_request_portfolio_url', array(
		'default'           => '/contact/',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_request_portfolio_url', array(
		'label'       => __( '"Request Portfolio" URL', 'technicalistic' ),
		'description' => __( 'Internal page or external URL for portfolio requests.', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );

	$wp_customize->add_setting( 'technicalistic_show_etsy_link', array(
		'default'           => false,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_etsy_link', array(
		'label'   => __( 'Show "Visit Etsy Shop" button (Art page)', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_etsy_url', array(
		'default'           => 'https://www.etsy.com/',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_etsy_url', array(
		'label'       => __( 'Etsy Shop URL', 'technicalistic' ),
		'description' => __( 'Your Etsy storefront URL.', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );

	$wp_customize->add_setting( 'technicalistic_show_portfolio_connect', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_portfolio_connect', array(
		'label'   => __( 'Show "Connect" link (Portfolio page)', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_portfolio_connect_url', array(
		'default'           => '/contact/',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_portfolio_connect_url', array(
		'label'       => __( '"Connect" Link URL', 'technicalistic' ),
		'description' => __( 'URL for the "Connect" link on the Portfolio page header.', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );

	$wp_customize->add_setting( 'technicalistic_show_blog_subscribe', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_blog_subscribe', array(
		'label'   => __( 'Show "Subscribe" link (Blog page)', 'technicalistic' ),
		'section' => 'technicalistic_links',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_blog_subscribe_url', array(
		'default'           => '',
		'sanitize_callback' => 'esc_url_raw',
	) );
	$wp_customize->add_control( 'technicalistic_blog_subscribe_url', array(
		'label'       => __( 'Blog Subscribe/RSS URL', 'technicalistic' ),
		'description' => __( 'RSS feed or signup page for blog updates.', 'technicalistic' ),
		'section'     => 'technicalistic_links',
		'type'        => 'url',
	) );
}
add_action( 'customize_register', 'technicalistic_customize_links' );

/**
 * Sanitize textarea: allow basic line breaks and HTML entities.
 *
 * @param string $input The textarea input.
 * @return string Sanitized output.
 */
function technicalistic_sanitize_textarea( $input ) {
	return wp_kses_post( $input );
}

/**
 * Register Customizer settings for blog coming-soon content.
 *
 * @param WP_Customize_Manager $wp_customize Customizer manager.
 */
function technicalistic_customize_blog_content( $wp_customize ) {
	$wp_customize->add_section( 'technicalistic_blog_content', array(
		'title'       => __( 'Blog Content', 'technicalistic' ),
		'description' => __( 'Toggle and edit the "Coming Soon" sections on the Blog page.', 'technicalistic' ),
		'priority'    => 92,
	) );

	$wp_customize->add_setting( 'technicalistic_show_blog_launching', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_blog_launching', array(
		'label'   => __( 'Show "Blog Launching Soon" section', 'technicalistic' ),
		'section' => 'technicalistic_blog_content',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_blog_launching_heading', array(
		'default'           => 'Blog Launching Soon',
		'sanitize_callback' => 'sanitize_text_field',
	) );
	$wp_customize->add_control( 'technicalistic_blog_launching_heading', array(
		'label'   => __( '"Blog Launching Soon" Heading', 'technicalistic' ),
		'section' => 'technicalistic_blog_content',
		'type'    => 'text',
	) );

	$wp_customize->add_setting( 'technicalistic_blog_launching_text', array(
		'default'           => "A blog is on its way with insights, tips, and behind-the-scenes stories. Subscribe below to be notified when the first post goes live.",
		'sanitize_callback' => 'technicalistic_sanitize_textarea',
	) );
	$wp_customize->add_control( 'technicalistic_blog_launching_text', array(
		'label'   => __( '"Blog Launching Soon" Description', 'technicalistic' ),
		'section' => 'technicalistic_blog_content',
		'type'    => 'textarea',
	) );

	$wp_customize->add_setting( 'technicalistic_show_upcoming_topics', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_upcoming_topics', array(
		'label'   => __( 'Show "Upcoming Topics" section', 'technicalistic' ),
		'section' => 'technicalistic_blog_content',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_upcoming_topics_heading', array(
		'default'           => 'Upcoming Topics',
		'sanitize_callback' => 'sanitize_text_field',
	) );
	$wp_customize->add_control( 'technicalistic_upcoming_topics_heading', array(
		'label'   => __( '"Upcoming Topics" Heading', 'technicalistic' ),
		'section' => 'technicalistic_blog_content',
		'type'    => 'text',
	) );

	$wp_customize->add_setting( 'technicalistic_upcoming_topics_items', array(
		'default'           => "Getting started guides\nBehind-the-scenes stories\nIndustry best practices\nTools and workflow tips\nCase studies\nCreative process insights",
		'sanitize_callback' => 'technicalistic_sanitize_textarea',
	) );
	$wp_customize->add_control( 'technicalistic_upcoming_topics_items', array(
		'label'       => __( 'Upcoming Topics (one per line)', 'technicalistic' ),
		'description' => __( 'Enter one topic per line. They will be displayed in a two-column grid.', 'technicalistic' ),
		'section'     => 'technicalistic_blog_content',
		'type'        => 'textarea',
	) );

	$wp_customize->add_setting( 'technicalistic_show_what_to_expect', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_what_to_expect', array(
		'label'   => __( 'Show "What to Expect" section', 'technicalistic' ),
		'section' => 'technicalistic_blog_content',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_what_to_expect_heading', array(
		'default'           => 'What to Expect',
		'sanitize_callback' => 'sanitize_text_field',
	) );
	$wp_customize->add_control( 'technicalistic_what_to_expect_heading', array(
		'label'   => __( '"What to Expect" Heading', 'technicalistic' ),
		'section' => 'technicalistic_blog_content',
		'type'    => 'text',
	) );

	$wp_customize->add_setting( 'technicalistic_what_to_expect_items', array(
		'default'           => "In-depth tutorials and how-to guides\nReal-world project case studies\nFrameworks and templates you can use\nTool reviews and workflow tips",
		'sanitize_callback' => 'technicalistic_sanitize_textarea',
	) );
	$wp_customize->add_control( 'technicalistic_what_to_expect_items', array(
		'label'       => __( '"What to Expect" Items (one per line)', 'technicalistic' ),
		'description' => __( 'Enter one item per line. They will be displayed as a bulleted list.', 'technicalistic' ),
		'section'     => 'technicalistic_blog_content',
		'type'        => 'textarea',
	) );
}
add_action( 'customize_register', 'technicalistic_customize_blog_content' );

/**
 * Register Customizer settings for art coming-soon content.
 *
 * @param WP_Customize_Manager $wp_customize Customizer manager.
 */
function technicalistic_customize_art_content( $wp_customize ) {
	$wp_customize->add_section( 'technicalistic_art_content', array(
		'title'       => __( 'Art Content', 'technicalistic' ),
		'description' => __( 'Toggle and edit the "Coming Soon" sections on the Art page.', 'technicalistic' ),
		'priority'    => 93,
	) );

	$wp_customize->add_setting( 'technicalistic_show_art_launching', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_art_launching', array(
		'label'   => __( 'Show "Creative Portfolio Launching Soon" section', 'technicalistic' ),
		'section' => 'technicalistic_art_content',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_art_launching_heading', array(
		'default'           => 'Creative Portfolio Launching Soon',
		'sanitize_callback' => 'sanitize_text_field',
	) );
	$wp_customize->add_control( 'technicalistic_art_launching_heading', array(
		'label'   => __( '"Creative Portfolio Launching Soon" Heading', 'technicalistic' ),
		'section' => 'technicalistic_art_content',
		'type'    => 'text',
	) );

	$wp_customize->add_setting( 'technicalistic_art_launching_text', array(
		'default'           => "This section will showcase visual art, fine art sculpture, digital designs, and other creative projects.",
		'sanitize_callback' => 'technicalistic_sanitize_textarea',
	) );
	$wp_customize->add_control( 'technicalistic_art_launching_text', array(
		'label'   => __( '"Creative Portfolio Launching Soon" Description', 'technicalistic' ),
		'section' => 'technicalistic_art_content',
		'type'    => 'textarea',
	) );

	$wp_customize->add_setting( 'technicalistic_show_whats_coming', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_whats_coming', array(
		'label'   => __( 'Show "What\'s Coming" section', 'technicalistic' ),
		'section' => 'technicalistic_art_content',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_whats_coming_heading', array(
		'default'           => "What's Coming",
		'sanitize_callback' => 'sanitize_text_field',
	) );
	$wp_customize->add_control( 'technicalistic_whats_coming_heading', array(
		'label'   => __( '"What\'s Coming" Heading', 'technicalistic' ),
		'section' => 'technicalistic_art_content',
		'type'    => 'text',
	) );

	$wp_customize->add_setting( 'technicalistic_whats_coming_items', array(
		'default'           => "Fine art sculpture gallery\nDigital art & design work\nCreative project case studies\nVisual art portfolio\nAvailable works for purchase\nCommission information",
		'sanitize_callback' => 'technicalistic_sanitize_textarea',
	) );
	$wp_customize->add_control( 'technicalistic_whats_coming_items', array(
		'label'       => __( '"What\'s Coming" Items (one per line)', 'technicalistic' ),
		'description' => __( 'Enter one item per line. They will be displayed in a two-column grid.', 'technicalistic' ),
		'section'     => 'technicalistic_art_content',
		'type'        => 'textarea',
	) );

	$wp_customize->add_setting( 'technicalistic_show_creative_philosophy', array(
		'default'           => true,
		'sanitize_callback' => 'technicalistic_sanitize_checkbox',
	) );
	$wp_customize->add_control( 'technicalistic_show_creative_philosophy', array(
		'label'   => __( 'Show "Creative Philosophy" section', 'technicalistic' ),
		'section' => 'technicalistic_art_content',
		'type'    => 'checkbox',
	) );

	$wp_customize->add_setting( 'technicalistic_creative_philosophy_heading', array(
		'default'           => 'Creative Philosophy',
		'sanitize_callback' => 'sanitize_text_field',
	) );
	$wp_customize->add_control( 'technicalistic_creative_philosophy_heading', array(
		'label'   => __( '"Creative Philosophy" Heading', 'technicalistic' ),
		'section' => 'technicalistic_art_content',
		'type'    => 'text',
	) );

	$wp_customize->add_setting( 'technicalistic_creative_philosophy_items', array(
		'default'           => "Exploring the intersection of traditional craft and contemporary expression\nWorking with physical materials and digital tools\nChallenging conventional boundaries and inviting deeper engagement\nCommitment to technical excellence and conceptual depth",
		'sanitize_callback' => 'technicalistic_sanitize_textarea',
	) );
	$wp_customize->add_control( 'technicalistic_creative_philosophy_items', array(
		'label'       => __( '"Creative Philosophy" Items (one per line)', 'technicalistic' ),
		'description' => __( 'Enter one item per line. They will be displayed as a bulleted list.', 'technicalistic' ),
		'section'     => 'technicalistic_art_content',
		'type'        => 'textarea',
	) );
}
add_action( 'customize_register', 'technicalistic_customize_art_content' );

/**
 * Load theme text domain for translations.
 */
function technicalistic_load_textdomain() {
	load_theme_textdomain( 'technicalistic', TECHNICALISTIC_DIR . '/languages' );
}
add_action( 'after_setup_theme', 'technicalistic_load_textdomain' );

/**
 * On single posts, rewrite tag permalink URLs to point to the Portfolio
 * page with a ?tag=slug parameter so the JS filter auto-activates.
 *
 * @param string  $url      The term link URL.
 * @param WP_Term $term     The term object.
 * @param string  $taxonomy The taxonomy slug.
 * @return string Modified URL.
 */
function technicalistic_tag_links_to_portfolio( $url, $term, $taxonomy ) {
	if ( 'post_tag' !== $taxonomy || ! is_singular( 'post' ) ) {
		return $url;
	}
	return home_url( '/portfolio/?tag=' . $term->slug );
}
add_filter( 'term_link', 'technicalistic_tag_links_to_portfolio', 10, 3 );

/**
 * ============================================================
 * Portfolio Thumbnails — per-post selection of 1–3 images that
 * render as a thumbnail strip in the Portfolio listing card.
 * Stored as a CSV of attachment IDs in `_portfolio_thumbs`.
 * Falls back to the post's featured image when no thumbs set.
 * ============================================================
 */

const TECHNICALISTIC_THUMBS_META = '_portfolio_thumbs';
const TECHNICALISTIC_THUMBS_MAX  = 3;

/**
 * Register the meta box on the post edit screen.
 */
function technicalistic_add_portfolio_thumbs_meta_box() {
	add_meta_box(
		'technicalistic_portfolio_thumbs',
		__( 'Portfolio Thumbnails', 'technicalistic' ),
		'technicalistic_render_portfolio_thumbs_meta_box',
		'post',
		'side',
		'default'
	);
}
add_action( 'add_meta_boxes', 'technicalistic_add_portfolio_thumbs_meta_box' );

/**
 * Render the meta box UI.
 *
 * @param WP_Post $post Current post.
 */
function technicalistic_render_portfolio_thumbs_meta_box( $post ) {
	wp_nonce_field( 'technicalistic_save_portfolio_thumbs', 'technicalistic_portfolio_thumbs_nonce' );

	$value = get_post_meta( $post->ID, TECHNICALISTIC_THUMBS_META, true );
	$ids   = array_filter( array_map( 'absint', explode( ',', (string) $value ) ) );

	echo '<p style="margin-top:0;color:#646970;">' .
		esc_html__( 'Select up to 3 images to show as a thumbnail strip on the Portfolio listing card. If none are set, the post\'s Featured Image is used.', 'technicalistic' ) .
		'</p>';

	echo '<div class="jb-portfolio-thumbs-list" id="jb-portfolio-thumbs-list" data-max="' . esc_attr( TECHNICALISTIC_THUMBS_MAX ) . '">';
	foreach ( $ids as $id ) {
		$src = wp_get_attachment_image_url( $id, 'thumbnail' );
		if ( ! $src ) {
			continue;
		}
		echo '<div class="jb-thumb" data-id="' . esc_attr( $id ) . '">';
		echo '<img src="' . esc_url( $src ) . '" alt="" />';
		echo '<button type="button" class="jb-thumb-remove" aria-label="' . esc_attr__( 'Remove', 'technicalistic' ) . '">&times;</button>';
		echo '</div>';
	}
	echo '</div>';

	echo '<input type="hidden" id="jb-portfolio-thumbs-ids" name="technicalistic_portfolio_thumbs" value="' . esc_attr( implode( ',', $ids ) ) . '" />';
	echo '<button type="button" class="button" id="jb-portfolio-thumbs-add">' .
		esc_html__( 'Select images', 'technicalistic' ) .
		'</button>';
}

/**
 * Save handler for the meta box.
 *
 * @param int $post_id Post being saved.
 */
function technicalistic_save_portfolio_thumbs( $post_id ) {
	if ( ! isset( $_POST['technicalistic_portfolio_thumbs_nonce'] ) ) {
		return;
	}
	if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['technicalistic_portfolio_thumbs_nonce'] ) ), 'technicalistic_save_portfolio_thumbs' ) ) {
		return;
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	$raw = isset( $_POST['technicalistic_portfolio_thumbs'] ) ? sanitize_text_field( wp_unslash( $_POST['technicalistic_portfolio_thumbs'] ) ) : '';
	$ids = array_filter( array_map( 'absint', explode( ',', $raw ) ) );
	$ids = array_slice( array_values( $ids ), 0, TECHNICALISTIC_THUMBS_MAX );

	if ( empty( $ids ) ) {
		delete_post_meta( $post_id, TECHNICALISTIC_THUMBS_META );
	} else {
		update_post_meta( $post_id, TECHNICALISTIC_THUMBS_META, implode( ',', $ids ) );
	}
}
add_action( 'save_post_post', 'technicalistic_save_portfolio_thumbs' );

/**
 * Enqueue media library scripts and the meta-box JS on the post edit screen.
 *
 * @param string $hook Current admin page.
 */
function technicalistic_admin_enqueue_portfolio_thumbs( $hook ) {
	if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
		return;
	}
	$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
	if ( $screen && 'post' !== $screen->post_type ) {
		return;
	}

	wp_enqueue_media();
	wp_enqueue_style(
		'technicalistic-admin-thumbs',
		TECHNICALISTIC_URI . '/assets/css/custom.css',
		array(),
		TECHNICALISTIC_VERSION
	);
	wp_enqueue_script(
		'technicalistic-admin-thumbs',
		TECHNICALISTIC_URI . '/assets/js/admin-portfolio-thumbs.js',
		array( 'jquery' ),
		TECHNICALISTIC_VERSION,
		true
	);
	wp_localize_script(
		'technicalistic-admin-thumbs',
		'TechnicalisticThumbs',
		array(
			'max'         => TECHNICALISTIC_THUMBS_MAX,
			'title'       => __( 'Select portfolio thumbnails', 'technicalistic' ),
			'buttonText'  => __( 'Use these images', 'technicalistic' ),
			'removeLabel' => __( 'Remove', 'technicalistic' ),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'technicalistic_admin_enqueue_portfolio_thumbs' );

/**
 * Render the portfolio-thumbs HTML for a specific post.
 *
 * Single source of truth: used by both the [portfolio_thumbs] shortcode
 * (which reads the global $post) and the render_block filter on
 * core/post-featured-image (which reads the block's postId context, the
 * reliable way to identify the post inside FSE post-template loops).
 *
 * @param int $post_id Post ID to render thumbs for.
 * @return string HTML for the strip, or empty string if nothing to show.
 */
function technicalistic_render_portfolio_thumbs_html( $post_id ) {
	$post_id = (int) $post_id;
	if ( ! $post_id ) {
		return '';
	}

	$permalink = get_permalink( $post_id );
	$value     = get_post_meta( $post_id, TECHNICALISTIC_THUMBS_META, true );
	$ids       = array_filter( array_map( 'absint', explode( ',', (string) $value ) ) );
	$ids       = array_slice( array_values( $ids ), 0, TECHNICALISTIC_THUMBS_MAX );

	if ( empty( $ids ) ) {
		$featured_id = (int) get_post_thumbnail_id( $post_id );
		if ( $featured_id ) {
			$ids = array( $featured_id );
		}
	}

	if ( empty( $ids ) ) {
		return '';
	}

	$count = count( $ids );
	$html  = '<div class="portfolio-thumb-strip" data-count="' . esc_attr( $count ) . '">';
	foreach ( $ids as $id ) {
		$img = wp_get_attachment_image(
			$id,
			'technicalistic-card',
			false,
			array(
				'loading' => 'lazy',
				'alt'     => esc_attr( get_the_title( $post_id ) ),
			)
		);
		if ( ! $img ) {
			continue;
		}
		$html .= '<a href="' . esc_url( $permalink ) . '" aria-hidden="true" tabindex="-1">' . $img . '</a>';
	}
	$html .= '</div>';

	return $html;
}

/**
 * Swap the Portfolio Thumbnail strip in for a post's Featured Image block.
 *
 * Themes should not register block types: a PHP-only block cannot be resolved
 * by the editor, which makes the Site Editor show the block as invalid and
 * offer "Attempt recovery." Instead we filter the rendered output of the core
 * `core/post-featured-image` block. When a post has saved Portfolio Thumbnails
 * we replace its single featured image with the multi-image strip; posts with
 * no saved thumbs keep their normal featured image untouched. Templates then
 * use only core blocks, so the editor never prompts for recovery.
 *
 * @param string $block_content The block's rendered HTML.
 * @param array  $block         The parsed block (blockName, attrs, context).
 * @return string Filtered HTML.
 */
function technicalistic_swap_featured_image_for_thumbs( $block_content, $block ) {
	if ( empty( $block['blockName'] ) || 'core/post-featured-image' !== $block['blockName'] ) {
		return $block_content;
	}

	$post_id = isset( $block['context']['postId'] ) ? (int) $block['context']['postId'] : (int) get_the_ID();
	if ( ! $post_id ) {
		return $block_content;
	}

	$thumbs = get_post_meta( $post_id, TECHNICALISTIC_THUMBS_META, true );
	if ( '' === (string) $thumbs ) {
		return $block_content;
	}

	$strip = technicalistic_render_portfolio_thumbs_html( $post_id );
	return $strip ? $strip : $block_content;
}
add_filter( 'render_block', 'technicalistic_swap_featured_image_for_thumbs', 10, 2 );

/**
 * Default [gallery] shortcode to use 'large' size instead of 'thumbnail',
 * so images aren't pixelated when stretched to grid tile width.
 *
 * @param array $atts Shortcode attributes.
 * @return array Modified attributes.
 */
function technicalistic_default_gallery_size( $atts ) {
	if ( empty( $atts['size'] ) || 'thumbnail' === $atts['size'] ) {
		$atts['size'] = 'large';
	}
	return $atts;
}
add_filter( 'shortcode_atts_gallery', 'technicalistic_default_gallery_size' );

/**
 * Check if the current page matches a given slug, even when the page
 * is set as the Posts page (where is_page() returns false).
 *
 * @param string $slug The page slug to check.
 * @return bool
 */
function technicalistic_is_page_slug( $slug ) {
	if ( is_page( $slug ) ) {
		return true;
	}

	$posts_page_id = (int) get_option( 'page_for_posts' );
	if ( $posts_page_id && is_home() ) {
		$posts_page = get_post( $posts_page_id );
		if ( $posts_page && $posts_page->post_name === $slug ) {
			return true;
		}
	}

	return false;
}

/**
 * Filter Query Loop block queries on specific pages to show only posts
 * in the matching category.
 *
 * @param array    $query_args WP_Query arguments for the block.
 * @param WP_Block $block      The Query Loop block instance.
 * @param int      $page       Current pagination page.
 * @return array Modified query arguments.
 */
function technicalistic_filter_page_queries( $query_args, $block, $page ) {
	$page_category_map = array(
		'portfolio' => 'Portfolio',
		'art'       => 'Art',
		'blog'      => 'blognew',
	);

	if ( is_front_page() ) {
		$cat_id = get_cat_ID( 'Portfolio' );
		if ( $cat_id ) {
			$query_args['cat'] = $cat_id;
		}
		return $query_args;
	}

	foreach ( $page_category_map as $page_slug => $category_name ) {
		if ( technicalistic_is_page_slug( $page_slug ) ) {
			$cat_id = get_cat_ID( $category_name );
			if ( $cat_id ) {
				$query_args['cat'] = $cat_id;
			}
			break;
		}
	}

	return $query_args;
}
add_filter( 'query_loop_block_query_vars', 'technicalistic_filter_page_queries', 10, 3 );
