<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Support;

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

final class FlagHelper
{
	/**
	 * Get the URL for a flag SVG by language code.
	 */
	public static function getFlagUrl(string $langCode): string
	{
		$flagFile = self::resolveFlagFile($langCode);
		return plugins_url('assets/img/flags/' . $flagFile, SIGNOCORE_ML_FILE);
	}

	/**
	 * Get an <img> tag for a flag.
	 */
	public static function getFlagImg(string $langCode, int $width = 20, int $height = 15, string $alt = ''): string
	{
		$url = self::getFlagUrl($langCode);
		return sprintf(
			'<img src="%s" alt="%s" class="sml-flag" width="%d" height="%d" loading="lazy">',
			esc_url($url),
			esc_attr($alt),
			$width,
			$height
		);
	}

	/**
	 * Check if a flag file exists for a language code.
	 */
	public static function flagExists(string $langCode): bool
	{
		$file = self::resolveFlagFile($langCode);
		$path = SIGNOCORE_ML_DIR . 'assets/img/flags/' . $file;

		return file_exists($path);
	}

	/**
	 * Resolve the flag filename, handling language code to country code mapping.
	 */
	private static function resolveFlagFile(string $langCode): string
	{
		// Direct mapping for codes that don't match country codes
		$map = [
			'en' => 'gb.svg',
			'ja' => 'jp.svg',
			'ko' => 'kr.svg',
			'zh-hans' => 'cn.svg',
			'zh-hant' => 'tw.svg',
			'ar' => 'sa.svg',
			'he' => 'il.svg',
			'hi' => 'in.svg',
			'bn' => 'bd.svg',
			'el' => 'gr.svg',
			'fa' => 'ir.svg',
			'ka' => 'ge.svg',
			'kk' => 'kz.svg',
			'km' => 'kh.svg',
			'ku' => 'iq.svg',
			'ms' => 'my.svg',
			'nb' => 'no.svg',
			'ne' => 'np.svg',
			'pt-br' => 'br.svg',
			'sv' => 'se.svg',
			'sw' => 'tz.svg',
			'ta' => 'in.svg',
			'uk' => 'ua.svg',
			'ur' => 'pk.svg',
			'vi' => 'vn.svg',
			'cs' => 'cz.svg',
			'da' => 'dk.svg',
			'et' => 'ee.svg',
			'hy' => 'am.svg',
			'sl' => 'si.svg',
			'sq' => 'al.svg',
			'sr' => 'rs.svg',
		];

		return $map[$langCode] ?? $langCode . '.svg';
	}
}
