<h1>YANZ UPLOAD ANJG</h1><?php
/**
 * TotalOnlineNews theme bootstrap.
 *
 * Lightweight by design: one stylesheet, one small script, no framework and no
 * build step. All content comes from standard WordPress APIs.
 *
 * @package TotalOnlineNews
 */

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

define( 'TON_VERSION', '1.5.14' );

/* ==========================================================================
   Theme setup
   ========================================================================== */
function ton_setup() {
	load_theme_textdomain( 'totalonlinenews', get_template_directory() . '/languages' );

	add_theme_support( 'title-tag' );
	add_theme_support( 'post-thumbnails' );
	add_theme_support( 'automatic-feed-links' );
	add_theme_support( 'responsive-embeds' );
	add_theme_support( 'align-wide' );
	add_theme_support( 'html5', array( 'search-form', 'gallery', 'caption', 'style', 'script', 'navigation-widgets' ) );
	add_theme_support( 'custom-logo', array( 'height' => 80, 'width' => 400, 'flex-height' => true, 'flex-width' => true ) );

	register_nav_menus( array(
		'primary' => __( 'Primary (categories bar)', 'totalonlinenews' ),
		'footer'  => __( 'Footer', 'totalonlinenews' ),
	) );

	/* Legacy card sizes, matching the previous site's layout. */
	set_post_thumbnail_size( 400, 250, true );
	add_image_size( 'ton-hero', 1200, 675, true );
	add_image_size( 'ton-card', 600, 375, true );
	add_image_size( 'ton-thumb', 240, 180, true );
}
add_action( 'after_setup_theme', 'ton_setup' );

function ton_content_width() {
	$GLOBALS['content_width'] = 720;
}
add_action( 'after_setup_theme', 'ton_content_width', 0 );

/* ==========================================================================
   Assets - one CSS file, one tiny JS file, no dependencies
   ========================================================================== */
/**
 * Cache-busting version for a theme asset.
 *
 * Using a hand-edited constant here was a real bug: markup shipped with new
 * classes while browsers kept serving the previous stylesheet for its full
 * 30-day max-age, so on a phone the new buttons rendered unstyled. The file's
 * own mtime now becomes the ?ver= value, so every deploy invalidates exactly
 * the files that changed and nothing else.
 *
 * @param string $relative Path inside the theme, e.g. '/style.css'.
 * @return string
 */
function ton_asset_version( $relative ) {
	$path = get_template_directory() . $relative;

	return file_exists( $path ) ? (string) filemtime( $path ) : TON_VERSION;
}

function ton_assets() {
	wp_enqueue_style( 'ton-style', get_stylesheet_uri(), array(), ton_asset_version( '/style.css' ) );

	wp_enqueue_script( 'ton-theme', get_template_directory_uri() . '/assets/js/theme.js', array(), ton_asset_version( '/assets/js/theme.js' ), true );
}
add_action( 'wp_enqueue_scripts', 'ton_assets' );

/* Trim front-end bloat that the theme does not use. */
function ton_cleanup() {
	remove_action( 'wp_head', 'wp_generator' );
	remove_action( 'wp_head', 'wlwmanifest_link' );
	remove_action( 'wp_head', 'rsd_link' );
	remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
	remove_action( 'wp_print_styles', 'print_emoji_styles' );
}
add_action( 'init', 'ton_cleanup' );

/* ==========================================================================
   Helpers - settings and migrated metadata
   ========================================================================== */

/** Site name, preferring the value migrated from the legacy admin. */
function ton_site_name() {
	$n = get_option( 'ton_site_name' );
	return $n ? $n : get_bloginfo( 'name', 'display' );
}

/** Legacy tagline, e.g. LATEST NEWS - BEYOND LIMITS. */
function ton_tagline() {
	$t = get_option( 'ton_tagline' );
	return $t ? $t : get_bloginfo( 'description', 'display' );
}

function ton_site_description() {
	$d = get_option( 'ton_site_description' );
	return $d ? $d : get_bloginfo( 'description', 'display' );
}

/** Boolean-ish legacy settings. */
function ton_flag_enabled( $option ) {
	$v = get_option( $option, null );
	if ( null === $v ) { return false; }
	return in_array( strtolower( (string) $v ), array( '1', 'true', 'yes', 'on' ), true );
}

/** Social profiles migrated from the legacy settings table. */
function ton_socials() {
	$map = array(
		'Facebook'  => 'ton_social_facebook',
		'X'         => 'ton_social_x',
		'Instagram' => 'ton_social_instagram',
		'YouTube'   => 'ton_social_youtube',
		'Telegram'  => 'ton_social_telegram',
	);
	$out = array();
	foreach ( $map as $label => $opt ) {
		$url = trim( (string) get_option( $opt, '' ) );
		if ( '' !== $url ) { $out[ $label ] = $url; }
	}
	return $out;
}

/** Read a migrated post meta value. */
function ton_meta( $key, $post_id = null ) {
	$post_id = $post_id ? $post_id : get_the_ID();
	return get_post_meta( $post_id, $key, true );
}

function ton_seo_title( $post_id = null ) {
	$t = trim( (string) ton_meta( '_ton_seo_title', $post_id ) );
	return $t ? $t : get_the_title( $post_id );
}

function ton_seo_description( $post_id = null ) {
	$d = trim( (string) ton_meta( '_ton_seo_description', $post_id ) );
	if ( $d ) { return $d; }
	$excerpt = trim( (string) ton_meta( '_ton_subtitle', $post_id ) );
	if ( ! $excerpt ) {
		$post = get_post( $post_id );
		$excerpt = $post ? wp_strip_all_tags( strip_shortcodes( $post->post_excerpt ? $post->post_excerpt : $post->post_content ) ) : '';
	}
	return wp_trim_words( $excerpt, 30, '' );
}

function ton_reading_time( $post_id = null ) {
	$rt = (int) ton_meta( '_ton_reading_time', $post_id );
	if ( $rt > 0 ) { return $rt; }
	$post = get_post( $post_id );
	$words = $post ? str_word_count( wp_strip_all_tags( $post->post_content ) ) : 0;
	return max( 1, (int) ceil( $words / 200 ) );
}

/* ==========================================================================
   SEO - meta description, Open Graph, Twitter cards and schema.org
   --------------------------------------------------------------------------
   IMPORTANT: every output below is skipped when a dedicated SEO plugin is
   active, so the two never emit competing tags. The theme also deliberately
   does NOT print <link rel="canonical"> because WordPress core already does
   (rel_canonical()); we only override its VALUE via the filter further down.
   ========================================================================== */

/** Is another SEO plugin already handling meta output? */
function ton_seo_plugin_active() {
	return (
		defined( 'WPSEO_VERSION' )      // Yoast SEO
		|| defined( 'RANK_MATH_VERSION' )   // Rank Math
		|| defined( 'AIOSEO_VERSION' )      // All in One SEO
		|| defined( 'SEOPRESS_VERSION' )    // SEOPress
		|| class_exists( 'The_SEO_Framework\\Load' )
	);
}

/**
 * Preferred archive URL for a term.
 *
 * Categories are canonical at /{slug}/ (the legacy public shape). The
 * ton-url-compat mu-plugin also rewrites term_link for categories, so this
 * helper is belt-and-braces and stays correct for tags and taxonomies.
 */
function ton_term_archive_url( $term ) {
	if ( ! $term || is_wp_error( $term ) ) { return home_url( '/' ); }
	if ( isset( $term->taxonomy ) && 'category' === $term->taxonomy ) {
		return home_url( '/' . $term->slug . '/' );
	}
	$link = get_term_link( $term );
	return is_wp_error( $link ) ? home_url( '/' ) : $link;
}

/** Current canonical URL, honouring the migrated _ton_canonical value. */
function ton_canonical_url() {
	if ( is_singular() ) {
		$custom = trim( (string) ton_meta( '_ton_canonical' ) );
		if ( '' !== $custom && filter_var( $custom, FILTER_VALIDATE_URL ) ) {
			return $custom;
		}
		return get_permalink();
	}
	if ( is_front_page() ) { return home_url( '/' ); }
	if ( is_category() || is_tag() || is_tax() ) {
		$base = ton_term_archive_url( get_queried_object() );
		/* Self-referencing canonical for paginated archives. */
		$paged = (int) get_query_var( 'paged' );
		if ( $paged > 1 ) { $base = trailingslashit( $base ) . 'page/' . $paged . '/'; }
		return $base;
	}
	if ( is_search() ) { return get_search_link(); }
	if ( is_author() ) { return get_author_posts_url( (int) get_query_var( 'author' ) ); }
	if ( is_home() ) { return home_url( '/' ); }
	if ( is_singular() ) { return get_permalink(); }
	return home_url( add_query_arg( array(), $GLOBALS['wp']->request ) );
}

/** Let WordPress core's canonical tag use the migrated URL. */
add_filter( 'get_canonical_url', function ( $url, $post ) {
	$custom = trim( (string) get_post_meta( $post->ID, '_ton_canonical', true ) );
	return ( '' !== $custom && filter_var( $custom, FILTER_VALIDATE_URL ) ) ? $custom : $url;
}, 10, 2 );

/** Fallback share image used by archives with no featured image. */
function ton_default_og_image() {
	$custom = trim( (string) get_option( 'ton_og_default', '' ) );
	if ( '' !== $custom && filter_var( $custom, FILTER_VALIDATE_URL ) ) { return $custom; }
	return get_template_directory_uri() . '/assets/img/og-default.jpg';
}

/** Best available social share image for the current view. */
function ton_share_image() {
	if ( is_singular() ) {
		$og = trim( (string) ton_meta( '_ton_og_image' ) );
		if ( $og ) { return $og; }
		if ( has_post_thumbnail() ) {
			$src = wp_get_attachment_image_src( get_post_thumbnail_id(), 'ton-hero' );
			if ( $src ) { return $src[0]; }
		}
		/* Pages and image-less posts share the branded default rather than none. */
		return ton_default_og_image();
	}
	return ton_default_og_image();
}

/** Title used for social cards. */
function ton_social_title() {
	if ( is_singular() ) { return ton_seo_title(); }
	if ( is_category() || is_tag() || is_tax() ) {
		$t = get_queried_object();
		return $t ? sprintf( '%s - %s', $t->name, ton_site_name() ) : ton_site_name();
	}
	if ( is_search() ) { return sprintf( 'Search: %s - %s', get_search_query(), ton_site_name() ); }
	if ( is_home() || is_front_page() ) {
		$d = get_option( 'ton_seo_default_title' );
		return $d ? $d : sprintf( '%s - %s', ton_site_name(), ton_tagline() );
	}
	return wp_get_document_title();
}

function ton_social_description() {
	if ( is_singular() ) { return ton_seo_description(); }

	$site = ton_site_name();

	if ( is_category() ) {
		$own = trim( wp_strip_all_tags( category_description() ) );
		if ( '' !== $own ) { return $own; }
		$term = get_queried_object();
		$name = $term ? $term->name : '';
		return sprintf( 'Latest %1$s news from %2$s - headlines, analysis and updates as they happen.', $name, $site );
	}

	if ( is_tag() ) {
		$term = get_queried_object();
		$name = $term ? $term->name : '';
		$n    = $term ? (int) $term->count : 0;
		return sprintf( 'Stories tagged %1$s - %2$d article(s) from the %3$s newsroom.', $name, $n, $site );
	}

	if ( is_author() ) {
		$bio = trim( wp_strip_all_tags( get_the_author_meta( 'description' ) ) );
		if ( '' !== $bio ) { return wp_trim_words( $bio, 30, '' ); }
		return sprintf( 'News, reports and analysis published by %1$s for %2$s.', get_the_author(), $site );
	}

	if ( is_tax() ) {
		$term = get_queried_object();
		$own  = trim( wp_strip_all_tags( term_description() ) );
		if ( '' !== $own ) { return $own; }
		$name = $term ? $term->name : '';
		return sprintf( 'Browse %1$s coverage from %2$s.', $name, $site );
	}

	if ( is_search() ) {
		return sprintf( 'Search results for %1$s on %2$s.', get_search_query(), $site );
	}

	if ( is_home() || is_front_page() ) {
		$d = get_option( 'ton_seo_default_description' );
		return $d ? $d : ton_site_description();
	}

	return ton_site_description();
}

/** Emit the social/SEO block. Does nothing when an SEO plugin is active. */
function ton_seo_head() {
	if ( ton_seo_plugin_active() ) { return; }

	$title = ton_social_title();
	$desc  = wp_strip_all_tags( (string) ton_social_description() );
	$url   = ton_canonical_url();
	$image = ton_share_image();
	$site  = ton_site_name();

	if ( $desc ) {
		printf( "\n<meta name=\"description\" content=\"%s\" />\n", esc_attr( wp_trim_words( $desc, 40, '' ) ) );
	}

	/* Robots: keep thin admin/utility views out of the index. */
	if ( is_search() || is_404() ) {
		echo "<meta name=\"robots\" content=\"noindex, follow\" />\n";
	}

	printf( "<meta property=\"og:type\" content=\"%s\" />\n", is_singular( 'post' ) ? 'article' : 'website' );
	printf( "<meta property=\"og:site_name\" content=\"%s\" />\n", esc_attr( $site ) );
	printf( "<meta property=\"og:title\" content=\"%s\" />\n", esc_attr( $title ) );
	printf( "<meta property=\"og:url\" content=\"%s\" />\n", esc_url( $url ) );
	if ( $desc ) { printf( "<meta property=\"og:description\" content=\"%s\" />\n", esc_attr( wp_trim_words( $desc, 40, '' ) ) ); }
	if ( $image ) { printf( "<meta property=\"og:image\" content=\"%s\" />\n", esc_url( $image ) ); }
	printf( "<meta property=\"og:locale\" content=\"%s\" />\n", esc_attr( str_replace( '-', '_', get_bloginfo( 'language' ) ) ) );

	if ( is_singular( 'post' ) ) {
		printf( "<meta property=\"article:published_time\" content=\"%s\" />\n", esc_attr( get_the_date( DATE_W3C ) ) );
		printf( "<meta property=\"article:modified_time\" content=\"%s\" />\n", esc_attr( get_the_modified_date( DATE_W3C ) ) );
		$cats = get_the_category();
		if ( $cats ) { printf( "<meta property=\"article:section\" content=\"%s\" />\n", esc_attr( $cats[0]->name ) ); }
		$tags = get_the_tags();
		if ( $tags ) {
			foreach ( $tags as $tag ) {
				printf( "<meta property=\"article:tag\" content=\"%s\" />\n", esc_attr( $tag->name ) );
			}
		}
	}

	echo "<meta name=\"twitter:card\" content=\"summary_large_image\" />\n";
	printf( "<meta name=\"twitter:title\" content=\"%s\" />\n", esc_attr( $title ) );
	if ( $desc ) { printf( "<meta name=\"twitter:description\" content=\"%s\" />\n", esc_attr( wp_trim_words( $desc, 40, '' ) ) ); }
	if ( $image ) { printf( "<meta name=\"twitter:image\" content=\"%s\" />\n", esc_url( $image ) ); }
}
add_action( 'wp_head', 'ton_seo_head', 2 );

/**
 * Canonical tag for NON-singular views.
 *
 * Core rel_canonical() only emits a canonical for singular posts, so
 * archives previously had none. This adds exactly one, and is skipped
 * entirely when an SEO plugin is active so two tags can never appear.
 */
function ton_archive_canonical() {
	if ( ton_seo_plugin_active() ) { return; }
	if ( is_singular() ) { return; }
	if ( is_search() || is_404() ) { return; }
	if ( ! ( is_front_page() || is_home() || is_category() || is_tag() || is_tax() || is_author() ) ) { return; }
	$url = ton_canonical_url();
	if ( $url ) {
		printf( '<link rel="canonical" href="%s" />' . "\n", esc_url( $url ) );
	}
}
add_action( 'wp_head', 'ton_archive_canonical', 1 );

/** Search-engine verification tokens migrated from the legacy settings. */
function ton_verification_head() {
	$token = trim( (string) get_option( 'ton_google_verification', '' ) );
	if ( '' !== $token ) {
		printf( "<meta name=\"google-site-verification\" content=\"%s\" />\n", esc_attr( $token ) );
	}
}
add_action( 'wp_head', 'ton_verification_head', 3 );

/* ==========================================================================
   schema.org structured data
   --------------------------------------------------------------------------
   Mirrors the shapes used by the legacy Next.js site (NewsMediaOrganization,
   WebSite, NewsArticle, BreadcrumbList, ItemList) so search engines see a
   consistent entity graph across the migration. Skipped entirely when an SEO
   plugin is active, to avoid two competing graphs.
   ========================================================================== */

function ton_org_node() {
	$node = array(
		'@type' => 'NewsMediaOrganization',
		'@id'   => home_url( '/#organization' ),
		'name'  => ton_site_name(),
		'url'   => home_url( '/' ),
	);
	$logo = get_theme_mod( 'custom_logo' ) ? wp_get_attachment_image_url( get_theme_mod( 'custom_logo' ), 'full' ) : '';
	$node['logo'] = array( '@type' => 'ImageObject', 'url' => $logo ? $logo : '' );
	$addr = trim( (string) get_option( 'ton_site_address', '' ) );
	if ( $addr ) { $node['address'] = array( '@type' => 'PostalAddress', 'streetAddress' => $addr ); }
	$email = trim( (string) get_option( 'ton_site_email', '' ) );
	if ( $email ) {
		$node['contactPoint'] = array( array( '@type' => 'ContactPoint', 'contactType' => 'editorial', 'email' => $email ) );
	}
	return $node;
}

function ton_website_node() {
	return array(
		'@type'     => 'WebSite',
		'@id'       => home_url( '/#website' ),
		'url'       => home_url( '/' ),
		'name'      => ton_site_name(),
		'publisher' => array( '@id' => home_url( '/#organization' ) ),
		'potentialAction' => array(
			'@type'       => 'SearchAction',
			'target'      => array( '@type' => 'EntryPoint', 'urlTemplate' => home_url( '/?s={search_term_string}' ) ),
			'query-input' => 'required name=search_term_string',
		),
	);
}

function ton_article_node( $post ) {
	$cats = get_the_category( $post->ID );
	$node = array(
		'@type'            => 'NewsArticle',
		'@id'              => get_permalink( $post ) . '#article',
		'mainEntityOfPage' => array( '@type' => 'WebPage', '@id' => get_permalink( $post ) ),
		'headline'         => wp_trim_words( get_the_title( $post ), 20, '' ),
		'description'      => ton_seo_description( $post->ID ),
		'articleSection'   => $cats ? $cats[0]->name : 'News',
		'datePublished'    => get_the_date( DATE_W3C, $post ),
		'dateModified'     => get_the_modified_date( DATE_W3C, $post ),
		'author'           => array( array(
			'@type' => 'Person',
			'name'  => get_the_author_meta( 'display_name', $post->post_author ) ?: 'TotalOnlineNews Desk',
		) ),
		'publisher'        => array( '@id' => home_url( '/#organization' ) ),
	);
	$img = ton_share_image();
	if ( $img ) { $node['image'] = array( $img ); }
	$src = trim( (string) get_post_meta( $post->ID, '_ton_source_url', true ) );
	$nm  = trim( (string) get_post_meta( $post->ID, '_ton_source_name', true ) );
	if ( $src || $nm ) {
		$node['isBasedOn'] = array_filter( array(
			'@type'    => 'CreativeWork',
			'name'     => $nm,
			'url'      => $src,
		) );
	}
	return $node;
}

function ton_breadcrumb_node( $items ) {
	$list = array();
	foreach ( $items as $i => $item ) {
		$list[] = array(
			'@type'    => 'ListItem',
			'position' => $i + 1,
			'name'     => $item['name'],
			'item'     => $item['url'],
		);
	}
	return array( '@type' => 'BreadcrumbList', 'itemListElement' => $list );
}

function ton_jsonld_head() {
	if ( ton_seo_plugin_active() ) { return; }

	$nodes = array();
	if ( is_front_page() || is_home() ) {
		$nodes[] = ton_org_node();
		$nodes[] = ton_website_node();
	} elseif ( is_singular( 'post' ) ) {
		$nodes[] = ton_org_node();
		$nodes[] = ton_website_node();
		$nodes[] = ton_article_node( get_queried_object() );
		$nodes[] = ton_breadcrumb_node( ton_breadcrumb_items() );
	} elseif ( is_category() || is_tag() || is_tax() ) {
		$nodes[] = ton_org_node();
		$nodes[] = ton_website_node();
		$nodes[] = ton_breadcrumb_node( ton_breadcrumb_items() );
	}

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

	$graph = array( '@context' => 'https://schema.org', '@graph' => $nodes );
	echo "\n<script type=\"application/ld+json\">" . wp_json_encode( $graph, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . "</script>\n";
}
add_action( 'wp_head', 'ton_jsonld_head', 4 );

/* ==========================================================================
   Breadcrumbs
   ========================================================================== */
function ton_breadcrumb_items() {
	$items = array( array( 'name' => __( 'Home', 'totalonlinenews' ), 'url' => home_url( '/' ) ) );

	if ( is_singular( 'post' ) ) {
		$cats = get_the_category();
		if ( $cats ) {
			$items[] = array( 'name' => $cats[0]->name, 'url' => get_category_link( $cats[0]->term_id ) );
		}
		$items[] = array( 'name' => get_the_title(), 'url' => get_permalink() );
	} elseif ( is_category() ) {
		$items[] = array( 'name' => single_cat_title( '', false ), 'url' => ton_canonical_url() );
	} elseif ( is_tag() ) {
		$items[] = array( 'name' => single_tag_title( '', false ), 'url' => ton_canonical_url() );
	} elseif ( is_search() ) {
		$items[] = array( 'name' => sprintf( __( 'Search: %s', 'totalonlinenews' ), get_search_query() ), 'url' => get_search_link() );
	} elseif ( is_404() ) {
		$items[] = array( 'name' => __( 'Page not found', 'totalonlinenews' ), 'url' => '' );
	} elseif ( is_page() ) {
		$items[] = array( 'name' => get_the_title(), 'url' => get_permalink() );
	} elseif ( is_author() ) {
		$items[] = array( 'name' => get_the_author(), 'url' => ton_canonical_url() );
	}
	return $items;
}

function ton_breadcrumbs() {
	$items = ton_breadcrumb_items();
	if ( count( $items ) < 2 ) { return; }
	echo '<nav class="ton-breadcrumbs" aria-label="' . esc_attr__( 'Breadcrumb', 'totalonlinenews' ) . '"><ol>';
	$last = count( $items ) - 1;
	foreach ( $items as $i => $item ) {
		if ( $i > 0 ) { echo '<li aria-hidden="true" class="sep">/</li>'; }
		echo '<li>';
		if ( $i === $last || ! $item['url'] ) {
			echo '<span aria-current="page">' . esc_html( $item['name'] ) . '</span>';
		} else {
			echo '<a href="' . esc_url( $item['url'] ) . '">' . esc_html( $item['name'] ) . '</a>';
		}
		echo '</li>';
	}
	echo '</ol></nav>';
}

/* ==========================================================================
   Breaking-news ticker
   --------------------------------------------------------------------------
   The ticker is fed from the posts table, never from a fixed list: it always
   shows the newest published stories, newest first. The rendered list is kept
   in a transient so a page render costs no extra query, and that transient is
   dropped the moment a post is published, updated, trashed or deleted, so the
   very next request already carries the new headline. The nginx page cache is
   flushed on the same events (see mu-plugins/ton-cache.php).
   ========================================================================== */

/** How many headlines the ticker carries. */
function ton_ticker_count() {
	return max( 1, (int) apply_filters( 'ton_ticker_count', 8 ) );
}

/**
 * The newest published headlines, newest first, each one only once.
 *
 * Only `publish` rows are queried, so drafts, scheduled and private stories
 * can never reach the ticker.
 *
 * @return array<int,array{title:string,link:string}>
 */
function ton_breaking_items() {
	$cached = get_transient( 'ton_ticker_data' );
	if ( is_array( $cached ) ) {
		return $cached;
	}

	$out  = array();
	$seen = array();
	foreach ( ton_latest_posts( ton_ticker_count() ) as $post ) {
		$title = trim( wp_strip_all_tags( get_the_title( $post ) ) );
		if ( '' === $title ) { continue; }
		$link = get_permalink( $post );

		// One story, one headline: a repeated permalink or a repeated title
		// (a duplicate post) is skipped instead of scrolling past twice.
		$keys = array( 'p' . (int) $post->ID, 'u' . md5( (string) $link ), 't' . md5( mb_strtolower( $title ) ) );
		$dupe = false;
		foreach ( $keys as $key ) {
			if ( isset( $seen[ $key ] ) ) { $dupe = true; }
		}
		if ( $dupe ) { continue; }
		foreach ( $keys as $key ) { $seen[ $key ] = true; }

		$out[] = array(
			'title' => $title,
			'link'  => $link,
		);
	}

	/** Filters the ticker list, e.g. to prepend a manually curated headline. */
	$out = array_values( (array) apply_filters( 'ton_ticker_items', $out ) );

	set_transient( 'ton_ticker_data', $out, 15 * MINUTE_IN_SECONDS );
	return $out;
}

/** Drop the cached ticker list - fired whenever the posts table changes. */
function ton_ticker_flush() {
	delete_transient( 'ton_ticker_data' );
}
add_action( 'save_post',              'ton_ticker_flush', 20 );
add_action( 'transition_post_status', 'ton_ticker_flush', 20 );
add_action( 'deleted_post',           'ton_ticker_flush', 20 );
add_action( 'trashed_post',           'ton_ticker_flush', 20 );
add_action( 'untrashed_post',         'ton_ticker_flush', 20 );

/**
 * Seconds for one marquee pass. The track holds the headline list twice and
 * slides one copy per pass, so the duration follows the estimated rendered
 * width: the scroll speed stays the same whether the ticker carries 1 headline
 * or 10, and the CSS 40s default is only a fallback.
 *
 * @param array $items Ticker items.
 * @return int
 */
function ton_ticker_duration( $items ) {
	$speed = max( 5.0, (float) apply_filters( 'ton_ticker_speed', 50 ) ); // pixels per second
	$width = 0;
	foreach ( (array) $items as $item ) {
		$width += mb_strlen( isset( $item['title'] ) ? (string) $item['title'] : '' ) * 7 + 60;
	}
	$seconds = (int) round( max( $width, 600 ) / $speed );
	return max( 20, min( 300, $seconds ) );
}

/* ==========================================================================
   Category helpers (order/colour/icon came across as term meta)
   ========================================================================== */
function ton_category_color( $term = null ) {
	$c = ( $term && ! is_wp_error( $term ) ) ? get_term_meta( $term->term_id, 'ton_color', true ) : '';
	return $c ? $c : '#B94249';
}

function ton_category_icon( $term = null ) {
	$i = ( $term && ! is_wp_error( $term ) ) ? get_term_meta( $term->term_id, 'ton_icon', true ) : '';
	return $i ? $i : '';
}

/** Categories in the legacy display order. */
function ton_categories() {
	$terms = get_categories( array( 'hide_empty' => false ) );
	usort( $terms, function ( $a, $b ) {
		$oa = (int) get_term_meta( $a->term_id, 'ton_order', true );
		$ob = (int) get_term_meta( $b->term_id, 'ton_order', true );
		if ( $oa === $ob ) { return strcmp( $a->name, $b->name ); }
		return $oa <=> $ob;
	} );
	return $terms;
}

/* ==========================================================================
   Post queries used by the front page
   ========================================================================== */
function ton_flagged_posts( $meta_key, $limit = 6, $exclude = array() ) {
	return get_posts( array(
		'post_type'      => 'post',
		'post_status'    => 'publish',
		'posts_per_page' => $limit,
		'post__not_in'   => $exclude,
		'ignore_sticky_posts' => true,
		'meta_query'     => array( array( 'key' => $meta_key, 'value' => '1' ) ),
	) );
}

function ton_latest_posts( $limit = 8, $exclude = array() ) {
	return get_posts( array(
		'post_type'      => 'post',
		'post_status'    => 'publish',
		'posts_per_page' => $limit,
		'post__not_in'   => $exclude,
		'ignore_sticky_posts' => true,
	) );
}

/** Merge lists and drop duplicates, preserving order. */
function ton_dedupe( $lists ) {
	$seen = array();
	$out  = array();
	foreach ( $lists as $list ) {
		foreach ( (array) $list as $post ) {
			if ( isset( $seen[ $post->ID ] ) ) { continue; }
			$seen[ $post->ID ] = true;
			$out[] = $post;
		}
	}
	return $out;
}

/** Legacy all-time view count (informational only). */
function ton_legacy_views( $post_id ) {
	return (int) get_post_meta( $post_id, '_ton_legacy_views', true );
}

/* ==========================================================================
   Template tags
   ========================================================================== */

/** Featured image with a branded placeholder, mirroring the legacy Thumb. */
function ton_thumb( $size = 'ton-card', $class = '', $attr = array() ) {
	$classes = trim( 'ton-thumb ' . $class );
	if ( has_post_thumbnail() ) {
		$args = array( 'class' => $classes, 'loading' => 'lazy', 'decoding' => 'async' );
		$alt = trim( (string) get_post_meta( get_post_thumbnail_id(), '_wp_attachment_image_alt', true ) );
		$args['alt'] = $alt ? $alt : wp_strip_all_tags( get_the_title() );
		if ( 'ton-hero' === $size ) { $args['loading'] = 'eager'; $args['fetchpriority'] = 'high'; }
		if ( ! empty( $attr ) ) { $args = array_merge( $args, $attr ); }
		the_post_thumbnail( $size, $args );
		return;
	}
	$cats        = get_the_category();
	$label       = $cats ? $cats[0]->name : 'TotalOnlineNews';
	$color       = $cats ? ton_category_color( $cats[0] ) : '#E31B23';
	$placeholder = sprintf(
		'background:linear-gradient(135deg,%1$s26 0%%,%1$s59 55%%,%1$s99 100%%)',
		sanitize_hex_color( $color )
	);
	printf(
		'<span class="ton-thumb ton-thumb--ph %1$s" style="%2$s" aria-hidden="true"><span>%3$s</span></span>',
		esc_attr( $class ),
		esc_attr( $placeholder ),
		esc_html( $label )
	);
}

/**
 * Hindi relative time, e.g. "2 घंटे पहले".
 *
 * human_time_diff() only speaks English, and the whole site is Hindi, so every
 * timestamp on cards, widget rows and the RSS list goes through here.
 *
 * @param int $timestamp Unix timestamp of the post or item.
 * @return string
 */
function ton_ago_hi( $timestamp ) {
	$diff = max( 0, time() - (int) $timestamp );

	if ( $diff < MINUTE_IN_SECONDS ) {
		return 'अभी';
	}
	if ( $diff < HOUR_IN_SECONDS ) {
		return (int) floor( $diff / MINUTE_IN_SECONDS ) . ' मिनट पहले';
	}
	if ( $diff < DAY_IN_SECONDS ) {
		return (int) floor( $diff / HOUR_IN_SECONDS ) . ' घंटे पहले';
	}
	if ( $diff < 30 * DAY_IN_SECONDS ) {
		return (int) floor( $diff / DAY_IN_SECONDS ) . ' दिन पहले';
	}
	if ( $diff < YEAR_IN_SECONDS ) {
		return (int) floor( $diff / ( 30 * DAY_IN_SECONDS ) ) . ' महीने पहले';
	}

	return (int) floor( $diff / YEAR_IN_SECONDS ) . ' साल पहले';
}

/** "3 min read" style meta line. */
function ton_meta_line( $post_id = null, $class = '' ) {
	$post_id = $post_id ? $post_id : get_the_ID();
	$rt      = ton_reading_time( $post_id );
	printf(
		'<div class="ton-meta %1$s"><span>%2$s</span>%3$s</div>',
		esc_attr( $class ),
		esc_html( ton_ago_hi( get_the_time( 'U', $post_id ) ) ),
		$rt > 1 ? '<span aria-hidden="true">&bull;</span><span>' . esc_html( $rt . ' min read' ) . '</span>' : ''
	);
}

/**
 * Inline SVG icons - no icon font, no external request.
 *
 * Return one inline SVG icon as a STRING.
 *
 * Icons are inline so they never depend on an icon font or an external CDN.
 * Anything that needs the markup INSIDE a printf()/sprintf() must use this
 * function: PHP evaluates the argument before the format string is printed,
 * so an echoing helper would emit the SVG outside the surrounding element.
 */
function ton_icon_svg( $name, $class = '' ) {
	/* link and mail are stroke-designed paths, not solid shapes. */
	$stroke = array( 'search', 'menu', 'close', 'chevron-left', 'chevron-right', 'chevron-double-right', 'clock', 'bolt', 'link', 'mail', 'home' );
	$paths  = array(
		'search'        => '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
		'menu'          => '<path d="M3 6h18M3 12h18M3 18h18"/>',
		'close'         => '<path d="M6 6l12 12M18 6L6 18"/>',
		'chevron-left'  => '<path d="m15 18-6-6 6-6"/>',
		'chevron-right' => '<path d="m9 18 6-6-6-6"/>',
		'chevron-double-right' => '<path d="m6 17 5-5-5-5"/><path d="m13 17 5-5-5-5"/>',
		'clock'         => '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
		'bolt'          => '<path d="M13 2 4 14h6l-1 8 9-12h-6l1-8Z"/>',
		'pause'         => '<path d="M9 5h2.2v14H9zM12.8 5H15v14h-2.2z"/>',
		'play'          => '<path d="M8 5v14l11-7z"/>',
		'facebook'      => '<path d="M13.5 21v-8h2.7l.4-3.1h-3.1V7.9c0-.9.3-1.5 1.6-1.5h1.7V3.6c-.3 0-1.3-.1-2.4-.1-2.4 0-4 1.5-4 4.1v2.3H7.6V13h2.7v8h3.2Z"/>',
		'x'             => '<path d="M17.5 3h3l-6.6 7.6L21.8 21h-6l-4.7-6.1L5.6 21h-3l7-8L2.5 3h6.2l4.2 5.6L17.5 3Zm-1 16h1.7L8.1 4.7H6.3L16.5 19Z"/>',
		'instagram'     => '<path d="M12 2.2c3.2 0 3.6 0 4.9.1 1.2.1 1.8.3 2.2.5.6.2 1 .5 1.4.9.4.4.7.8.9 1.4.2.4.4 1 .5 2.2.1 1.3.1 1.7.1 4.9s0 3.6-.1 4.9c-.1 1.2-.3 1.8-.5 2.2-.2.6-.5 1-.9 1.4-.4.4-.8.7-1.4.9-.4.2-1 .4-2.2.5-1.3.1-1.7.1-4.9.1s-3.6 0-4.9-.1c-1.2-.1-1.8-.3-2.2-.5-.6-.2-1-.5-1.4-.9-.4-.4-.7-.8-.9-1.4-.2-.4-.4-1-.5-2.2C2.2 15.6 2.2 15.2 2.2 12s0-3.6.1-4.9c.1-1.2.3-1.8.5-2.2.2-.6.5-1 .9-1.4.4-.4.8-.7 1.4-.9.4-.2 1-.4 2.2-.5C8.4 2.2 8.8 2.2 12 2.2Zm0 3.1A6.7 6.7 0 1 0 18.7 12 6.7 6.7 0 0 0 12 5.3Zm0 11a4.3 4.3 0 1 1 4.3-4.3A4.3 4.3 0 0 1 12 16.3Zm6.9-11.2a1.6 1.6 0 1 1-1.6-1.6 1.6 1.6 0 0 1 1.6 1.6Z"/>',
		'youtube'       => '<path d="M22 8.2a3 3 0 0 0-2.1-2.1C18 5.5 12 5.5 12 5.5s-6 0-7.9.6A3 3 0 0 0 2 8.2 31 31 0 0 0 1.5 12 31 31 0 0 0 2 15.8a3 3 0 0 0 2.1 2.1c1.9.6 7.9.6 7.9.6s6 0 7.9-.6a3 3 0 0 0 2.1-2.1A31 31 0 0 0 22.5 12 31 31 0 0 0 22 8.2ZM10 15V9l5.2 3L10 15Z"/>',
		'telegram'      => '<path d="M21.9 4.3 18.6 20c-.2 1.1-.9 1.4-1.8.9l-4.9-3.6-2.4 2.3c-.3.3-.5.5-1 .5l.3-4.8 9.1-8.2c.4-.4-.1-.6-.6-.2L6.1 13.1.9 11.5c-1.1-.3-1.1-1.1.2-1.6L20.2 3c.9-.3 1.8.2 1.7 1.3Z"/>',
		'whatsapp'      => '<path d="M12 2a10 10 0 0 0-8.6 15L2 22l5.1-1.3A10 10 0 1 0 12 2Zm5.8 14.2c-.2.7-1.4 1.3-2 1.4-.5.1-1.1.1-1.8-.1a13 13 0 0 1-6.5-5.7c-.5-.8-.8-1.7-.8-2.6 0-1 .5-1.5.7-1.7.2-.2.4-.3.6-.3h.4c.1 0 .3 0 .5.4l.7 1.7c.1.2 0 .3-.1.5l-.3.4c-.1.1-.2.2-.1.4a8 8 0 0 0 3.6 3.1c.2.1.4.1.5 0l.7-.8c.2-.2.3-.2.5-.1l1.6.8c.2.1.4.2.4.3a3 3 0 0 1 0 .8Z"/>',
		'linkedin'      => '<path d="M6.9 21H3.6V9.2h3.3V21ZM5.2 7.7A1.9 1.9 0 1 1 7.1 5.8 1.9 1.9 0 0 1 5.2 7.7ZM21 21h-3.3v-5.7c0-1.4 0-3.1-1.9-3.1s-2.2 1.5-2.2 3v5.8H10.3V9.2h3.1v1.6h.1a3.4 3.4 0 0 1 3.1-1.7c3.3 0 3.9 2.2 3.9 5V21Z"/>',
		'link'          => '<path d="M10 13a5 5 0 0 0 7.1 0l3-3a5 5 0 0 0-7.1-7.1L11.5 4.4"/><path d="M14 11a5 5 0 0 0-7.1 0l-3 3a5 5 0 0 0 7.1 7.1l1.4-1.4"/>',
		'mail'          => '<path d="M3 6h18v12H3z"/><path d="m3 7 9 6 9-6"/>',
		'home'          => '<path d="m3 10 9-7 9 7v10a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z"/>',
	);
	if ( ! isset( $paths[ $name ] ) ) { return; }
	$filled = ! in_array( $name, $stroke, true );
	return sprintf(
		'<svg class="%1$s" width="%4$d" height="%4$d" viewBox="0 0 24 24" aria-hidden="true" focusable="false"%2$s>%3$s</svg>',
		esc_attr( $class ),
		$filled ? ' fill="currentColor"' : ' fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"',
		$paths[ $name ], // phpcs:ignore WordPress.Security.EscapeOutput -- fixed inline SVG markup.
		18
	);
}

/** Echo wrapper - keeps every existing template call site working unchanged. */
function ton_icon( $name, $class = '' ) {
	echo ton_icon_svg( $name, $class ); // phpcs:ignore WordPress.Security.EscapeOutput -- trusted inline SVG.
}

/* ==========================================================================
   Social sharing (accessible: real links, no third-party tracking scripts)
   ========================================================================== */
function ton_share_buttons( $post_id = null ) {
	$post_id = $post_id ? $post_id : get_the_ID();
	$url     = get_permalink( $post_id );
	$title   = get_the_title( $post_id );
	$u       = rawurlencode( $url );
	$t       = rawurlencode( $title );

	$targets = array(
		'facebook' => array( __( 'Share on Facebook', 'totalonlinenews' ), 'https://www.facebook.com/sharer/sharer.php?u=' . $u ),
		'x'        => array( __( 'Share on X', 'totalonlinenews' ), 'https://twitter.com/intent/tweet?url=' . $u . '&text=' . $t ),
		'whatsapp' => array( __( 'Share on WhatsApp', 'totalonlinenews' ), 'https://api.whatsapp.com/send?text=' . $t . '%20' . $u ),
		'telegram' => array( __( 'Share on Telegram', 'totalonlinenews' ), 'https://t.me/share/url?url=' . $u . '&text=' . $t ),
		'linkedin' => array( __( 'Share on LinkedIn', 'totalonlinenews' ), 'https://www.linkedin.com/sharing/share-offsite/?url=' . $u ),
		'mail'     => array( __( 'Share by email', 'totalonlinenews' ), 'mailto:?subject=' . $t . '&body=' . $u ),
	);

	echo '<div class="ton-share"><span class="ton-share__label">' . esc_html__( 'Share', 'totalonlinenews' ) . '</span>';
	foreach ( $targets as $icon => $data ) {
		printf(
			'<a href="%1$s" target="_blank" rel="noopener noreferrer nofollow" aria-label="%2$s" title="%2$s">%3$s</a>',
			esc_url( $data[1] ),
			esc_attr( $data[0] ),
			ton_icon_svg( $icon ) // phpcs:ignore WordPress.Security.EscapeOutput -- trusted inline SVG.
		);
	}
	/* Copy-link button: progressive enhancement, works without JS too. */
	printf(
		'<button type="button" class="ton-copy" data-ton-copy="%1$s" aria-label="%2$s" title="%2$s">%3$s</button>',
		esc_url( $url ),
		esc_attr__( 'Copy link', 'totalonlinenews' ),
		ton_icon_svg( 'link' ) // phpcs:ignore WordPress.Security.EscapeOutput -- trusted inline SVG.
	);
	echo '</div>';
}

/* ==========================================================================
   Source attribution (imported drafts carry an outbound source)
   ========================================================================== */
function ton_source_block( $post_id = null ) {
	$post_id = $post_id ? $post_id : get_the_ID();
	$name    = trim( (string) ton_meta( '_ton_source_name', $post_id ) );
	$url     = trim( (string) ton_meta( '_ton_source_url', $post_id ) );
	if ( ! $name && ! $url ) { return; }

	echo '<div class="ton-source">';
	if ( $name ) {
		printf( '<strong>%s:</strong> ', esc_html__( 'Source', 'totalonlinenews' ) );
		echo esc_html( $name );
	}
	if ( $url && filter_var( $url, FILTER_VALIDATE_URL ) ) {
		printf( ' &mdash; <a href="%1$s" target="_blank" rel="noopener noreferrer nofollow">%1$s</a>', esc_url( $url ) );
	}
	echo '</div>';
}

/* ==========================================================================
   Gallery (stored as a comma-separated attachment id list by the migration)
   ========================================================================== */
function ton_gallery_block( $post_id = null ) {
	$post_id = $post_id ? $post_id : get_the_ID();
	$raw     = trim( (string) ton_meta( '_ton_gallery', $post_id ) );
	if ( ! $raw ) { return; }
	$ids = array_filter( array_map( 'absint', explode( ',', $raw ) ) );
	if ( ! $ids ) { return; }

	echo '<div class="ton-gallery" role="list">';
	foreach ( $ids as $id ) {
		$full = wp_get_attachment_image_url( $id, 'full' );
		if ( ! $full ) { continue; }
		$alt = get_post_meta( $id, '_wp_attachment_image_alt', true );
		printf(
			'<a href="%1$s" class="ton-groupfocus" role="listitem"><img src="%1$s" alt="%2$s" loading="lazy" decoding="async" /></a>',
			esc_url( $full ),
			esc_attr( $alt ? $alt : get_the_title( $post_id ) )
		);
	}
	echo '</div>';
}

/* ==========================================================================
   Navigation - falls back to real category links when no menu is assigned
   ========================================================================== */
function ton_fallback_nav() {
	echo '<ul id="primary-menu" class="ton-nav__list">';
	printf(
		'<li%1$s><a href="%2$s">%3$s %4$s</a></li>',
		is_front_page() ? ' class="current-menu-item"' : '',
		esc_url( home_url( '/' ) ),
		ton_icon_svg( 'home', 'ton-nav__home-icon' ),
		esc_html__( 'Home', 'totalonlinenews' )
	);
	foreach ( ton_categories() as $term ) {
		$icon = ton_category_icon( $term );
		printf(
			'<li%1$s><a href="%2$s">%3$s%4$s</a></li>',
			( is_category( $term->term_id ) ? ' class="current-menu-item"' : '' ),
			esc_url( get_category_link( $term->term_id ) ),
			$icon ? '<span aria-hidden="true">' . esc_html( $icon ) . '</span> ' : '',
			esc_html( $term->name )
		);
	}
	if ( get_page_by_path( 'newsletter' ) ) {
		printf( '<li class="ton-nav__newsletter"><a href="%1$s">%2$s</a></li>', esc_url( home_url( '/newsletter/' ) ), esc_html__( 'Newsletter', 'totalonlinenews' ) );
	}
	echo '</ul>';
}

/** Append the public newsletter signup to a custom primary menu too. */
function ton_newsletter_primary_menu_item( $items, $args ) {
	if ( empty( $args->theme_location ) || 'primary' !== $args->theme_location || ! get_page_by_path( 'newsletter' ) || false !== strpos( $items, 'href="' . esc_url( home_url( '/newsletter/' ) ) . '"' ) ) {
		return $items;
	}
	return $items . '<li class="menu-item ton-nav__newsletter"><a href="' . esc_url( home_url( '/newsletter/' ) ) . '">' . esc_html__( 'Newsletter', 'totalonlinenews' ) . '</a></li>';
}
add_filter( 'wp_nav_menu_items', 'ton_newsletter_primary_menu_item', 20, 2 );

/* ==========================================================================
   Excerpt length
   ========================================================================== */
add_filter( 'excerpt_length', function () { return 24; }, 999 );
add_filter( 'excerpt_more', function () { return '&hellip;'; } );

/* ==========================================================================
   Comments - the legacy CMS kept them disabled portal-wide; the migration
   already stored the correct comment_status on every post, so the theme does
   not override it. This only closes comments site-wide when the migrated
   setting says so, without touching individual posts.
   ========================================================================== */

/* ==========================================================================
   Social profile list (only the networks actually configured are shown)
   ========================================================================== */
function ton_social_list( $class = '' ) {
	$socials = ton_socials();
	if ( ! $socials ) { return; }
	$icons = array( 'Facebook' => 'facebook', 'X' => 'x', 'Instagram' => 'instagram', 'YouTube' => 'youtube', 'Telegram' => 'telegram' );
	echo '<ul class="ton-socials ' . esc_attr( $class ) . '">';
	foreach ( $socials as $label => $url ) {
		printf(
			'<li><a href="%1$s" target="_blank" rel="noopener noreferrer" aria-label="%2$s">%3$s<span class="ton-socials__label">%2$s</span></a></li>',
			esc_url( $url ),
			esc_attr( sprintf( __( '%1$s on %2$s', 'totalonlinenews' ), ton_site_name(), $label ) ),
			ton_icon_svg( isset( $icons[ $label ] ) ? $icons[ $label ] : 'link' ) // phpcs:ignore WordPress.Security.EscapeOutput -- trusted inline SVG.
		);
	}
	echo '</ul>';
}

/* Hide the text label inside the header/utility variants; the footer shows it. */
function ton_social_label_css() {
	echo '<style id="ton-social-labels">.ton-utility .ton-socials__label,.ton-masthead .ton-socials__label{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap}</style>';
}
add_action( 'wp_head', 'ton_social_label_css', 5 );

/* ==========================================================================
   Masthead social icons
   Right of the logo/tagline, before the search and menu buttons.
   ========================================================================== */

/**
 * The newsroom's official profiles, in display order.
 *
 * Each entry carries the legacy option that can override it, so a URL edited
 * in the settings screen keeps winning over the default below. YouTube is
 * deliberately absent: only these four networks belong in the masthead.
 *
 * @return array<string,array{option:string,icon:string,url:string}>
 */
function ton_masthead_social_defaults() {
	return array(
		'Facebook'  => array(
			'option' => 'ton_social_facebook',
			'icon'   => 'facebook',
			'url'    => 'https://www.facebook.com/profile.php?id=61595148851319',
		),
		'X'         => array(
			'option' => 'ton_social_x',
			'icon'   => 'x',
			'url'    => 'https://x.com/totalonlinenews?s=11',
		),
		'Instagram' => array(
			'option' => 'ton_social_instagram',
			'icon'   => 'instagram',
			'url'    => 'https://www.instagram.com/totalonline.news?rpxt=OWhjMnl6NXdhcDY1&utm_source=qr',
		),
		'Telegram'  => array(
			'option' => 'ton_social_telegram',
			'icon'   => 'telegram',
			'url'    => 'https://t.me/totalonlinenews',
		),
	);
}

/**
 * Icon-only social links for the masthead.
 *
 * Kept separate from ton_social_list() so the utility bar, the mobile drawer
 * and the footer keep rendering exactly what their settings say.
 */
function ton_masthead_socials() {
	$items = array();
	foreach ( ton_masthead_social_defaults() as $label => $social ) {
		$url = trim( (string) get_option( $social['option'], '' ) );
		if ( '' === $url ) {
			$url = $social['url'];
		}
		if ( '' === $url ) {
			continue;
		}
		$items[ $label ] = array(
			'url'  => $url,
			'icon' => $social['icon'],
		);
	}
	if ( ! $items ) {
		return;
	}

	echo '<ul class="ton-socials ton-socials--masthead" aria-label="' . esc_attr__( 'Follow us on social media', 'totalonlinenews' ) . '">';
	foreach ( $items as $label => $social ) {
		$name = sprintf( __( '%1$s on %2$s', 'totalonlinenews' ), ton_site_name(), $label );
		printf(
			'<li><a href="%1$s" target="_blank" rel="noopener noreferrer" aria-label="%2$s" title="%2$s">%3$s<span class="ton-socials__label">%4$s</span></a></li>',
			esc_url( $social['url'] ),
			esc_attr( $name ),
			ton_icon_svg( $social['icon'] ), // phpcs:ignore WordPress.Security.EscapeOutput -- trusted inline SVG.
			esc_html( $label )
		);
	}
	echo '</ul>';
}

/* ==========================================================================
   Pagination
   ========================================================================== */
function ton_pagination() {
	$links = paginate_links( array(
		'type'      => 'array',
		'prev_text' => esc_html__( '\u2039 Prev', 'totalonlinenews' ),
		'next_text' => esc_html__( 'Next \u203a', 'totalonlinenews' ),
	) );
	if ( ! $links ) { return; }
	echo '<nav class="ton-pagination" aria-label="' . esc_attr__( 'Posts navigation', 'totalonlinenews' ) . '">';
	foreach ( $links as $link ) { echo wp_kses_post( $link ); }
	echo '</nav>';
}

/* Friendly, translatable titles for the archive views. */
add_filter( 'get_the_archive_title', function ( $title ) {
	if ( is_category() || is_tag() || is_tax() ) { return single_term_title( '', false ); }
	if ( is_author() ) { return get_the_author(); }
	if ( is_search() ) { return sprintf( __( 'Search: %s', 'totalonlinenews' ), get_search_query() ); }
	if ( is_post_type_archive() ) { return post_type_archive_title( '', false ); }
	return $title;
} );

/* ==========================================================================
   Homepage de-duplication
   --------------------------------------------------------------------------
   The front page renders seven blocks (hero, trending, latest, category rows,
   Popular, Editor's Picks). Before this registry every block queried
   independently, so the same story could appear up to seven times: measured on
   production, 213 article links resolved to only 83 distinct posts, and both
   sidebar widgets were 100% repeats.

   ton_shown() is one process-wide list of post IDs already printed. Every
   front-page query passes it as post__not_in and then registers what it used,
   so a story can appear on the home page exactly once.
   ========================================================================== */

/**
 * Read or extend the list of posts already printed on this page.
 *
 * @param int[]|int|null $ids Null to read, IDs to register.
 * @return int[] Currently registered IDs.
 */
function ton_shown( $ids = null ) {
	if ( ! isset( $GLOBALS['ton_shown_ids'] ) ) {
		$GLOBALS['ton_shown_ids'] = array();
	}

	if ( null !== $ids ) {
		foreach ( (array) $ids as $id ) {
			$id = (int) $id;
			if ( $id > 0 ) {
				$GLOBALS['ton_shown_ids'][ $id ] = true;
			}
		}
	}

	return array_keys( $GLOBALS['ton_shown_ids'] );
}

/** Forget everything printed so far (used by tests and by ajax re-renders). */
function ton_shown_reset() {
	$GLOBALS['ton_shown_ids'] = array();
}

/* ==========================================================================
   Primary navigation
   --------------------------------------------------------------------------
   The legacy menu carried 28 entries - 15 Devanagari categories, 11 English
   ones prefixed with emoji, plus Home and Newsletter - which overflowed the
   bar into a sideways scroller. The bar now shows the seven categories the
   newsroom actually leads with and moves the rest under a single "More"
   control. Nothing is deleted: every category stays reachable and the footer
   still lists all of them.
   ========================================================================== */

/**
 * The seven lead categories, resolved by NAME so the percent-encoded
 * Devanagari slugs never have to be written down.
 *
 * @return array<int,array{term:WP_Term,label:string}>
 */
function ton_nav_primary_items() {
	static $items = null;

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

	$config = apply_filters(
		'ton_nav_primary_config',
		array(
			array( 'name' => 'भारत', 'label' => 'भारत' ),
			array( 'name' => 'राजस्थान', 'label' => 'राजस्थान' ),
			array( 'name' => 'हरियाणा', 'label' => 'हरियाणा' ),
			array( 'name' => 'महाराष्ट्र', 'label' => 'महाराष्ट्र' ),
			array( 'name' => 'क्रिकेट', 'label' => 'क्रिकेट' ),
			array( 'name' => 'बिज़नेस', 'label' => 'बिज़नेस' ),
			array( 'name' => 'टेक्नोलॉजी', 'label' => 'टेक्नोलॉजी' ),
			array( 'name' => 'मनोरंजन', 'label' => 'मनोरंजन' ),
		)
	);

	$items = array();
	$ids   = array();

	foreach ( $config as $entry ) {
		$term = get_term_by( 'name', $entry['name'], 'category' );

		if ( ! $term || is_wp_error( $term ) ) {
			continue;
		}

		$ids[] = (int) $term->term_id;

		$items[] = array(
			'term'  => $term,
			'label' => '' !== $entry['label'] ? $entry['label'] : $term->name,
		);
	}

	/* Remember the lead IDs so the "More" list can exclude them. */
	$GLOBALS['ton_nav_primary_ids'] = $ids;

	return $items;
}

/**
 * Everything the "More" dropdown carries: every other category that actually
 * holds published posts, in the newsroom display order.
 *
 * @return WP_Term[]
 */
/**
 * Everything the "More" dropdown carries: every other category that actually
 * holds published posts, in the newsroom display order.
 *
 * @return WP_Term[]
 */
function ton_nav_more_items() {
	$lead = isset( $GLOBALS['ton_nav_primary_ids'] ) ? (array) $GLOBALS['ton_nav_primary_ids'] : array();
	$out  = array();

	foreach ( ton_categories() as $term ) {
		if ( (int) $term->count < 1 ) {
			continue;
		}
		if ( in_array( (int) $term->term_id, $lead, true ) ) {
			continue;
		}
		$out[] = $term;
	}

	return $out;
}

/**
 * Renders the desktop category bar: seven lead links plus a "More" menu.
 *
 * Replaces wp_nav_menu() for the `primary` location, so the site menu stored in
 * the database is left untouched and rolling back is a one-line change.
 *
 * @return void
 */
function ton_primary_nav() {
	$items = ton_nav_primary_items();
	$more  = ton_nav_more_items();
	$home  = home_url( '/' );
	?>
	<div class="ton-nav__in">
		<ul class="ton-nav__list">
			<li class="ton-nav__item ton-nav__item--home">
				<a href="<?php echo esc_url( $home ); ?>"<?php echo is_front_page() ? ' class="is-current"' : ''; ?>>
					<?php ton_icon( 'home', 'ton-nav__home-icon' ); ?>
					<span class="screen-reader-text"><?php esc_html_e( 'Home', 'totalonlinenews' ); ?></span>
				</a>
			</li>

			<?php foreach ( $items as $item ) : ?>
				<li class="ton-nav__item">
					<a href="<?php echo esc_url( get_category_link( $item['term']->term_id ) ); ?>"<?php echo is_category( $item['term']->term_id ) ? ' class="is-current"' : ''; ?>>
						<?php echo esc_html( $item['label'] ); ?>
					</a>
				</li>
			<?php endforeach; ?>
		</ul>

		<?php if ( $more ) : ?>
			<?php /* The "More" control sits OUTSIDE .ton-nav__list on purpose: that
			         list is an overflow-x scroller on narrow screens, and a scroller
			         clips absolutely positioned children. */ ?>
			<div class="ton-nav__morewrap">
				<button type="button"
					class="ton-nav__morebtn"
					data-ton-nav-more
					aria-expanded="false"
					aria-controls="ton-nav-more">
					<?php esc_html_e( 'More', 'totalonlinenews' ); ?>
					<svg width="14" height="14" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
				</button>
				<ul class="ton-nav__more notranslate" translate="no" id="ton-nav-more" hidden>
					<?php foreach ( $more as $term ) : ?>
						<li>
							<a href="<?php echo esc_url( get_category_link( $term->term_id ) ); ?>"<?php echo is_category( $term->term_id ) ? ' class="is-current"' : ''; ?>>
								<?php echo esc_html( $term->name ); ?>
								<em><?php echo esc_html( (string) $term->count ); ?></em>
							</a>
						</li>
					<?php endforeach; ?>
				</ul>
			</div>
		<?php endif; ?>
	</div>
	<?php
}

/**
 * Renders the mobile drawer navigation as a flat list.
 *
 * A dropdown inside a drawer is a two-tap dead end, so every category is listed
 * directly here. Emoji from the legacy term meta are deliberately not printed.
 *
 * @return void
 */
function ton_mobile_nav() {
	$items = ton_nav_primary_items();
	$more  = ton_nav_more_items();
	?>
	<ul class="ton-mnav">
		<li>
			<a href="<?php echo esc_url( home_url( '/' ) ); ?>"<?php echo is_front_page() ? ' class="is-active"' : ''; ?>>
				<?php ton_icon( 'home', 'ton-mnav__ico' ); ?>
				<?php esc_html_e( 'Home', 'totalonlinenews' ); ?>
			</a>
		</li>

		<?php foreach ( $items as $item ) : ?>
			<li>
				<a href="<?php echo esc_url( get_category_link( $item['term']->term_id ) ); ?>"<?php echo is_category( $item['term']->term_id ) ? ' class="is-active"' : ''; ?>>
					<?php echo esc_html( $item['label'] ); ?>
				</a>
			</li>
		<?php endforeach; ?>

		<?php if ( $more ) : ?>
			<li class="ton-mnav__label" aria-hidden="true"><?php esc_html_e( 'More categories', 'totalonlinenews' ); ?></li>
			<?php foreach ( $more as $term ) : ?>
				<li>
					<a href="<?php echo esc_url( get_category_link( $term->term_id ) ); ?>"<?php echo is_category( $term->term_id ) ? ' class="is-active"' : ''; ?>>
						<?php echo esc_html( $term->name ); ?>
					</a>
				</li>
			<?php endforeach; ?>
		<?php endif; ?>
	</ul>
	<?php
}



/* ==========================================================================
   Homepage category blocks
   --------------------------------------------------------------------------
   The home page used to print a block for all 26 categories, which pushed the
   card count past 100 and buried the newest reporting. A block is now printed
   only when the category has at least three stories from the last seven days,
   and never more than TON_HOME_MAX_BLOCKS blocks are printed at all.
   ========================================================================== */

/** Hard ceiling on homepage category blocks. */
define( 'TON_HOME_MAX_BLOCKS', 10 );

/** A block needs at least this many recent stories. */
define( 'TON_HOME_MIN_RECENT', 3 );

/**
 * Number of published posts per category inside the last N days.
 *
 * One grouped query for the whole page instead of 26 separate WP_Query calls.
 * Uses current_time('mysql') because post_date is stored in site-local time.
 *
 * @param int $days Look-back window.
 * @return array<int,int> term_id => count
 */
function ton_category_recent_counts( $days = 7 ) {
	static $cache = array();

	$days = max( 1, (int) $days );

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

	global $wpdb;

	$since = date( 'Y-m-d H:i:s', current_time( 'timestamp' ) - ( $days * DAY_IN_SECONDS ) );

	$rows = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT tt.term_id AS term_id, COUNT(DISTINCT p.ID) AS total
			 FROM {$wpdb->term_relationships} tr
			 INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
			 INNER JOIN {$wpdb->posts} p ON p.ID = tr.object_id
			 WHERE tt.taxonomy = 'category'
			   AND p.post_type = 'post'
			   AND p.post_status = 'publish'
			   AND p.post_date >= %s
			 GROUP BY tt.term_id",
			$since
		)
	);

	$out = array();

	foreach ( (array) $rows as $row ) {
		$out[ (int) $row->term_id ] = (int) $row->total;
	}

	$cache[ $days ] = $out;

	return $out;
}

/**
 * Whether a category block should be printed on the homepage.
 *
 * @param int $term_id    Category term ID.
 * @param int $shown      How many blocks have already been printed.
 * @param int $days       Look-back window.
 * @return bool
 */
function ton_show_category_block( $term_id, $shown = 0, $days = 30 ) {
	if ( (int) $shown >= TON_HOME_MAX_BLOCKS ) {
		return false;
	}

	$counts = ton_category_recent_counts( $days );

	return isset( $counts[ (int) $term_id ] ) && (int) $counts[ (int) $term_id ] >= TON_HOME_MIN_RECENT;
}


/* ==========================================================================
   Language switcher
   --------------------------------------------------------------------------
   Client-side Google Translate only. The site itself stays Hindi for crawlers:
   no translated HTML, no per-language URLs, no hreflang. The browser sets a
   `googtrans` cookie and, only then, loads Google's widget script.

   Every code below was verified against the Translate engine (client=gtx,
   sl=hi), which returned HTTP 200 with real output for all twenty. Google's
   own script is not loaded for a default Hindi visitor at all.

   `short` is the two-character badge shown in the header button, written in the
   language's own script so it reads correctly at a glance.
   ========================================================================== */

/**
 * Languages offered by the switcher.
 *
 * @return array<int,array<string,mixed>>
 */
function ton_languages() {
	return apply_filters(
		'ton_languages',
		array(
			array( 'code' => 'hi',       'label' => 'हिन्दी',      'short' => 'हि',   'rtl' => false ),
			array( 'code' => 'en',       'label' => 'English',    'short' => 'EN',   'rtl' => false ),
			array( 'code' => 'bn',       'label' => 'বাংলা',       'short' => 'বাং',  'rtl' => false ),
			array( 'code' => 'mr',       'label' => 'मराठी',       'short' => 'मरा',  'rtl' => false ),
			array( 'code' => 'te',       'label' => 'తెలుగు',      'short' => 'తె',   'rtl' => false ),
			array( 'code' => 'ta',       'label' => 'தமிழ்',       'short' => 'த',    'rtl' => false ),
			array( 'code' => 'gu',       'label' => 'ગુજરાતી',     'short' => 'ગુ',   'rtl' => false ),
			array( 'code' => 'kn',       'label' => 'ಕನ್ನಡ',       'short' => 'ಕ',    'rtl' => false ),
			array( 'code' => 'ml',       'label' => 'മലയാളം',      'short' => 'മ',    'rtl' => false ),
			array( 'code' => 'pa',       'label' => 'ਪੰਜਾਬੀ',      'short' => 'ਪੰ',   'rtl' => false ),
			array( 'code' => 'or',       'label' => 'ଓଡ଼ିଆ',       'short' => 'ଓ',    'rtl' => false ),
			array( 'code' => 'ur',       'label' => 'اردو',        'short' => 'ا',    'rtl' => true ),
			array( 'code' => 'as',       'label' => 'অসমীয়া',      'short' => 'অ',    'rtl' => false ),
			array( 'code' => 'mai',      'label' => 'मैथिली',      'short' => 'मै',   'rtl' => false ),
			array( 'code' => 'sa',       'label' => 'संस्कृतम्',    'short' => 'सं',   'rtl' => false ),
			array( 'code' => 'gom',      'label' => 'कोंकणी',      'short' => 'कों',  'rtl' => false ),
			array( 'code' => 'sd',       'label' => 'सिन्धी',      'short' => 'سن',   'rtl' => true ),
			array( 'code' => 'doi',      'label' => 'डोगरी',       'short' => 'डो',   'rtl' => false ),
			array( 'code' => 'mni-Mtei', 'label' => 'ꯃꯩꯇꯩꯂꯣꯟ',    'short' => 'ꯃ',    'rtl' => false ),
			array( 'code' => 'bho',      'label' => 'भोजपुरी',     'short' => 'भो',   'rtl' => false ),
		)
	);
}

/**
 * The source language the site is written in.
 *
 * @return string
 */
function ton_source_language() {
	return (string) apply_filters( 'ton_source_language', 'hi' );
}

/**
 * Look up one language entry by code.
 *
 * @param string $code Language code.
 * @return array|null
 */
function ton_language( $code ) {
	foreach ( ton_languages() as $lang ) {
		if ( $lang['code'] === $code ) {
			return $lang;
		}
	}

	return null;
}

/**
 * Comma-separated code list handed to Google's widget.
 *
 * @return string
 */
function ton_language_codes() {
	return implode( ',', wp_list_pluck( ton_languages(), 'code' ) );
}

/**
 * True when the visitor already carries a Google Translate choice.
 *
 * The cookie is the only signal available on the server, and it is exactly the
 * condition under which the browser will need Google's hosts.
 *
 * @return bool
 */
function ton_translation_active() {
	$raw = isset( $_COOKIE['googtrans'] ) ? (string) wp_unslash( $_COOKIE['googtrans'] ) : '';

	/* Shape is /source/target, e.g. /hi/bn or /hi/mni-Mtei. */
	return (bool) preg_match( '#^/[A-Za-z]{2,3}(?:-[A-Za-z]+)?/[A-Za-z]{2,3}(?:-[A-Za-z]+)?$#', $raw );
}

/**
 * Warm the connection to Google's Translate hosts.
 *
 * Only printed for a visitor who has already chosen a language, so a default
 * Hindi reader gets no extra hints, no extra tags and no extra bytes.
 *
 * @return void
 */
function ton_language_resource_hints() {
	if ( ! ton_translation_active() ) {
		return;
	}

	$hosts = array(
		'https://translate.google.com',
		'https://translate.googleapis.com',
		'https://translate-pa.googleapis.com',
		'https://www.gstatic.com',
	);

	echo "\n<!-- TotalOnlineNews: Translate connection warm-up -->\n";

	foreach ( $hosts as $host ) {
		printf( '<link rel="preconnect" href="%s">' . "\n", esc_url( $host ) );
		printf( '<link rel="dns-prefetch" href="%s">' . "\n", esc_url( $host ) );
	}
}
add_action( 'wp_head', 'ton_language_resource_hints', 1 );

/**
 * Header button: globe + the current language's short code.
 *
 * The server always renders Hindi; the inline bootstrap rewrites the badge from
 * localStorage before first paint, so a returning reader never sees a flash of
 * the wrong code.
 *
 * @return void
 */
function ton_language_button() {
	$hi = ton_language( 'hi' );
	?>
	<button type="button"
		class="ton-langbtn notranslate"
		translate="no"
		data-ton-lang-open
		aria-haspopup="dialog"
		aria-expanded="false"
		aria-controls="ton-lang-panel"
		aria-label="<?php esc_attr_e( 'भाषा बदलें', 'totalonlinenews' ); ?>">
		<svg class="ton-langbtn__globe" width="20" height="20" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
			<circle cx="12" cy="12" r="9"/><path d="M3 12h18"/><path d="M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18Z"/>
		</svg>
		<span class="ton-langbtn__label" data-ton-lang-label><?php echo esc_html( $hi['label'] ); ?></span>
		<svg class="ton-langbtn__chev" width="12" height="12" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
			<path d="m6 9 6 6 6-6"/>
		</svg>
	</button>
	<?php
}

/**
 * The picker itself. Rendered once per page and shared by the header button and
 * the drawer button. Every language name carries notranslate/translate="no" so
 * Google never translates the picker into the language being picked.
 *
 * @return void
 */
function ton_language_panel() {
	$codes = ton_language_codes();
	$src   = ton_source_language();
	?>
	<div class="ton-lang" id="ton-lang-panel" data-ton-lang-panel hidden>
		<button type="button" class="ton-lang__scrim" data-ton-lang-close tabindex="-1" aria-hidden="true"></button>
		<div class="ton-lang__box notranslate" translate="no" role="dialog" aria-modal="true" aria-labelledby="ton-lang-h" data-ton-source="<?php echo esc_attr( $src ); ?>" data-ton-codes="<?php echo esc_attr( $codes ); ?>">
			<div class="ton-lang__head">
				<h2 class="ton-lang__title notranslate" translate="no" id="ton-lang-h"><?php esc_html_e( 'भाषा चुनें', 'totalonlinenews' ); ?></h2>
				<button type="button" class="ton-lang__x" data-ton-lang-close aria-label="<?php esc_attr_e( 'बंद करें', 'totalonlinenews' ); ?>">
					<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
				</button>
			</div>
			<ul class="ton-lang__list">
				<?php foreach ( ton_languages() as $lang ) : ?>
					<li>
						<button type="button"
							class="ton-lang__item notranslate<?php echo $lang['code'] === $src ? ' is-current' : ''; ?>"
							translate="no"
							lang="<?php echo esc_attr( $lang['code'] ); ?>"
							dir="<?php echo $lang['rtl'] ? 'rtl' : 'ltr'; ?>"
							data-ton-lang-set="<?php echo esc_attr( $lang['code'] ); ?>"
							data-ton-lang-short="<?php echo esc_attr( $lang['short'] ); ?>"
							data-ton-lang-rtl="<?php echo $lang['rtl'] ? '1' : '0'; ?>">
							<span class="ton-lang__name"><?php echo esc_html( $lang['label'] ); ?></span>
							<?php if ( $lang['code'] === $src ) : ?>
								<em class="ton-lang__tag"><?php esc_html_e( 'मूल', 'totalonlinenews' ); ?></em>
							<?php endif; ?>
						</button>
					</li>
				<?php endforeach; ?>
			</ul>
			<p class="ton-lang__note notranslate" translate="no"><?php esc_html_e( 'अनुवाद Google का है। मूल खबरें हिन्दी में ही हैं।', 'totalonlinenews' ); ?></p>
		<