<?php

declare(strict_types=1);

if (! function_exists('admin_normalize_alert_plain')) {
    /**
     * Plain text for matching flash messages to language lines.
     */
    function admin_normalize_alert_plain(?string $text): string
    {
        if ($text === null || $text === '') {
            return '';
        }
        $plain = strip_tags($text);
        $plain = html_entity_decode($plain, ENT_QUOTES | ENT_HTML5, 'UTF-8');

        return trim(preg_replace('/\s+/u', ' ', $plain));
    }
}

if (! function_exists('admin_normalize_alert_key')) {
    function admin_normalize_alert_key(?string $text): string
    {
        $plain = admin_normalize_alert_plain($text);

        return mb_strtolower($plain, 'UTF-8');
    }
}

if (! function_exists('admin_build_flash_bilingual_map')) {
    /**
     * Map normalized message (lowercase plain) => ['en' => string, 'ar' => string|null].
     *
     * @return array<string, array{en: string, ar: ?string}>
     */
    function admin_build_flash_bilingual_map(): array
    {
        static $map = null;
        if ($map !== null) {
            return $map;
        }

        $map = [];

        $defaultPath = APPPATH . 'Language/Default/Localize.php';
        $enPath      = APPPATH . 'Language/en/Localize.php';
        $arPath      = APPPATH . 'Language/ar/Localize.php';

        $default = is_file($defaultPath) ? (include $defaultPath) : [];
        $enOnly  = is_file($enPath) ? (include $enPath) : [];
        $arOnly  = is_file($arPath) ? (include $arPath) : [];

        if (! is_array($default)) {
            $default = [];
        }
        if (! is_array($enOnly)) {
            $enOnly = [];
        }
        if (! is_array($arOnly)) {
            $arOnly = [];
        }

        $enMerged = array_merge($default, $enOnly);
        $allKeys  = array_unique(array_merge(array_keys($enMerged), array_keys($arOnly)));

        foreach ($allKeys as $key) {
            $en = isset($enMerged[$key]) ? (string) $enMerged[$key] : '';
            $ar = isset($arOnly[$key]) ? (string) $arOnly[$key] : '';

            if ($en === '' && $ar === '') {
                continue;
            }

            $primaryEn = $en !== '' ? $en : $ar;
            $primaryAr = $ar !== '' ? $ar : null;

            if ($primaryAr !== null && trim($primaryEn) === trim($primaryAr)) {
                $primaryAr = null;
            }

            if ($en !== '') {
                $k = admin_normalize_alert_key($en);
                if ($k !== '') {
                    $map[$k] = ['en' => $en, 'ar' => $primaryAr];
                }
            }
            if ($ar !== '' && admin_normalize_alert_key($ar) !== admin_normalize_alert_key($en)) {
                $k = admin_normalize_alert_key($ar);
                if ($k !== '') {
                    $map[$k] = ['en' => $primaryEn, 'ar' => $primaryAr];
                }
            }
        }

        $manualPath = APPPATH . 'Config/Admin_flash_en_ar.php';
        if (is_file($manualPath)) {
            $manual = include $manualPath;
            if (is_array($manual)) {
                foreach ($manual as $normKey => $row) {
                    if (! is_string($normKey) || $normKey === '') {
                        continue;
                    }
                    $nk = admin_normalize_alert_key($normKey);
                    if ($nk === '') {
                        continue;
                    }
                    if (is_array($row) && isset($row['en'], $row['ar'])) {
                        $map[$nk] = ['en' => (string) $row['en'], 'ar' => (string) $row['ar']];
                    }
                }
            }
        }

        return $map;
    }
}

if (! function_exists('admin_resolve_flash_bilingual_pair')) {
    /**
     * @return array{en: string, ar: ?string}|null
     */
    function admin_resolve_flash_bilingual_pair(string $message): ?array
    {
        $norm = admin_normalize_alert_key($message);
        if ($norm === '') {
            return null;
        }

        $map = admin_build_flash_bilingual_map();

        return $map[$norm] ?? null;
    }
}

if (! function_exists('admin_alert_bilingual_markup')) {
    /**
     * HTML for one or two lines (English + Arabic), escaped.
     */
    function admin_alert_bilingual_markup(string $enText, string $arText): string
    {
        $enText = trim($enText);
        $arText = trim($arText);
        if ($arText === '' || $enText === $arText) {
            return '<div class="admin-alert-line admin-alert-line--plain" dir="ltr" lang="en">' . esc($enText) . '</div>';
        }

        return '<div class="admin-alert-bilingual-stack">'
            . '<div class="admin-alert-line admin-alert-line--en" dir="ltr" lang="en">' . esc($enText) . '</div>'
            . '<div class="admin-alert-line admin-alert-line--ar" dir="rtl" lang="ar">' . esc($arText) . '</div>'
            . '</div>';
    }
}

if (! function_exists('admin_apply_lang_placeholders')) {
    /**
     * Replace {key} placeholders in language strings (avoids ICU/MessageFormatter quirks).
     */
    function admin_apply_lang_placeholders(string $template, array $args = []): string
    {
        if ($args === []) {
            return $template;
        }
        foreach ($args as $key => $value) {
            $template = str_replace('{' . $key . '}', (string) $value, $template);
        }

        return $template;
    }
}

if (! function_exists('admin_bilingual_lang_strings')) {
    /**
     * Same language line in English and Arabic locales (for APIs, emails, etc.).
     *
     * @return array{en: string, ar: string}
     */
    function admin_bilingual_lang_strings(string $line, array $args = []): array
    {
        $language = service('language');
        $saved     = $language->getLocale();
        $language->setLocale('en');
        $rawEn = (string) lang($line, []);
        $language->setLocale('ar');
        $rawAr = (string) lang($line, []);
        $language->setLocale($saved);

        return [
            'en' => admin_apply_lang_placeholders($rawEn, $args),
            'ar' => admin_apply_lang_placeholders($rawAr, $args),
        ];
    }
}

if (! function_exists('admin_bilingual_lang')) {
    /**
     * Bilingual HTML for a Localize key (admin flash / alerts with placeholders).
     */
    function admin_bilingual_lang(string $line, array $args = []): string
    {
        $strings = admin_bilingual_lang_strings($line, $args);

        return admin_alert_bilingual_markup($strings['en'], $strings['ar']);
    }
}

if (! function_exists('admin_flash_bilingual_html')) {
    /**
     * Render admin flash content: English + Arabic when both are known; otherwise a single safe block.
     */
    function admin_flash_bilingual_html(string $message): string
    {
        if (trim($message) === '') {
            return '';
        }

        // Pre-rendered markup from admin_bilingual_lang() / admin_alert_bilingual_markup()
        if (str_contains($message, 'admin-alert-line')) {
            return $message;
        }

        if (preg_match('/<\s*[a-z!]/i', $message)) {
            return '<div class="admin-alert-html">' . $message . '</div>';
        }

        $pair = admin_resolve_flash_bilingual_pair($message);
        if ($pair === null) {
            return '<div class="admin-alert-line admin-alert-line--plain" dir="auto">' . esc($message) . '</div>';
        }

        $en = $pair['en'];
        $ar = $pair['ar'] ?? '';

        return admin_alert_bilingual_markup($en, (string) $ar);
    }
}
