<?php

namespace App\Helpers;

class BladeTranslationHelper
{
    private static $translations = [];
    private static $currentLanguage = 'en';
    private static $loaded = false;

    /**
     * Initialize the helper with user language
     */
    public static function init($language = 'en')
    {
        self::$currentLanguage = $language;
        self::loadTranslations($language);
    }

    /**
     * Load translations for the specified language
     */
    private static function loadTranslations($language)
    {
        if (isset(self::$translations[$language])) {
            return;
        }

        // Try modular system first
        $modularPath = public_path("assets/languages/{$language}");
        if (is_dir($modularPath) && file_exists("{$modularPath}/index.json")) {
            self::loadModularTranslations($language, $modularPath);
        } else {
            // Fallback to monolithic file
            self::loadMonolithicTranslations($language);
        }

        self::$loaded = true;
    }

    /**
     * Load modular translations
     */
    private static function loadModularTranslations($language, $modularPath)
    {
        $indexFile = "{$modularPath}/index.json";
        if (!file_exists($indexFile)) {
            return;
        }

        $index = json_decode(file_get_contents($indexFile), true);
        if (!$index || !isset($index['files'])) {
            return;
        }

        $translations = [];
        foreach ($index['files'] as $file) {
            $filePath = "{$modularPath}/{$file}";
            if (file_exists($filePath)) {
                $sectionData = json_decode(file_get_contents($filePath), true);
                if ($sectionData) {
                    $translations = array_merge_recursive($translations, $sectionData);
                }
            }
        }

        self::$translations[$language] = $translations;
    }

    /**
     * Load monolithic translations
     */
    private static function loadMonolithicTranslations($language)
    {
        $filePath = public_path("assets/languages/{$language}.json");
        if (file_exists($filePath)) {
            $data = json_decode(file_get_contents($filePath), true);
            if ($data) {
                self::$translations[$language] = $data;
            }
        }
    }

    /**
     * Get translation by key
     */
    public static function get($key, $params = [], $language = null)
    {
        $language = $language ?: self::$currentLanguage;

        if (!isset(self::$translations[$language])) {
            self::loadTranslations($language);
        }

        $value = self::getNestedValue(self::$translations[$language] ?? [], $key);

        // Fallback to English if translation not found
        if (!$value && $language !== 'en') {
            if (!isset(self::$translations['en'])) {
                self::loadTranslations('en');
            }
            $value = self::getNestedValue(self::$translations['en'] ?? [], $key);
        }

        if (!$value) {
            return $key; // Return key if no translation found
        }

        // Replace parameters
        foreach ($params as $param => $replacement) {
            $value = str_replace("[{$param}]", $replacement, $value);
        }

        return $value;
    }

    /**
     * Get nested value using dot notation
     */
    private static function getNestedValue($array, $key)
    {
        $keys = explode('.', $key);
        $current = $array;

        foreach ($keys as $k) {
            if (!is_array($current) || !array_key_exists($k, $current)) {
                return null;
            }
            $current = $current[$k];
        }

        return is_string($current) ? $current : null;
    }

    /**
     * Generate JavaScript object for client-side use
     */
    public static function generateJavaScriptPreload($language = null, $sections = [])
    {
        $language = $language ?: self::$currentLanguage;

        if (!isset(self::$translations[$language])) {
            self::loadTranslations($language);
        }

        $translations = self::$translations[$language] ?? [];

        // If specific sections requested, filter to those sections
        if (!empty($sections)) {
            $filteredTranslations = [];
            foreach ($sections as $section) {
                if (isset($translations[$section])) {
                    $filteredTranslations[$section] = $translations[$section];
                }
            }
            $translations = $filteredTranslations;
        }

        return json_encode($translations, JSON_UNESCAPED_UNICODE);
    }

    /**
     * Generate critical CSS for preventing flash
     */
    public static function generateCriticalCSS()
    {
        return '
        <style id="critical-translation-css">
            [data-translate]:not(.translated) {
                opacity: 0;
                transition: opacity 0.3s ease-in-out;
            }

            [data-translate].translated {
                opacity: 1;
            }

            .language-preload [data-translate] {
                visibility: hidden;
            }

            .language-ready [data-translate] {
                visibility: visible;
                opacity: 1;
            }

            body.language-loading {
                overflow: hidden;
            }

            body.language-ready {
                overflow: auto;
            }
        </style>';
    }

    /**
     * Get all available languages
     */
    public static function getAvailableLanguages()
    {
        return [
            'en' => ['name' => 'English', 'flag' => '🇺🇸', 'dir' => 'ltr'],
            'ar' => ['name' => 'العربية', 'flag' => '🇸🇦', 'dir' => 'rtl'],
            'fr' => ['name' => 'Français', 'flag' => '🇫🇷', 'dir' => 'ltr'],
            'de' => ['name' => 'Deutsch', 'flag' => '🇩🇪', 'dir' => 'ltr'],
            'es' => ['name' => 'Español', 'flag' => '🇪🇸', 'dir' => 'ltr'],
            'ru' => ['name' => 'Русский', 'flag' => '🇷🇺', 'dir' => 'ltr'],
            'zh-CN' => ['name' => '简体中文', 'flag' => '🇨🇳', 'dir' => 'ltr'],
        ];
    }

    /**
     * Get current language metadata
     */
    public static function getCurrentLanguageMeta()
    {
        $languages = self::getAvailableLanguages();
        return $languages[self::$currentLanguage] ?? $languages['en'];
    }

    /**
     * Generate language configuration for JavaScript
     */
    public static function generateLanguageConfig($user = null)
    {
        $isAuthenticated = $user !== null;
        $browserLanguage = request()->header('Accept-Language');
        $serverLanguage = $user ? ($user->language ?? 'en') : 'en';

        // Parse browser language
        if ($browserLanguage) {
            $browserLanguage = strtolower(substr($browserLanguage, 0, 2));
            if (!in_array($browserLanguage, array_keys(self::getAvailableLanguages()))) {
                $browserLanguage = 'en';
            }
        } else {
            $browserLanguage = 'en';
        }

        return [
            'isAuthenticated' => $isAuthenticated,
            'userId' => $user?->id,
            'currentLanguage' => $serverLanguage,
            'browserLanguage' => $browserLanguage,
            'availableLanguages' => self::getAvailableLanguages(),
            'csrfToken' => csrf_token(),
        ];
    }
}
