<?php
/**
 * Country/flag helpers for Chess Podium
 *
 * @package Chess_Podium
 */

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

final class ChessPodium_CountryHelper
{
    /** FIDE 3-letter federation code to ISO 3166-1 alpha-2 */
    private const FIDE_TO_ISO = [
        'AFG' => 'AF', 'ALB' => 'AL', 'ALG' => 'DZ', 'AND' => 'AD', 'ANG' => 'AO', 'ARG' => 'AR',
        'ARM' => 'AM', 'AUS' => 'AU', 'AUT' => 'AT', 'AZE' => 'AZ', 'BAH' => 'BH', 'BAN' => 'BD',
        'BEL' => 'BE', 'BIH' => 'BA', 'BLR' => 'BY', 'BOL' => 'BO', 'BRA' => 'BR', 'BRN' => 'BN',
        'BUL' => 'BG', 'BUR' => 'MM', 'CAM' => 'KH', 'CAN' => 'CA', 'CHI' => 'CL', 'CHN' => 'CN',
        'COL' => 'CO', 'CRC' => 'CR', 'CRO' => 'HR', 'CUB' => 'CU', 'CYP' => 'CY', 'CZE' => 'CZ',
        'DEN' => 'DK', 'DOM' => 'DO', 'ECU' => 'EC', 'EGY' => 'EG', 'ENG' => 'GB', 'ESA' => 'SV',
        'EST' => 'EE', 'ETH' => 'ET', 'FIN' => 'FI', 'FRA' => 'FR', 'GEO' => 'GE', 'GER' => 'DE',
        'GRE' => 'GR', 'GUA' => 'GT', 'HKG' => 'HK', 'HON' => 'HN', 'HUN' => 'HU', 'ICE' => 'IS',
        'IND' => 'IN', 'INA' => 'ID', 'IRI' => 'IR', 'IRL' => 'IE', 'ISR' => 'IL', 'ITA' => 'IT',
        'JAM' => 'JM', 'JPN' => 'JP', 'KAZ' => 'KZ', 'KEN' => 'KE', 'KOR' => 'KR', 'KOS' => 'XK',
        'KSA' => 'SA', 'KUW' => 'KW', 'LAT' => 'LV', 'LIB' => 'LB', 'LIE' => 'LI', 'LTU' => 'LT',
        'LUX' => 'LU', 'MAC' => 'MO', 'MAD' => 'MG', 'MAL' => 'MY', 'MAR' => 'MA', 'MDA' => 'MD',
        'MEX' => 'MX', 'MGL' => 'MN', 'MKD' => 'MK', 'MLT' => 'MT', 'MNE' => 'ME', 'MON' => 'MC',
        'NED' => 'NL', 'NOR' => 'NO', 'NZL' => 'NZ', 'PAK' => 'PK', 'PAN' => 'PA', 'PAR' => 'PY',
        'PER' => 'PE', 'PHI' => 'PH', 'POL' => 'PL', 'POR' => 'PT', 'PUR' => 'PR', 'QAT' => 'QA',
        'ROU' => 'RO', 'RSA' => 'ZA', 'RUS' => 'RU', 'SCO' => 'GB', 'SEN' => 'SN', 'SGP' => 'SG',
        'SLO' => 'SI', 'SRB' => 'RS', 'SUI' => 'CH', 'SVK' => 'SK', 'SWE' => 'SE', 'SYR' => 'SY', 'THA' => 'TH',
        'TUN' => 'TN', 'TUR' => 'TR', 'UAE' => 'AE', 'UKR' => 'UA', 'URU' => 'UY', 'USA' => 'US',
        'UZB' => 'UZ', 'VEN' => 'VE', 'VIE' => 'VN', 'WLS' => 'GB', 'YEM' => 'YE',
    ];

    /** ISO 2-letter to country name (for dropdown). Alphabetical by name. */
    public static function get_countries(): array
    {
        $list = [
            'AF' => 'Afghanistan', 'AL' => 'Albania', 'DZ' => 'Algeria', 'AD' => 'Andorra',
            'AO' => 'Angola', 'AR' => 'Argentina', 'AM' => 'Armenia', 'AU' => 'Australia',
            'AT' => 'Austria', 'AZ' => 'Azerbaijan', 'BH' => 'Bahrain', 'BD' => 'Bangladesh',
            'BY' => 'Belarus', 'BE' => 'Belgium', 'BZ' => 'Belize', 'BJ' => 'Benin',
            'BT' => 'Bhutan', 'BO' => 'Bolivia', 'BA' => 'Bosnia and Herzegovina',
            'BW' => 'Botswana', 'BR' => 'Brazil', 'BN' => 'Brunei', 'BG' => 'Bulgaria',
            'BF' => 'Burkina Faso', 'MM' => 'Myanmar', 'BI' => 'Burundi', 'KH' => 'Cambodia',
            'CM' => 'Cameroon', 'CA' => 'Canada', 'CV' => 'Cape Verde', 'CF' => 'Central African Republic',
            'TD' => 'Chad', 'CL' => 'Chile', 'CN' => 'China', 'CO' => 'Colombia',
            'KM' => 'Comoros', 'CG' => 'Congo', 'CR' => 'Costa Rica', 'CI' => 'Ivory Coast',
            'HR' => 'Croatia', 'CU' => 'Cuba', 'CY' => 'Cyprus', 'CZ' => 'Czech Republic',
            'CD' => 'DR Congo', 'DK' => 'Denmark', 'DJ' => 'Djibouti', 'DO' => 'Dominican Republic',
            'EC' => 'Ecuador', 'EG' => 'Egypt', 'SV' => 'El Salvador', 'GQ' => 'Equatorial Guinea',
            'ER' => 'Eritrea', 'EE' => 'Estonia', 'SZ' => 'Eswatini', 'ET' => 'Ethiopia',
            'FJ' => 'Fiji', 'FI' => 'Finland', 'FR' => 'France', 'GA' => 'Gabon',
            'GM' => 'Gambia', 'GE' => 'Georgia', 'DE' => 'Germany', 'GH' => 'Ghana',
            'GR' => 'Greece', 'GT' => 'Guatemala', 'GN' => 'Guinea', 'GW' => 'Guinea-Bissau',
            'GY' => 'Guyana', 'HT' => 'Haiti', 'HN' => 'Honduras', 'HK' => 'Hong Kong',
            'HU' => 'Hungary', 'IS' => 'Iceland', 'IN' => 'India', 'ID' => 'Indonesia',
            'IR' => 'Iran', 'IQ' => 'Iraq', 'IE' => 'Ireland', 'IL' => 'Israel',
            'IT' => 'Italy', 'JM' => 'Jamaica', 'JP' => 'Japan', 'JO' => 'Jordan',
            'KZ' => 'Kazakhstan', 'KE' => 'Kenya', 'KI' => 'Kiribati', 'KP' => 'North Korea',
            'KR' => 'South Korea', 'XK' => 'Kosovo', 'KW' => 'Kuwait', 'KG' => 'Kyrgyzstan',
            'LA' => 'Laos', 'LV' => 'Latvia', 'LB' => 'Lebanon', 'LS' => 'Lesotho',
            'LR' => 'Liberia', 'LY' => 'Libya', 'LI' => 'Liechtenstein', 'LT' => 'Lithuania',
            'LU' => 'Luxembourg', 'MO' => 'Macau', 'MG' => 'Madagascar', 'MW' => 'Malawi',
            'MY' => 'Malaysia', 'MV' => 'Maldives', 'ML' => 'Mali', 'MT' => 'Malta',
            'MH' => 'Marshall Islands', 'MR' => 'Mauritania', 'MU' => 'Mauritius',
            'MX' => 'Mexico', 'FM' => 'Micronesia', 'MD' => 'Moldova', 'MC' => 'Monaco',
            'MN' => 'Mongolia', 'ME' => 'Montenegro', 'MA' => 'Morocco', 'MZ' => 'Mozambique',
            'NA' => 'Namibia', 'NR' => 'Nauru', 'NP' => 'Nepal', 'NL' => 'Netherlands',
            'NZ' => 'New Zealand', 'NI' => 'Nicaragua', 'NE' => 'Niger', 'NG' => 'Nigeria',
            'MK' => 'North Macedonia', 'NO' => 'Norway', 'OM' => 'Oman', 'PK' => 'Pakistan',
            'PW' => 'Palau', 'PS' => 'Palestine', 'PA' => 'Panama', 'PG' => 'Papua New Guinea',
            'PY' => 'Paraguay', 'PE' => 'Peru', 'PH' => 'Philippines', 'PL' => 'Poland',
            'PT' => 'Portugal', 'PR' => 'Puerto Rico', 'QA' => 'Qatar', 'RO' => 'Romania',
            'RU' => 'Russia', 'RW' => 'Rwanda', 'KN' => 'Saint Kitts and Nevis',
            'LC' => 'Saint Lucia', 'VC' => 'Saint Vincent and the Grenadines', 'WS' => 'Samoa',
            'SM' => 'San Marino', 'ST' => 'São Tomé and Príncipe', 'SA' => 'Saudi Arabia',
            'SN' => 'Senegal', 'RS' => 'Serbia', 'SC' => 'Seychelles', 'SL' => 'Sierra Leone',
            'SG' => 'Singapore', 'SK' => 'Slovakia', 'SI' => 'Slovenia', 'SB' => 'Solomon Islands',
            'SO' => 'Somalia', 'ZA' => 'South Africa', 'SS' => 'South Sudan', 'ES' => 'Spain',
            'LK' => 'Sri Lanka', 'SD' => 'Sudan', 'SR' => 'Suriname', 'CH' => 'Switzerland',
            'SE' => 'Sweden', 'SY' => 'Syria', 'TW' => 'Taiwan', 'TJ' => 'Tajikistan',
            'TZ' => 'Tanzania', 'TH' => 'Thailand', 'TL' => 'Timor-Leste', 'TG' => 'Togo',
            'TO' => 'Tonga', 'TT' => 'Trinidad and Tobago', 'TN' => 'Tunisia', 'TR' => 'Turkey',
            'TM' => 'Turkmenistan', 'TV' => 'Tuvalu', 'UG' => 'Uganda', 'UA' => 'Ukraine',
            'AE' => 'United Arab Emirates', 'GB' => 'United Kingdom', 'US' => 'United States',
            'UY' => 'Uruguay', 'UZ' => 'Uzbekistan', 'VU' => 'Vanuatu', 'VA' => 'Vatican City',
            'VE' => 'Venezuela', 'VN' => 'Vietnam', 'YE' => 'Yemen', 'ZM' => 'Zambia', 'ZW' => 'Zimbabwe',
        ];
        asort($list, SORT_FLAG_CASE | SORT_STRING);
        return ['' => __('— Select country —', 'chess-podium')] + $list;
    }

    public static function fide_to_iso(string $fideCode): ?string
    {
        $key = strtoupper(substr($fideCode, 0, 3));
        return self::FIDE_TO_ISO[$key] ?? null;
    }

    /** Convert ISO 2-letter code to flag emoji (Unicode regional indicators) */
    public static function flag_emoji(string $iso): string
    {
        $iso = strtoupper(substr($iso, 0, 2));
        if (strlen($iso) !== 2 || $iso[0] < 'A' || $iso[0] > 'Z' || $iso[1] < 'A' || $iso[1] > 'Z') {
            return '';
        }
        $flag = '';
        for ($i = 0; $i < 2; $i++) {
            $flag .= mb_chr(0x1F1E6 + ord($iso[$i]) - ord('A'));
        }
        return $flag;
    }

    /** Render flag with optional title for accessibility (emoji - works in admin) */
    public static function render_flag(string $iso, string $title = ''): string
    {
        $emoji = self::flag_emoji($iso);
        if ($emoji === '') {
            return '';
        }
        $title = $title ?: $iso;
        return '<span class="cp-flag" title="' . esc_attr($title) . '" role="img" aria-label="' . esc_attr($title) . '">' . $emoji . '</span>';
    }

    /** Render flag as image (uses local assets - no remote CDN). Fallback to emoji if file missing. */
    public static function render_flag_img(string $iso, string $title = '', int $width = 20): string
    {
        $iso = strtoupper(substr($iso, 0, 2));
        if (strlen($iso) !== 2 || !ctype_alpha($iso)) {
            return '';
        }
        $isoLower = strtolower($iso);
        $title = $title ?: $iso;

        $basePath = apply_filters('chess_podium_flag_img_base_path', null);
        $pluginDir = defined('CHESS_PODIUM_PLUGIN_DIR') ? CHESS_PODIUM_PLUGIN_DIR : '';
        $flagsPath = $pluginDir . 'assets/img/flags/' . $isoLower . '.png';

        if ($basePath !== null && $basePath !== '') {
            // Export context: relative path only (no scheme/host). Plugin must have file so export copies it.
            if ($pluginDir === '' || !file_exists($flagsPath)) {
                return self::render_flag($iso, $title);
            }
            // Relative path only; use esc_attr so it is not turned into an absolute URL (esc_url can cause mixed content / wrong host).
            $url = $basePath . '/' . $isoLower . '.png';
            $height = (int) round($width * 0.75);
            return '<img src="' . esc_attr($url) . '" alt="' . esc_attr($title) . '" title="' . esc_attr($title) . '" class="cp-flag-img" width="' . $width . '" height="' . $height . '" loading="lazy" style="vertical-align:middle;">';
        }

        if ($pluginDir === '' || !file_exists($flagsPath)) {
            return self::render_flag($iso, $title);
        }
        $url = plugins_url('assets/img/flags/' . $isoLower . '.png', defined('CHESS_PODIUM_PLUGIN_FILE') ? CHESS_PODIUM_PLUGIN_FILE : __FILE__);
        $height = (int) round($width * 0.75);
        return '<img src="' . esc_url($url) . '" alt="' . esc_attr($title) . '" title="' . esc_attr($title) . '" class="cp-flag-img" width="' . $width . '" height="' . $height . '" loading="lazy" style="vertical-align:middle;">';
    }
}
