import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";

export const LANGUAGES = [
  { code: "en", label: "English", flag: "🇬🇧", dir: "ltr" as const },
  { code: "ar", label: "العربية", flag: "🇸🇦", dir: "rtl" as const },
  { code: "fr", label: "Français", flag: "🇫🇷", dir: "ltr" as const },
  { code: "es", label: "Español", flag: "🇪🇸", dir: "ltr" as const },
  { code: "ro", label: "Română", flag: "🇷🇴", dir: "ltr" as const },
  { code: "de", label: "Deutsch", flag: "🇩🇪", dir: "ltr" as const },
  { code: "ru", label: "Русский", flag: "🇷🇺", dir: "ltr" as const },
  { code: "ko", label: "한국어", flag: "🇰🇷", dir: "ltr" as const },
  { code: "fil", label: "Filipino", flag: "🇵🇭", dir: "ltr" as const },
] as const;

export type LangCode = (typeof LANGUAGES)[number]["code"];

// Master English resource — single source of truth for every string.
const en = {
  translation: {
    common: {
      cancel: "Cancel",
      save: "Save",
      saving: "Saving...",
      delete: "Delete",
      edit: "Edit",
      close: "Close",
      loading: "Loading...",
      connect: "Connect",
      connecting: "Connecting...",
      refresh: "Refresh",
      back: "Back",
      logout: "Logout",
      search: "Search",
      all: "All",
      yes: "Yes",
      no: "No",
      timeshift: "Timeshift",
      active: "Active",
      setActive: "Set Active",
      test: "Test",
      username: "Username",
      password: "Password",
      add: "Add",
      create: "Create",
      update: "Update",
      open: "Open",
      retry: "Retry",
    },
    welcome: {
      title: "NADIPLAYER",
      chooseHowToContinue: "Choose how to continue",
      guest: "GUEST",
      guestHint: "Enter with your own Xtream server — manage everything locally.",
      enter: "Enter",
      login: "LOGIN",
      loginHint:
        "Subscribers: sign in with the username & password provided by your admin.",
      signIn: "Sign In",
      premiumTag: "Premium IPTV Experience",
      language: "Language",
    },
    menu: {
      title: "Menu",
      home: "Home",
      liveTv: "Live TV",
      movies: "Movies",
      series: "Series",
      account: "Account",
      settings: "Settings",
      open: "Open menu",
      close: "Close menu",
    },
    login: {
      subtitle: "Subscriber Sign-In",
      username: "Username",
      password: "Password",
      submit: "Sign In",
      submitting: "Signing in...",
      contactAdmin: "No account? Contact your NADIPLAYER administrator to get credentials.",
      back: "Back",
    },
    home: {
      logout: "Logout",
      profile: "Profile",
      guestMode: "Guest Mode",
      connected: "Connected.",
      awaiting: "Awaiting server sync.",
      waiting: "Waiting to connect.",
      subscriber: "Subscriber",
      expires: "Expires",
      noExpiry: "No expiry set",
      daysRemaining_one: "{{count}} day remaining",
      daysRemaining_other: "{{count}} days remaining",
      expired: "EXPIRED",
      timeshift: "Timeshift",
      categories: {
        liveTv: "Live TV",
        movies: "Movies",
        series: "Series",
        worldCup: "World Cup",
        liveTvCount: "+5000 Channels",
        moviesCount: "+1200 Movies",
        seriesCount: "+500 Series",
        worldCupCount: "FIFA 2026 · Live",
      },
      infoBar:
        "LIVE: +5000 Channels. MOVIES: +1200 Titles. SERIES: +500 Series.",
    },
    expired: {
      title: "SUBSCRIPTION EXPIRED",
      hi: "Hi",
      message:
        "Your NADIPLAYER subscription has ended. To continue watching, please contact us on WhatsApp to renew.",
      contactWhatsapp: "Customer Support",
      signOut: "Sign Out",
      whatsappPrefill:
        "Hi, my NADIPLAYER subscription ({{username}}) has expired. I'd like to renew.",
    },
    splash: {
      tagline: "Tune In to the Universe",
      premiumTag: "Premium IPTV Experience",
    },
    firstRun: {
      title: "Choose your language",
      subtitle: "Use ← → to switch flags, then press Continue",
      continue: "Continue",
      hint: "You can change this later from Settings",
    },
    update: {
      titleNormal: "New update available",
      titleForced: "Update required",
      forcedNotice: "You must install the latest version to keep using the app.",
      adminPreview:
        "Admin preview. This popup is forced for normal users (installed v{{installed}} < min v{{min}}). You can dismiss it freely — admins are never locked out.",
      loginPreview:
        "Login is always reachable so admins can update the app version. Tap \"Later\" to continue to the login form.",
      needPermission:
        "Please enable \"Allow install from this source\" for Nadiplayer in the screen we just opened, then come back and tap the button again.",
      installerOpened: "Installer opened. Follow the on-screen prompt to install.",
      whatsNew: "What's new",
      noUrl: "No download link configured. Contact the admin.",
      downloadingPercent: "Downloading {{percent}}%…",
      downloading: "Downloading…",
      openingInstaller: "Opening installer…",
      allowInstallRetry: "Allow install — try again",
      installerLaunched: "Installer launched",
      retry: "Retry update",
      updateNow: "Update now",
      downloadUpdate: "Download update",
      openInPlayStore: "Open in Play Store",
      later: "Later",
      closeAria: "Close update notice",
    },
    pageLayout: {
      weatherCity: "Los Angeles 24°",
    },
    notFound: {
      title: "404",
      message: "Oops! Page not found",
      goHome: "Return to Home",
    },
    account: {
      title: "ACCOUNT",
      profilesCount_one: "{{count}} profile",
      profilesCount_other: "{{count}} profiles",
      addServer: "Add Server",
      devicePairing: "Device Pairing",
      devicePairingDesc:
        "Link a Smart TV or streaming device to your IPTV account using a 6-digit PIN — no typing long URLs on your remote.",
      imOnDevice: "I'm on the Device",
      iHavePin: "I have a PIN",
      playbackMode: "Playback Mode",
      playbackModeDesc:
        "Where streams open when you click a channel. External opens the stream directly in your chosen player app — each viewer streams from their own IP, so providers can't ban a shared app IP.",
      internal: "Internal (built-in)",
      external: "External",
      externalOn: "External player mode on",
      internalOn: "Internal player mode on",
      externalPlayer: "External Player",
      externalPlayerDesc:
        "The app that opens when you click a channel in External mode. VidoPlay is the default — install it once, then enjoy one-tap launch on every channel.",
      default: "DEFAULT",
      install: "Install",
      externalPlayerSet: "External player → {{name}}",
      playerIdentity: "Player Identity",
      playerIdentityDesc:
        "The User-Agent header sent with stream & API requests. Choose the one your IPTV provider expects.",
      sending: "Sending",
      userAgentSet: "User-Agent → {{name}}",
      noProfiles: "No profiles yet",
      noProfilesDesc: "Add an Xtream Codes server to get started.",
      profileName: "Profile Name",
      serverUrl: "Server URL",
      user: "user",
      profileUpdated: "Profile updated",
      playlistReloaded: "Playlist reloaded",
      profileRemoved: "Profile removed",
      confirmDelete: "Delete this profile?",
      connectedSuccess: "{{name}} connected successfully",
      connectFailed: "{{name}}: {{error}}",
      reloadPlaylist: "Reload Playlist",
    },
    liveTV: {
      title: "LIVE TV",
      searchPlaceholder: "Search channels…",
      noActiveServer: "No active server.",
      addProfile: "Add a profile",
      contactAdmin: "Contact your admin",
      favs: "Favs",
      listView: "List view",
      gridView: "Grid view",
      selectChannel: "Select a channel",
      failedLoad: "Failed to load. Check credentials.",
      noChannels: "No channels found.",
      nowPrefix: "Now: {{title}}",
      reopen: "Re-open",
      channels_one: "{{count}} channel",
      channels_other: "{{count}} channels",
      epgFor: "EPG · {{name}}",
      openingInApp: "Opening {{channel}} in {{app}}",
      sentToApp: "Sent to {{app}}. Install the APK for reliable auto-launch.",
      couldntOpen:
        "Couldn't open {{app}}. Install it from Account → External Player.",
    },
    movies: {
      title: "MOVIES",
      searchPlaceholder: "Search movies...",
      noActiveServer: "No active server.",
      addProfile: "Add a profile",
      contactAdmin: "Contact your admin",
      failedLoad: "Failed to load movies.",
    },
    series: {
      title: "SERIES",
      searchPlaceholder: "Search series...",
      noActiveServer: "No active server.",
      addProfile: "Add a profile",
      contactAdmin: "Contact your admin",
      failedLoad: "Failed to load series.",
      season: "Season {{n}}",
      episodePrefix: "E{{n}}",
    },
    addServer: {
      title: "ADD PLAYLIST",
      xtreamTab: "Xtream Codes",
      m3uTab: "M3U URL",
      advanced: "Advanced",
      shared: "Shared",
      ownServer: "Own server",
      sharedHint:
        "Uses the Xtream server configured by the admin in Global Settings.",
      ownHint: "Enter your personal Xtream server credentials.",
      loadingShared: "Loading shared server details...",
      sharedNotConfigured:
        "The admin hasn't configured a shared server yet. Switch to Own server or ask your admin to set it up.",
      autoFilled: "Shared server · Auto-filled from Global Settings",
      profileNamePlaceholder: "Profile Name (e.g., Family TV)",
      serverUrlPlaceholder: "Server URL (http://...)",
      usernamePlaceholder: "Username",
      passwordPlaceholder: "Password",
      m3uPlaceholder: "https://example.com/playlist.m3u",
      hintShared: "Pick Shared to reuse the NADIPLAYER global server.",
      hintOwn: "Enter your Xtream Codes credentials to load TV, Movies & Series.",
      hintM3u: "Paste any M3U / M3U8 playlist URL to import.",
    },
    admin: {
      title: "NADIPLAYER ADMIN",
      subtitle: "Subscriber Control Panel",
      logout: "Logout",
      settingsHeading: "GLOBAL SETTINGS",
      whatsapp: "WhatsApp (e.g. +15551234567)",
      sharedServer: "Shared Xtream Server",
      sharedUsername: "Shared Xtream Username",
      sharedPassword: "Shared Xtream Password",
      saveSettings: "Save Settings",
      settingsSaved: "Settings saved",
      createHeading: "CREATE SUBSCRIBER",
      usernameLabel: "Username",
      passwordLabel: "Password",
      daysLabel: "Days",
      xtreamMode: "Xtream Mode",
      modeShared: "Shared (global)",
      modeOwn: "Own server (per-user)",
      serverUrl: "Xtream Server URL",
      xtreamUsername: "Xtream Username",
      xtreamPassword: "Xtream Password",
      createUser: "Create User",
      creating: "Creating...",
      userCreated: "User created",
      subscribersHeading: "SUBSCRIBERS ({{count}})",
      noSubscribers: "No subscribers yet.",
      noExpiry: "no expiry",
      daysLeft_one: "{{count}} day left",
      daysLeft_other: "{{count}} days left",
      expired: "EXPIRED",
      advanced: "Advanced",
      server: "Server",
      xtUser: "Xt. User",
      xtPass: "Xt. Pass",
      saveXtream: "Save Xtream",
      xtreamSaved: "Xtream saved",
      newPassword: "New password",
      updatePassword: "Update password",
      passwordUpdated: "Password updated",
      addDays: "+{{n}}d",
      subDays: "-{{n}}d",
      dayAdded_one: "Added {{count}} day",
      dayAdded_other: "Added {{count}} days",
      dayRemoved_one: "Removed {{count}} day",
      dayRemoved_other: "Removed {{count}} days",
      deleteUser: "Delete",
      userDeleted: "User deleted",
      confirmDeleteUser: 'Delete user "{{username}}"?',
      loadFailed: "Failed to load",
      opFailed: "Failed",
      adsToggleLabel: "Ads",
      adsToggleOn: "Enabled — this user sees ads",
      adsToggleOff: "Disabled — this user is ad-free",
      adsForcedOn: "Ads forced ON for this user",
      adsForcedOff: "Ads disabled for this user",
    },
    premium: {
      goldBadge: "Premium Account",
      adFreeTag: "Ad-free",
      daysRemaining_one: "{{count}} day remaining",
      daysRemaining_other: "{{count}} days remaining",
      expiresOn: "Expires on",
      expiredTitle: "Subscription expired",
      renewNow: "Renew now",
      haveSubscription: "I already have a subscription · Sign in",
      upgradePitch:
        "Upgrade to a Premium Account to enjoy an ad-free experience and exclusive features.",
      adminBadge: "Administrator account",
      adminHint: "All features unlocked, no ads.",
      premiumSubscriber: "Premium Subscriber",
      welcomeMessage:
        "You are using the Premium Version! Enjoy an ad-free experience, advanced hardware acceleration for 4K support, and priority technical assistance. (Note: NadiPlayer is a media player only; no content or playlists are provided).",
    },
    noServer: {
      title: "Upgrade to Premium",
      titleSubscriber: "Add a profile",
      alreadySubscribed: "Already have a subscription?",
      upgradeNow: "Upgrade Now",
      signIn: "Sign In",
      or: "or",
      addOwnProfile: "Add a profile",
      addOwnHint: "Use your own Xtream / M3U / Stalker credentials.",
      subscriberHint:
        "Connect your own Xtream Codes, M3U playlist, or Stalker portal to start watching.",
    },
    upgrade: {
      tag: "Premium Activation",
      title: "UPGRADE TO PREMIUM",
      intro:
        "Premium unlocks an ad-free experience and exclusive features. Activation is handled outside the app.",
      howToTitle: "How to upgrade",
      instructions: "Visit",
      toActivate: "to activate.",
      fromBrowser: "from your browser.",
      scanHint:
        "Or scan the QR code with your phone — it opens the activation page directly.",
      deviceInfo: "Your device identifiers",
      macAddress: "MAC Address",
      deviceId: "Device ID",
      devicePin: "Device PIN",
      pairingHint:
        "Use your MAC Address and Device PIN on the website to pair this device with your subscription.",
      deviceHint:
        "Provide these identifiers on the website if requested — they let us link your premium activation to this exact device.",
      recheck: "Re-check my subscription",
      compliance: "No in-app purchase · Activation via website",
    },
    trial: {
      expiredTitle: "TRIAL EXPIRED",
      expiredDescription:
        "Your 30-day free trial has expired. Upgrade to a 1-year premium account to continue using NadiPlayer without ads.",
      daysUsed: "{{used}} days used · started {{date}}",
      loginAlready: "I already have a subscription · Log in",
      upgradeInfo: "Upgrade info & device ID",
      visitWebsiteHint:
        "To upgrade to Premium and remove ads, please visit our website",
      fromBrowser: "from your browser.",
      recheck: "Re-check my subscription",
      footnote: "No in-app purchase · Activation via website",
    },
  },
} as const;

// Arabic — complete translation.
const ar = {
  translation: {
    common: {
      cancel: "إلغاء",
      save: "حفظ",
      saving: "جاري الحفظ...",
      delete: "حذف",
      edit: "تعديل",
      close: "إغلاق",
      loading: "جاري التحميل...",
      connect: "اتصال",
      connecting: "جاري الاتصال...",
      refresh: "تحديث",
      back: "رجوع",
      logout: "تسجيل الخروج",
      search: "بحث",
      all: "الكل",
      yes: "نعم",
      no: "لا",
      timeshift: "تقديم وتأخير",
      active: "نشط",
      setActive: "تفعيل",
      test: "اختبار",
      username: "اسم المستخدم",
      password: "كلمة المرور",
      add: "إضافة",
      create: "إنشاء",
      update: "تحديث",
      open: "فتح",
      retry: "إعادة المحاولة",
    },
    welcome: {
      title: "NADIPLAYER",
      chooseHowToContinue: "اختر كيفية المتابعة",
      guest: "ضيف",
      guestHint: "ادخل بسيرفر Xtream الخاص بك — تحكم بكل شيء محليا.",
      enter: "دخول",
      login: "تسجيل الدخول",
      loginHint:
        "للمشتركين: سجل الدخول باسم المستخدم وكلمة المرور من المسؤول.",
      signIn: "تسجيل الدخول",
      premiumTag: "تجربة IPTV مميزة",
      language: "اللغة",
    },
    menu: {
      title: "القائمة",
      home: "الرئيسية",
      liveTv: "بث مباشر",
      movies: "أفلام",
      series: "مسلسلات",
      account: "الحساب",
      settings: "الإعدادات",
      open: "فتح القائمة",
      close: "إغلاق القائمة",
    },
    login: {
      subtitle: "تسجيل دخول المشترك",
      username: "اسم المستخدم",
      password: "كلمة المرور",
      submit: "تسجيل الدخول",
      submitting: "جاري تسجيل الدخول...",
      contactAdmin:
        "لا يوجد حساب؟ تواصل مع مسؤول NADIPLAYER للحصول على بيانات الاعتماد.",
      back: "رجوع",
    },
    home: {
      logout: "تسجيل الخروج",
      profile: "الملف",
      guestMode: "وضع الضيف",
      connected: "متصل.",
      awaiting: "بانتظار مزامنة السيرفر.",
      waiting: "بانتظار الاتصال.",
      subscriber: "مشترك",
      expires: "ينتهي في",
      noExpiry: "بدون تاريخ انتهاء",
      daysRemaining_zero: "لا أيام متبقية",
      daysRemaining_one: "متبقي يوم واحد",
      daysRemaining_two: "متبقي يومان",
      daysRemaining_few: "متبقي {{count}} أيام",
      daysRemaining_many: "متبقي {{count}} يوما",
      daysRemaining_other: "متبقي {{count}} يوم",
      expired: "منتهي",
      timeshift: "تقديم وتأخير",
      categories: {
        liveTv: "بث مباشر",
        movies: "أفلام",
        series: "مسلسلات",
        liveTvCount: "+5000 قناة",
        moviesCount: "+1200 فيلم",
        seriesCount: "+500 مسلسل",
      },
      infoBar: "مباشر: +5000 قناة. أفلام: +1200 عنوان. مسلسلات: +500 مسلسل.",
    },
    expired: {
      title: "انتهى الاشتراك",
      hi: "مرحبا",
      message:
        "لقد انتهى اشتراك NADIPLAYER الخاص بك. لمتابعة المشاهدة، يرجى التواصل معنا عبر واتساب لتجديد الاشتراك.",
      contactWhatsapp: "دعم العملاء",
      signOut: "تسجيل الخروج",
      whatsappPrefill:
        "مرحبا، انتهى اشتراك NADIPLAYER الخاص بي ({{username}}). أرغب بالتجديد.",
    },
    splash: {
      tagline: "اضبط على الكون",
      premiumTag: "تجربة IPTV مميزة",
    },
    firstRun: {
      title: "اختر لغتك",
      subtitle: "استخدم ← → للتنقل بين الأعلام، ثم اضغط متابعة",
      continue: "متابعة",
      hint: "يمكنك تغيير هذا لاحقا من الإعدادات",
    },
    update: {
      titleNormal: "تحديث جديد متاح",
      titleForced: "التحديث مطلوب",
      forcedNotice: "يجب تثبيت أحدث إصدار لمتابعة استخدام التطبيق.",
      adminPreview:
        "معاينة المسؤول. هذه النافذة إلزامية للمستخدمين العاديين (الإصدار المثبت v{{installed}} أقل من الحد الأدنى v{{min}}). يمكنك تجاهلها بحرية — لا يتم حظر المسؤولين أبدا.",
      loginPreview:
        "صفحة تسجيل الدخول متاحة دائما حتى يتمكن المسؤولون من تحديث إصدار التطبيق. اضغط \"لاحقا\" للمتابعة إلى نموذج تسجيل الدخول.",
      needPermission:
        "يرجى تمكين \"السماح بالتثبيت من هذا المصدر\" لتطبيق Nadiplayer في الشاشة التي فتحناها للتو، ثم عد واضغط الزر مرة أخرى.",
      installerOpened: "تم فتح المثبت. اتبع التعليمات على الشاشة للتثبيت.",
      whatsNew: "ما الجديد",
      noUrl: "لم يتم تكوين رابط التنزيل. تواصل مع المسؤول.",
      downloadingPercent: "جاري التنزيل {{percent}}%…",
      downloading: "جاري التنزيل…",
      openingInstaller: "جاري فتح المثبت…",
      allowInstallRetry: "اسمح بالتثبيت — حاول مرة أخرى",
      installerLaunched: "تم تشغيل المثبت",
      retry: "إعادة محاولة التحديث",
      updateNow: "تحديث الآن",
      downloadUpdate: "تنزيل التحديث",
      openInPlayStore: "افتح في متجر Play",
      later: "لاحقا",
      closeAria: "إغلاق إشعار التحديث",
    },
    pageLayout: {
      weatherCity: "لوس أنجلوس 24°",
    },
    notFound: {
      title: "404",
      message: "عذرا! الصفحة غير موجودة",
      goHome: "العودة إلى الرئيسية",
    },
    account: {
      title: "الحساب",
      profilesCount_zero: "لا ملفات شخصية",
      profilesCount_one: "ملف شخصي واحد",
      profilesCount_two: "ملفان شخصيان",
      profilesCount_few: "{{count}} ملفات شخصية",
      profilesCount_many: "{{count}} ملفا شخصيا",
      profilesCount_other: "{{count}} ملف شخصي",
      addServer: "إضافة سيرفر",
      devicePairing: "إقران الجهاز",
      devicePairingDesc:
        "اربط تلفزيون ذكي أو جهاز بث بحساب IPTV الخاص بك باستخدام رمز PIN مكون من 6 أرقام - دون كتابة روابط طويلة على جهاز التحكم.",
      imOnDevice: "أنا على الجهاز",
      iHavePin: "لدي رمز PIN",
      playbackMode: "وضع التشغيل",
      playbackModeDesc:
        "أين تفتح المشاهدات عند الضغط على قناة. الوضع الخارجي يفتح مباشرة في مشغلك المفضل — كل مشاهد يبث من IP الخاص به، لذا لا يمكن لمزودي الخدمة حظر IP التطبيق المشترك.",
      internal: "داخلي (مدمج)",
      external: "خارجي",
      externalOn: "تم تفعيل المشغل الخارجي",
      internalOn: "تم تفعيل المشغل الداخلي",
      externalPlayer: "المشغل الخارجي",
      externalPlayerDesc:
        "التطبيق الذي يفتح عند الضغط على قناة في الوضع الخارجي. VidoPlay هو الافتراضي — ثبته مرة واحدة ثم استمتع بفتح بنقرة واحدة لكل قناة.",
      default: "افتراضي",
      install: "تثبيت",
      externalPlayerSet: "المشغل الخارجي ← {{name}}",
      playerIdentity: "هوية المشغل",
      playerIdentityDesc:
        "ترويسة User-Agent المرسلة مع طلبات البث وواجهة API. اختر الذي يتوقعه مزود IPTV.",
      sending: "إرسال",
      userAgentSet: "User-Agent ← {{name}}",
      noProfiles: "لا توجد ملفات شخصية بعد",
      noProfilesDesc: "أضف سيرفر Xtream Codes للبدء.",
      profileName: "اسم الملف الشخصي",
      serverUrl: "رابط السيرفر",
      user: "المستخدم",
      profileUpdated: "تم تحديث الملف الشخصي",
      playlistReloaded: "تم إعادة تحميل القائمة",
      profileRemoved: "تم حذف الملف الشخصي",
      confirmDelete: "حذف هذا الملف الشخصي؟",
      connectedSuccess: "تم الاتصال بـ {{name}} بنجاح",
      connectFailed: "{{name}}: {{error}}",
      reloadPlaylist: "إعادة تحميل القائمة",
    },
    liveTV: {
      title: "البث المباشر",
      searchPlaceholder: "ابحث عن قنوات…",
      noActiveServer: "لا يوجد سيرفر نشط.",
      addProfile: "أضف ملفا شخصيا",
      contactAdmin: "تواصل مع المسؤول",
      favs: "المفضلة",
      listView: "عرض قائمة",
      gridView: "عرض شبكي",
      selectChannel: "اختر قناة",
      failedLoad: "فشل التحميل. تحقق من بيانات الاعتماد.",
      noChannels: "لم يتم العثور على قنوات.",
      nowPrefix: "الآن: {{title}}",
      reopen: "إعادة الفتح",
      channels_one: "قناة واحدة",
      channels_other: "{{count}} قناة",
      epgFor: "دليل البرامج · {{name}}",
      openingInApp: "جاري فتح {{channel}} في {{app}}",
      sentToApp: "تم الإرسال إلى {{app}}. ثبت APK للتشغيل التلقائي الموثوق.",
      couldntOpen:
        "تعذر فتح {{app}}. ثبته من الحساب ← المشغل الخارجي.",
    },
    movies: {
      title: "الأفلام",
      searchPlaceholder: "ابحث عن أفلام...",
      noActiveServer: "لا يوجد سيرفر نشط.",
      addProfile: "أضف ملفا شخصيا",
      contactAdmin: "تواصل مع المسؤول",
      failedLoad: "فشل تحميل الأفلام.",
    },
    series: {
      title: "المسلسلات",
      searchPlaceholder: "ابحث عن مسلسلات...",
      noActiveServer: "لا يوجد سيرفر نشط.",
      addProfile: "أضف ملفا شخصيا",
      contactAdmin: "تواصل مع المسؤول",
      failedLoad: "فشل تحميل المسلسلات.",
      season: "الموسم {{n}}",
      episodePrefix: "ح{{n}}",
    },
    addServer: {
      title: "إضافة قائمة",
      xtreamTab: "Xtream Codes",
      m3uTab: "رابط M3U",
      advanced: "متقدم",
      shared: "مشترك",
      ownServer: "سيرفر خاص",
      sharedHint: "يستخدم سيرفر Xtream الذي ضبطه المسؤول في الإعدادات العامة.",
      ownHint: "أدخل بيانات اعتماد سيرفر Xtream الخاص بك.",
      loadingShared: "جاري تحميل تفاصيل السيرفر المشترك...",
      sharedNotConfigured:
        "لم يقم المسؤول بضبط سيرفر مشترك بعد. بدل إلى سيرفر خاص أو اطلب من المسؤول ضبطه.",
      autoFilled: "سيرفر مشترك · تم التعبئة من الإعدادات العامة",
      profileNamePlaceholder: "اسم الملف (مثال: تلفزيون العائلة)",
      serverUrlPlaceholder: "رابط السيرفر (http://...)",
      usernamePlaceholder: "اسم المستخدم",
      passwordPlaceholder: "كلمة المرور",
      m3uPlaceholder: "https://example.com/playlist.m3u",
      hintShared: "اختر مشترك لاستخدام سيرفر NADIPLAYER العام.",
      hintOwn: "أدخل بيانات Xtream Codes لتحميل التلفزيون والأفلام والمسلسلات.",
      hintM3u: "الصق أي رابط قائمة M3U / M3U8 للاستيراد.",
    },
    admin: {
      title: "إدارة NADIPLAYER",
      subtitle: "لوحة التحكم بالمشتركين",
      logout: "تسجيل الخروج",
      settingsHeading: "الإعدادات العامة",
      whatsapp: "واتساب (مثال +15551234567)",
      sharedServer: "سيرفر Xtream المشترك",
      sharedUsername: "اسم مستخدم Xtream المشترك",
      sharedPassword: "كلمة مرور Xtream المشتركة",
      saveSettings: "حفظ الإعدادات",
      settingsSaved: "تم حفظ الإعدادات",
      createHeading: "إنشاء مشترك",
      usernameLabel: "اسم المستخدم",
      passwordLabel: "كلمة المرور",
      daysLabel: "الأيام",
      xtreamMode: "وضع Xtream",
      modeShared: "مشترك (عام)",
      modeOwn: "سيرفر خاص (لكل مستخدم)",
      serverUrl: "رابط سيرفر Xtream",
      xtreamUsername: "اسم مستخدم Xtream",
      xtreamPassword: "كلمة مرور Xtream",
      createUser: "إنشاء مستخدم",
      creating: "جاري الإنشاء...",
      userCreated: "تم إنشاء المستخدم",
      subscribersHeading: "المشتركون ({{count}})",
      noSubscribers: "لا يوجد مشتركون بعد.",
      noExpiry: "بدون انتهاء",
      daysLeft_zero: "لا أيام متبقية",
      daysLeft_one: "متبقي يوم واحد",
      daysLeft_two: "متبقي يومان",
      daysLeft_few: "متبقي {{count}} أيام",
      daysLeft_many: "متبقي {{count}} يوما",
      daysLeft_other: "متبقي {{count}} يوم",
      expired: "منتهي",
      advanced: "متقدم",
      server: "السيرفر",
      xtUser: "مستخدم Xt",
      xtPass: "كلمة Xt",
      saveXtream: "حفظ Xtream",
      xtreamSaved: "تم حفظ Xtream",
      newPassword: "كلمة مرور جديدة",
      updatePassword: "تحديث كلمة المرور",
      passwordUpdated: "تم تحديث كلمة المرور",
      addDays: "+{{n}} يوم",
      subDays: "-{{n}} يوم",
      dayAdded_one: "تمت إضافة يوم واحد",
      dayAdded_other: "تمت إضافة {{count}} أيام",
      dayRemoved_one: "تم حذف يوم واحد",
      dayRemoved_other: "تم حذف {{count}} أيام",
      deleteUser: "حذف",
      userDeleted: "تم حذف المستخدم",
      confirmDeleteUser: 'حذف المستخدم "{{username}}"؟',
      loadFailed: "فشل التحميل",
      opFailed: "فشل",
    },
    premium: {
      goldBadge: "حساب مميز",
      adFreeTag: "بدون إعلانات",
      daysRemaining_zero: "لا أيام متبقية",
      daysRemaining_one: "يوم واحد متبقي",
      daysRemaining_two: "يومان متبقيان",
      daysRemaining_few: "متبقي {{count}} أيام",
      daysRemaining_many: "متبقي {{count}} يوما",
      daysRemaining_other: "متبقي {{count}} يوم",
      expiresOn: "ينتهي في",
      expiredTitle: "انتهى الاشتراك",
      renewNow: "جدد الآن",
      haveSubscription: "لدي اشتراك بالفعل · تسجيل الدخول",
      upgradePitch:
        "قم بالترقية إلى الحساب المميز للاستمتاع بتجربة بدون إعلانات وميزات حصرية.",
      adminBadge: "حساب المسؤول",
      adminHint: "جميع الميزات مفعلة، بدون إعلانات.",
      premiumSubscriber: "مشترك مميز",
      welcomeMessage:
        "أنت تستخدم النسخة المميزة! استمتع بتجربة بدون إعلانات، وتسريع الأجهزة المتقدم لدعم 4K، والمساعدة التقنية ذات الأولوية. (ملاحظة: NadiPlayer هو مشغل وسائط فقط؛ لا يتم توفير أي محتوى أو قوائم تشغيل).",
    },
    noServer: {
      title: "الترقية إلى المميز",
      titleSubscriber: "إضافة ملف شخصي",
      alreadySubscribed: "هل لديك اشتراك بالفعل؟",
      upgradeNow: "الترقية الآن",
      signIn: "تسجيل الدخول",
      or: "أو",
      addOwnProfile: "إضافة ملف شخصي",
      addOwnHint: "استخدم بيانات اعتماد Xtream / M3U / Stalker الخاصة بك.",
      subscriberHint:
        "قم بتوصيل بيانات Xtream Codes أو قائمة M3U أو بوابة Stalker الخاصة بك للبدء بالمشاهدة.",
    },
    upgrade: {
      tag: "تفعيل المميز",
      title: "الترقية إلى المميز",
      intro:
        "يفتح الحساب المميز تجربة بدون إعلانات وميزات حصرية. يتم التفعيل خارج التطبيق.",
      howToTitle: "كيفية الترقية",
      instructions: "قم بزيارة",
      toActivate: "للتفعيل.",
      fromBrowser: "من المتصفح.",
      scanHint:
        "أو امسح رمز QR ضوئيًا باستخدام هاتفك — يفتح صفحة التفعيل مباشرةً.",
      deviceInfo: "معرفات جهازك",
      macAddress: "عنوان MAC",
      deviceId: "معرف الجهاز",
      devicePin: "رمز الجهاز",
      pairingHint:
        "استخدم عنوان MAC ورمز الجهاز على الموقع لربط هذا الجهاز باشتراكك.",
      deviceHint:
        "قدم هذه المعرفات على الموقع عند الطلب — تساعدنا على ربط تفعيل المميز بهذا الجهاز بالتحديد.",
      recheck: "إعادة التحقق من اشتراكي",
      compliance: "لا يوجد شراء داخل التطبيق · التفعيل عبر الموقع",
    },
    trial: {
      expiredTitle: "انتهت الفترة التجريبية",
      expiredDescription:
        "انتهت فترتك التجريبية المجانية لمدة 30 يومًا. قم بالترقية إلى حساب مميز لمدة سنة للمتابعة بدون إعلانات.",
      daysUsed: "تم استخدام {{used}} يوم · بدأت في {{date}}",
      loginAlready: "لدي اشتراك بالفعل · تسجيل الدخول",
      upgradeInfo: "معلومات الترقية ومعرف الجهاز",
      visitWebsiteHint: "للترقية إلى المميز وإزالة الإعلانات، يرجى زيارة موقعنا",
      fromBrowser: "من المتصفح.",
      recheck: "إعادة التحقق من اشتراكي",
      footnote: "لا يوجد شراء داخل التطبيق · التفعيل عبر الموقع",
    },
  },
};

// Helper to deep-merge override tables onto the English base so missing keys
// automatically fall back to English (handled by i18next fallbackLng as well,
// but making it explicit keeps every language structurally complete).
const fr = {
  translation: {
    ...en.translation,
    welcome: {
      ...en.translation.welcome,
      chooseHowToContinue: "Choisissez comment continuer",
      guest: "INVITÉ",
      guestHint:
        "Entrez avec votre propre serveur Xtream — gérez tout localement.",
      enter: "Entrer",
      login: "CONNEXION",
      loginHint:
        "Abonnés : connectez-vous avec le nom d'utilisateur et le mot de passe fournis par votre administrateur.",
      signIn: "Se connecter",
      premiumTag: "Expérience IPTV Premium",
      language: "Langue",
    },
    menu: {
      title: "Menu",
      home: "Accueil",
      liveTv: "TV en direct",
      movies: "Films",
      series: "Séries",
      account: "Compte",
      settings: "Paramètres",
      open: "Ouvrir le menu",
      close: "Fermer le menu",
    },
    login: {
      ...en.translation.login,
      subtitle: "Connexion Abonné",
      username: "Nom d'utilisateur",
      password: "Mot de passe",
      submit: "Se connecter",
      submitting: "Connexion...",
      contactAdmin:
        "Pas de compte ? Contactez votre administrateur NADIPLAYER pour obtenir les identifiants.",
      back: "Retour",
    },
    home: {
      ...en.translation.home,
      logout: "Déconnexion",
      profile: "Profil",
      guestMode: "Mode Invité",
      connected: "Connecté.",
      awaiting: "En attente de synchronisation.",
      waiting: "En attente de connexion.",
      subscriber: "Abonné",
      expires: "Expire le",
      noExpiry: "Aucune date d'expiration",
      daysRemaining_one: "{{count}} jour restant",
      daysRemaining_other: "{{count}} jours restants",
      expired: "EXPIRÉ",
      timeshift: "Timeshift",
      categories: {
        ...en.translation.home.categories,
        liveTv: "TV en direct",
        movies: "Films",
        series: "Séries",
        liveTvCount: "+5000 Chaînes",
        moviesCount: "+1200 Films",
        seriesCount: "+500 Séries",
      },
      infoBar: "DIRECT : +5000 Chaînes. FILMS : +1200. SÉRIES : +500.",
    },
    expired: {
      ...en.translation.expired,
      title: "ABONNEMENT EXPIRÉ",
      hi: "Bonjour",
      message:
        "Votre abonnement NADIPLAYER a pris fin. Pour continuer à regarder, contactez-nous sur WhatsApp pour renouveler.",
      contactWhatsapp: "Service client",
      signOut: "Se déconnecter",
      whatsappPrefill:
        "Bonjour, mon abonnement NADIPLAYER ({{username}}) a expiré. Je souhaite renouveler.",
    },
    splash: {
      tagline: "Branchez-vous sur l'univers",
      premiumTag: "Expérience IPTV Premium",
    },
    firstRun: {
      title: "Choisissez votre langue",
      subtitle: "Utilisez ← → pour changer de drapeau, puis appuyez sur Continuer",
      continue: "Continuer",
      hint: "Vous pourrez modifier cela plus tard dans les paramètres",
    },
    update: {
      titleNormal: "Nouvelle mise à jour disponible",
      titleForced: "Mise à jour requise",
      forcedNotice: "Vous devez installer la dernière version pour continuer à utiliser l'application.",
      adminPreview:
        "Aperçu admin. Ce popup est forcé pour les utilisateurs normaux (installé v{{installed}} < min v{{min}}). Vous pouvez le fermer librement — les admins ne sont jamais bloqués.",
      loginPreview:
        "La connexion est toujours accessible afin que les administrateurs puissent mettre à jour la version. Appuyez sur « Plus tard » pour accéder au formulaire de connexion.",
      needPermission:
        "Veuillez activer « Autoriser l'installation depuis cette source » pour Nadiplayer dans l'écran qui vient de s'ouvrir, puis revenez et réappuyez sur le bouton.",
      installerOpened: "Programme d'installation ouvert. Suivez les instructions à l'écran.",
      whatsNew: "Nouveautés",
      noUrl: "Aucun lien de téléchargement configuré. Contactez l'administrateur.",
      downloadingPercent: "Téléchargement {{percent}}%…",
      downloading: "Téléchargement…",
      openingInstaller: "Ouverture du programme d'installation…",
      allowInstallRetry: "Autoriser l'installation — réessayer",
      installerLaunched: "Programme d'installation lancé",
      retry: "Réessayer la mise à jour",
      updateNow: "Mettre à jour",
      downloadUpdate: "Télécharger la mise à jour",
      openInPlayStore: "Ouvrir dans Play Store",
      later: "Plus tard",
      closeAria: "Fermer la notification de mise à jour",
    },
    notFound: {
      ...en.translation.notFound,
      message: "Oups ! Page introuvable",
      goHome: "Retour à l'accueil",
    },
    liveTV: {
      ...en.translation.liveTV,
      title: "TV EN DIRECT",
      searchPlaceholder: "Rechercher des chaînes…",
      noActiveServer: "Aucun serveur actif.",
      addProfile: "Ajouter un profil",
      favs: "Favoris",
      selectChannel: "Sélectionnez une chaîne",
      noChannels: "Aucune chaîne trouvée.",
      failedLoad: "Échec du chargement. Vérifiez les identifiants.",
      channels_one: "{{count}} chaîne",
      channels_other: "{{count}} chaînes",
    },
    movies: {
      ...en.translation.movies,
      title: "FILMS",
      searchPlaceholder: "Rechercher des films...",
      noActiveServer: "Aucun serveur actif.",
      addProfile: "Ajouter un profil",
      failedLoad: "Échec du chargement des films.",
    },
    series: {
      ...en.translation.series,
      title: "SÉRIES",
      searchPlaceholder: "Rechercher des séries...",
      noActiveServer: "Aucun serveur actif.",
      addProfile: "Ajouter un profil",
      failedLoad: "Échec du chargement des séries.",
      season: "Saison {{n}}",
    },
    addServer: {
      ...en.translation.addServer,
      title: "AJOUTER UNE LISTE",
      advanced: "Avancé",
      shared: "Partagé",
      ownServer: "Serveur propre",
      profileNamePlaceholder: "Nom du profil (ex. TV Famille)",
      usernamePlaceholder: "Nom d'utilisateur",
      passwordPlaceholder: "Mot de passe",
    },
    admin: {
      ...en.translation.admin,
      title: "NADIPLAYER ADMIN",
      subtitle: "Panneau de contrôle des abonnés",
      settingsHeading: "PARAMÈTRES GLOBAUX",
      createHeading: "CRÉER UN ABONNÉ",
      subscribersHeading: "ABONNÉS ({{count}})",
      createUser: "Créer l'utilisateur",
      saveSettings: "Enregistrer",
    },
    account: {
      ...en.translation.account,
      title: "COMPTE",
      addServer: "Ajouter un serveur",
      devicePairing: "Appairage d'appareil",
      playbackMode: "Mode de lecture",
      externalPlayer: "Lecteur externe",
      playerIdentity: "Identité du lecteur",
    },
    premium: {
      ...en.translation.premium,
      goldBadge: "Compte Premium",
      adFreeTag: "Sans pub",
      daysRemaining_one: "{{count}} jour restant",
      daysRemaining_other: "{{count}} jours restants",
      expiresOn: "Expire le",
      expiredTitle: "Abonnement expiré",
      renewNow: "Renouveler",
      haveSubscription: "J'ai déjà un abonnement · Se connecter",
      upgradePitch:
        "Passez au compte Premium pour profiter d'une expérience sans publicité et de fonctionnalités exclusives.",
      adminBadge: "Compte administrateur",
      adminHint: "Toutes les fonctionnalités débloquées, sans pub.",
      premiumSubscriber: "Abonné Premium",
      welcomeMessage:
        "Vous utilisez la version Premium ! Profitez d'une expérience sans publicité, d'une accélération matérielle avancée pour le support 4K, et d'une assistance technique prioritaire. (Remarque : NadiPlayer est un lecteur multimédia uniquement ; aucun contenu ni playlist n'est fourni).",
    },
    noServer: {
      title: "Passer en Premium",
      titleSubscriber: "Ajouter un profil",
      alreadySubscribed: "Vous avez déjà un abonnement ?",
      upgradeNow: "Mettre à niveau",
      signIn: "Se connecter",
      or: "ou",
      addOwnProfile: "Ajouter un profil",
      addOwnHint: "Utilisez vos identifiants Xtream / M3U / Stalker.",
      subscriberHint:
        "Connectez vos identifiants Xtream Codes, votre playlist M3U ou votre portail Stalker pour commencer à regarder.",
    },
    upgrade: {
      tag: "Activation Premium",
      title: "PASSER EN PREMIUM",
      intro:
        "Premium débloque une expérience sans publicité et des fonctionnalités exclusives. L'activation se fait hors de l'application.",
      howToTitle: "Comment passer en Premium",
      instructions: "Visitez",
      toActivate: "pour activer.",
      fromBrowser: "depuis votre navigateur.",
      scanHint:
        "Ou scannez le code QR avec votre téléphone — il ouvre la page d'activation directement.",
      deviceInfo: "Identifiants de votre appareil",
      macAddress: "Adresse MAC",
      deviceId: "ID Appareil",
      devicePin: "Code PIN appareil",
      pairingHint:
        "Utilisez votre adresse MAC et votre code PIN appareil sur le site pour associer cet appareil à votre abonnement.",
      deviceHint:
        "Fournissez ces identifiants sur le site si demandé — ils nous permettent de lier votre activation Premium à cet appareil.",
      recheck: "Re-vérifier mon abonnement",
      compliance: "Aucun achat in-app · Activation via le site",
    },
    trial: {
      expiredTitle: "ESSAI EXPIRÉ",
      expiredDescription:
        "Votre essai gratuit de 30 jours est terminé. Passez à un compte Premium d'un an pour continuer sans publicité.",
      daysUsed: "{{used}} jours utilisés · démarré le {{date}}",
      loginAlready: "J'ai déjà un abonnement · Se connecter",
      upgradeInfo: "Infos de mise à niveau & ID appareil",
      visitWebsiteHint:
        "Pour passer en Premium et supprimer les publicités, visitez notre site",
      fromBrowser: "depuis votre navigateur.",
      recheck: "Re-vérifier mon abonnement",
      footnote: "Aucun achat in-app · Activation via le site",
    },
  },
};

const es = {
  translation: {
    ...en.translation,
    welcome: {
      ...en.translation.welcome,
      chooseHowToContinue: "Elige cómo continuar",
      guest: "INVITADO",
      guestHint: "Entra con tu propio servidor Xtream — gestiona todo localmente.",
      enter: "Entrar",
      login: "INICIAR SESIÓN",
      loginHint:
        "Suscriptores: inicia sesión con el usuario y contraseña que te dio tu administrador.",
      signIn: "Iniciar Sesión",
      premiumTag: "Experiencia IPTV Premium",
      language: "Idioma",
    },
    login: {
      ...en.translation.login,
      subtitle: "Acceso de Suscriptor",
      username: "Usuario",
      password: "Contraseña",
      submit: "Iniciar Sesión",
      submitting: "Accediendo...",
      contactAdmin:
        "¿No tienes cuenta? Contacta a tu administrador de NADIPLAYER para obtener credenciales.",
      back: "Atrás",
    },
    home: {
      ...en.translation.home,
      logout: "Cerrar Sesión",
      profile: "Perfil",
      guestMode: "Modo Invitado",
      connected: "Conectado.",
      awaiting: "Esperando sincronización.",
      waiting: "Esperando conexión.",
      subscriber: "Suscriptor",
      expires: "Expira",
      noExpiry: "Sin fecha de expiración",
      daysRemaining_one: "Queda {{count}} día",
      daysRemaining_other: "Quedan {{count}} días",
      expired: "EXPIRADO",
      categories: {
        ...en.translation.home.categories,
        liveTv: "TV en Vivo",
        movies: "Películas",
        series: "Series",
        liveTvCount: "+5000 Canales",
        moviesCount: "+1200 Películas",
        seriesCount: "+500 Series",
      },
      infoBar: "EN VIVO: +5000 Canales. PELÍCULAS: +1200. SERIES: +500.",
    },
    expired: {
      ...en.translation.expired,
      title: "SUSCRIPCIÓN EXPIRADA",
      hi: "Hola",
      message:
        "Tu suscripción NADIPLAYER ha finalizado. Para seguir viendo, contáctanos por WhatsApp para renovar.",
      contactWhatsapp: "Atención al cliente",
      signOut: "Cerrar Sesión",
      whatsappPrefill:
        "Hola, mi suscripción NADIPLAYER ({{username}}) ha expirado. Me gustaría renovarla.",
    },
    splash: { tagline: "Sintoniza con el universo", premiumTag: "Experiencia IPTV Premium" },
    firstRun: {
      title: "Elige tu idioma",
      subtitle: "Usa ← → para cambiar de bandera, luego pulsa Continuar",
      continue: "Continuar",
      hint: "Puedes cambiarlo más tarde desde Ajustes",
    },
    update: {
      titleNormal: "Nueva actualización disponible",
      titleForced: "Actualización requerida",
      forcedNotice: "Debes instalar la última versión para seguir usando la app.",
      adminPreview:
        "Vista de admin. Este popup es obligatorio para usuarios normales (instalado v{{installed}} < min v{{min}}). Puedes cerrarlo libremente — los administradores nunca quedan bloqueados.",
      loginPreview:
        "El inicio de sesión siempre está disponible para que los administradores puedan actualizar la versión. Pulsa \"Más tarde\" para continuar al formulario de inicio.",
      needPermission:
        "Activa \"Permitir instalación desde esta fuente\" para Nadiplayer en la pantalla que abrimos, luego vuelve y pulsa el botón otra vez.",
      installerOpened: "Instalador abierto. Sigue las instrucciones para instalar.",
      whatsNew: "Novedades",
      noUrl: "No hay enlace de descarga configurado. Contacta al administrador.",
      downloadingPercent: "Descargando {{percent}}%…",
      downloading: "Descargando…",
      openingInstaller: "Abriendo instalador…",
      allowInstallRetry: "Permitir instalación — reintentar",
      installerLaunched: "Instalador iniciado",
      retry: "Reintentar actualización",
      updateNow: "Actualizar ahora",
      downloadUpdate: "Descargar actualización",
      openInPlayStore: "Abrir en Play Store",
      later: "Más tarde",
      closeAria: "Cerrar aviso de actualización",
    },
    notFound: {
      ...en.translation.notFound,
      message: "¡Ups! Página no encontrada",
      goHome: "Volver al inicio",
    },
    liveTV: {
      ...en.translation.liveTV,
      title: "TV EN VIVO",
      searchPlaceholder: "Buscar canales…",
      noActiveServer: "Sin servidor activo.",
      addProfile: "Añadir perfil",
      favs: "Favs",
      selectChannel: "Selecciona un canal",
      noChannels: "No se encontraron canales.",
      channels_one: "{{count}} canal",
      channels_other: "{{count}} canales",
    },
    movies: {
      ...en.translation.movies,
      title: "PELÍCULAS",
      searchPlaceholder: "Buscar películas...",
      noActiveServer: "Sin servidor activo.",
      addProfile: "Añadir perfil",
      failedLoad: "Error al cargar películas.",
    },
    series: {
      ...en.translation.series,
      title: "SERIES",
      searchPlaceholder: "Buscar series...",
      noActiveServer: "Sin servidor activo.",
      addProfile: "Añadir perfil",
      failedLoad: "Error al cargar series.",
      season: "Temporada {{n}}",
    },
    addServer: {
      ...en.translation.addServer,
      title: "AÑADIR PLAYLIST",
      advanced: "Avanzado",
      shared: "Compartido",
      ownServer: "Servidor propio",
    },
    admin: {
      ...en.translation.admin,
      subtitle: "Panel de control de suscriptores",
      settingsHeading: "AJUSTES GLOBALES",
      createHeading: "CREAR SUSCRIPTOR",
      subscribersHeading: "SUSCRIPTORES ({{count}})",
      createUser: "Crear usuario",
      saveSettings: "Guardar",
    },
    account: {
      ...en.translation.account,
      title: "CUENTA",
      addServer: "Añadir servidor",
      devicePairing: "Emparejar dispositivo",
      playbackMode: "Modo de reproducción",
      externalPlayer: "Reproductor externo",
      playerIdentity: "Identidad del reproductor",
    },
    premium: {
      ...en.translation.premium,
      goldBadge: "Cuenta Premium",
      adFreeTag: "Sin anuncios",
      daysRemaining_one: "Queda {{count}} día",
      daysRemaining_other: "Quedan {{count}} días",
      expiresOn: "Expira el",
      expiredTitle: "Suscripción expirada",
      renewNow: "Renovar ahora",
      haveSubscription: "Ya tengo suscripción · Iniciar sesión",
      upgradePitch:
        "Actualiza a una cuenta Premium para disfrutar de una experiencia sin anuncios y funciones exclusivas.",
      adminBadge: "Cuenta de administrador",
      adminHint: "Todas las funciones desbloqueadas, sin anuncios.",
      premiumSubscriber: "Suscriptor Premium",
      welcomeMessage:
        "¡Estás usando la versión Premium! Disfruta de una experiencia sin anuncios, aceleración de hardware avanzada para compatibilidad con 4K y asistencia técnica prioritaria. (Nota: NadiPlayer es solo un reproductor multimedia; no se proporciona contenido ni listas de reproducción).",
    },
    noServer: {
      title: "Pásate a Premium",
      titleSubscriber: "Añadir un perfil",
      alreadySubscribed: "¿Ya tienes una suscripción?",
      upgradeNow: "Actualizar ahora",
      signIn: "Iniciar sesión",
      or: "o",
      addOwnProfile: "Añadir un perfil",
      addOwnHint: "Usa tus credenciales Xtream / M3U / Stalker.",
      subscriberHint:
        "Conecta tus credenciales de Xtream Codes, tu lista M3U o tu portal Stalker para empezar a ver.",
    },
    upgrade: {
      tag: "Activación Premium",
      title: "ACTUALIZAR A PREMIUM",
      intro:
        "Premium desbloquea una experiencia sin anuncios y funciones exclusivas. La activación se realiza fuera de la app.",
      howToTitle: "Cómo actualizar",
      instructions: "Visita",
      toActivate: "para activar.",
      fromBrowser: "desde tu navegador.",
      scanHint:
        "O escanea el código QR con tu teléfono — abre la página de activación directamente.",
      deviceInfo: "Identificadores de tu dispositivo",
      macAddress: "Dirección MAC",
      deviceId: "ID del dispositivo",
      devicePin: "PIN del dispositivo",
      pairingHint:
        "Usa tu dirección MAC y PIN del dispositivo en el sitio para vincular este dispositivo con tu suscripción.",
      deviceHint:
        "Proporciona estos identificadores en el sitio si se te solicitan — nos permiten vincular tu activación Premium a este dispositivo.",
      recheck: "Volver a verificar mi suscripción",
      compliance: "Sin compras dentro de la app · Activación a través del sitio",
    },
    trial: {
      expiredTitle: "PRUEBA EXPIRADA",
      expiredDescription:
        "Tu prueba gratuita de 30 días ha expirado. Actualiza a una cuenta Premium de 1 año para seguir usando NadiPlayer sin anuncios.",
      daysUsed: "{{used}} días usados · iniciado el {{date}}",
      loginAlready: "Ya tengo una suscripción · Iniciar sesión",
      upgradeInfo: "Información de actualización e ID del dispositivo",
      visitWebsiteHint:
        "Para actualizar a Premium y eliminar los anuncios, visita nuestro sitio",
      fromBrowser: "desde tu navegador.",
      recheck: "Volver a verificar mi suscripción",
      footnote: "Sin compras dentro de la app · Activación a través del sitio",
    },
  },
};

const ru = {
  translation: {
    ...en.translation,
    welcome: {
      ...en.translation.welcome,
      chooseHowToContinue: "Выберите, как продолжить",
      guest: "ГОСТЬ",
      guestHint: "Войдите со своим собственным сервером Xtream.",
      enter: "Войти",
      login: "ВХОД",
      loginHint: "Подписчики: войдите с данными от администратора.",
      signIn: "Войти",
      premiumTag: "Премиум IPTV-опыт",
      language: "Язык",
    },
    login: {
      ...en.translation.login,
      subtitle: "Вход подписчика",
      username: "Имя пользователя",
      password: "Пароль",
      submit: "Войти",
      submitting: "Вход...",
      contactAdmin: "Нет аккаунта? Свяжитесь с администратором NADIPLAYER.",
      back: "Назад",
    },
    home: {
      ...en.translation.home,
      logout: "Выйти",
      profile: "Профиль",
      guestMode: "Режим гостя",
      connected: "Подключено.",
      awaiting: "Ожидание синхронизации.",
      waiting: "Ожидание подключения.",
      subscriber: "Подписчик",
      expires: "Истекает",
      noExpiry: "Без срока действия",
      daysRemaining_one: "Осталось {{count}} день",
      daysRemaining_other: "Осталось {{count}} дней",
      expired: "ИСТЁК",
      categories: {
        ...en.translation.home.categories,
        liveTv: "ТВ",
        movies: "Фильмы",
        series: "Сериалы",
        liveTvCount: "+5000 каналов",
        moviesCount: "+1200 фильмов",
        seriesCount: "+500 сериалов",
      },
      infoBar: "ТВ: +5000 каналов. ФИЛЬМЫ: +1200. СЕРИАЛЫ: +500.",
    },
    expired: {
      ...en.translation.expired,
      title: "ПОДПИСКА ИСТЕКЛА",
      hi: "Привет",
      message:
        "Ваша подписка NADIPLAYER закончилась. Свяжитесь с нами в WhatsApp для продления.",
      contactWhatsapp: "Поддержка клиентов",
      signOut: "Выйти",
      whatsappPrefill:
        "Здравствуйте, моя подписка NADIPLAYER ({{username}}) истекла. Хочу продлить.",
    },
    splash: { tagline: "Настройтесь на вселенную", premiumTag: "Премиум IPTV-опыт" },
    firstRun: {
      title: "Выберите язык",
      subtitle: "Используйте ← → для смены флага, затем нажмите Продолжить",
      continue: "Продолжить",
      hint: "Это можно изменить позже в настройках",
    },
    update: {
      titleNormal: "Доступно обновление",
      titleForced: "Требуется обновление",
      forcedNotice: "Чтобы продолжить пользоваться приложением, установите последнюю версию.",
      adminPreview:
        "Предпросмотр администратора. Это окно обязательно для обычных пользователей (установлена v{{installed}} < минимум v{{min}}). Вы можете закрыть его — администраторы никогда не блокируются.",
      loginPreview:
        "Страница входа всегда доступна, чтобы администраторы могли обновить версию приложения. Нажмите «Позже», чтобы перейти к форме входа.",
      needPermission:
        "Включите «Разрешить установку из этого источника» для Nadiplayer в открытом окне, затем вернитесь и нажмите кнопку снова.",
      installerOpened: "Установщик открыт. Следуйте подсказкам на экране для установки.",
      whatsNew: "Что нового",
      noUrl: "Ссылка для загрузки не настроена. Свяжитесь с администратором.",
      downloadingPercent: "Загрузка {{percent}}%…",
      downloading: "Загрузка…",
      openingInstaller: "Открытие установщика…",
      allowInstallRetry: "Разрешите установку — попробуйте снова",
      installerLaunched: "Установщик запущен",
      retry: "Повторить обновление",
      updateNow: "Обновить сейчас",
      downloadUpdate: "Скачать обновление",
      openInPlayStore: "Открыть в Play Store",
      later: "Позже",
      closeAria: "Закрыть уведомление об обновлении",
    },
    notFound: {
      ...en.translation.notFound,
      message: "Упс! Страница не найдена",
      goHome: "На главную",
    },
    liveTV: {
      ...en.translation.liveTV,
      title: "ЖИВОЕ ТВ",
      searchPlaceholder: "Поиск каналов…",
      noActiveServer: "Нет активного сервера.",
      addProfile: "Добавить профиль",
      favs: "Избранное",
      selectChannel: "Выберите канал",
      noChannels: "Каналы не найдены.",
      channels_one: "{{count}} канал",
      channels_other: "{{count}} каналов",
    },
    movies: {
      ...en.translation.movies,
      title: "ФИЛЬМЫ",
      searchPlaceholder: "Поиск фильмов...",
      noActiveServer: "Нет активного сервера.",
      addProfile: "Добавить профиль",
      failedLoad: "Не удалось загрузить фильмы.",
    },
    series: {
      ...en.translation.series,
      title: "СЕРИАЛЫ",
      searchPlaceholder: "Поиск сериалов...",
      noActiveServer: "Нет активного сервера.",
      addProfile: "Добавить профиль",
      failedLoad: "Не удалось загрузить сериалы.",
      season: "Сезон {{n}}",
    },
    addServer: {
      ...en.translation.addServer,
      title: "ДОБАВИТЬ ПЛЕЙЛИСТ",
      advanced: "Расширенные",
      shared: "Общий",
      ownServer: "Свой сервер",
    },
    admin: {
      ...en.translation.admin,
      subtitle: "Панель управления подписчиками",
      settingsHeading: "ГЛОБАЛЬНЫЕ НАСТРОЙКИ",
      createHeading: "СОЗДАТЬ ПОДПИСЧИКА",
      subscribersHeading: "ПОДПИСЧИКИ ({{count}})",
      createUser: "Создать",
      saveSettings: "Сохранить",
    },
    account: {
      ...en.translation.account,
      title: "АККАУНТ",
      addServer: "Добавить сервер",
      devicePairing: "Связать устройство",
      playbackMode: "Режим воспроизведения",
      externalPlayer: "Внешний плеер",
      playerIdentity: "Идентификатор плеера",
    },
    premium: {
      ...en.translation.premium,
      goldBadge: "Premium-аккаунт",
      adFreeTag: "Без рекламы",
      daysRemaining_one: "Остался {{count}} день",
      daysRemaining_few: "Осталось {{count}} дня",
      daysRemaining_many: "Осталось {{count}} дней",
      daysRemaining_other: "Осталось {{count}} дней",
      expiresOn: "Истекает",
      expiredTitle: "Подписка истекла",
      renewNow: "Продлить",
      haveSubscription: "У меня уже есть подписка · Войти",
      upgradePitch:
        "Перейдите на Premium-аккаунт, чтобы наслаждаться опытом без рекламы и эксклюзивными функциями.",
      adminBadge: "Аккаунт администратора",
      adminHint: "Все функции разблокированы, без рекламы.",
      premiumSubscriber: "Premium-подписчик",
    },
  },
};

const ko = {
  translation: {
    ...en.translation,
    welcome: {
      ...en.translation.welcome,
      chooseHowToContinue: "계속하는 방법을 선택하세요",
      guest: "게스트",
      guestHint: "자신의 Xtream 서버로 입장하세요.",
      enter: "입장",
      login: "로그인",
      loginHint: "가입자: 관리자가 제공한 아이디와 비밀번호로 로그인하세요.",
      signIn: "로그인",
      premiumTag: "프리미엄 IPTV 경험",
      language: "언어",
    },
    login: {
      ...en.translation.login,
      subtitle: "가입자 로그인",
      username: "사용자 이름",
      password: "비밀번호",
      submit: "로그인",
      submitting: "로그인 중...",
      contactAdmin: "계정이 없으신가요? NADIPLAYER 관리자에게 문의하세요.",
      back: "뒤로",
    },
    home: {
      ...en.translation.home,
      logout: "로그아웃",
      profile: "프로필",
      guestMode: "게스트 모드",
      connected: "연결됨.",
      awaiting: "서버 동기화 대기 중.",
      waiting: "연결 대기 중.",
      subscriber: "가입자",
      expires: "만료일",
      noExpiry: "만료일 없음",
      daysRemaining_one: "{{count}}일 남음",
      daysRemaining_other: "{{count}}일 남음",
      expired: "만료됨",
      categories: {
        ...en.translation.home.categories,
        liveTv: "실시간 TV",
        movies: "영화",
        series: "시리즈",
        liveTvCount: "+5000 채널",
        moviesCount: "+1200 영화",
        seriesCount: "+500 시리즈",
      },
      infoBar: "실시간: +5000 채널. 영화: +1200. 시리즈: +500.",
    },
    expired: {
      ...en.translation.expired,
      title: "구독 만료됨",
      hi: "안녕하세요",
      message: "NADIPLAYER 구독이 종료되었습니다. 갱신을 위해 WhatsApp으로 문의하세요.",
      contactWhatsapp: "고객 지원",
      signOut: "로그아웃",
      whatsappPrefill:
        "안녕하세요, 제 NADIPLAYER 구독 ({{username}})이 만료되었습니다. 갱신하고 싶습니다.",
    },
    splash: { tagline: "우주에 맞추세요", premiumTag: "프리미엄 IPTV 경험" },
    firstRun: {
      title: "언어를 선택하세요",
      subtitle: "← → 키로 국기를 전환한 후 계속을 누르세요",
      continue: "계속",
      hint: "나중에 설정에서 변경할 수 있습니다",
    },
    update: {
      titleNormal: "새 업데이트 사용 가능",
      titleForced: "업데이트 필요",
      forcedNotice: "앱을 계속 사용하려면 최신 버전을 설치해야 합니다.",
      adminPreview:
        "관리자 미리보기. 이 팝업은 일반 사용자에게 강제됩니다 (설치 v{{installed}} < 최소 v{{min}}). 자유롭게 닫을 수 있습니다 — 관리자는 절대 잠기지 않습니다.",
      loginPreview:
        "관리자가 앱 버전을 업데이트할 수 있도록 로그인은 항상 접근 가능합니다. \"나중에\"를 눌러 로그인 양식으로 계속하세요.",
      needPermission:
        "방금 연 화면에서 Nadiplayer에 대해 \"이 출처에서 설치 허용\"을 활성화한 다음, 돌아와서 버튼을 다시 누르세요.",
      installerOpened: "설치 프로그램이 열렸습니다. 화면 안내에 따라 설치하세요.",
      whatsNew: "새로운 기능",
      noUrl: "다운로드 링크가 구성되지 않았습니다. 관리자에게 문의하세요.",
      downloadingPercent: "다운로드 중 {{percent}}%…",
      downloading: "다운로드 중…",
      openingInstaller: "설치 프로그램 여는 중…",
      allowInstallRetry: "설치 허용 — 다시 시도",
      installerLaunched: "설치 프로그램 시작됨",
      retry: "업데이트 재시도",
      updateNow: "지금 업데이트",
      downloadUpdate: "업데이트 다운로드",
      openInPlayStore: "Play 스토어에서 열기",
      later: "나중에",
      closeAria: "업데이트 알림 닫기",
    },
    notFound: { ...en.translation.notFound, message: "페이지를 찾을 수 없습니다", goHome: "홈으로" },
    liveTV: {
      ...en.translation.liveTV,
      title: "실시간 TV",
      searchPlaceholder: "채널 검색…",
      noActiveServer: "활성 서버 없음.",
      addProfile: "프로필 추가",
      favs: "즐겨찾기",
      selectChannel: "채널을 선택하세요",
      noChannels: "채널을 찾을 수 없습니다.",
      channels_one: "{{count}}개 채널",
      channels_other: "{{count}}개 채널",
    },
    movies: {
      ...en.translation.movies,
      title: "영화",
      searchPlaceholder: "영화 검색...",
      noActiveServer: "활성 서버 없음.",
      addProfile: "프로필 추가",
      failedLoad: "영화 로드 실패.",
    },
    series: {
      ...en.translation.series,
      title: "시리즈",
      searchPlaceholder: "시리즈 검색...",
      noActiveServer: "활성 서버 없음.",
      addProfile: "프로필 추가",
      failedLoad: "시리즈 로드 실패.",
      season: "시즌 {{n}}",
    },
    addServer: {
      ...en.translation.addServer,
      title: "플레이리스트 추가",
      advanced: "고급",
      shared: "공유",
      ownServer: "자체 서버",
    },
    admin: {
      ...en.translation.admin,
      subtitle: "가입자 제어판",
      settingsHeading: "전체 설정",
      createHeading: "가입자 생성",
      subscribersHeading: "가입자 ({{count}})",
      createUser: "사용자 생성",
      saveSettings: "저장",
    },
    account: {
      ...en.translation.account,
      title: "계정",
      addServer: "서버 추가",
      devicePairing: "기기 연결",
      playbackMode: "재생 모드",
      externalPlayer: "외부 플레이어",
      playerIdentity: "플레이어 신원",
    },
    premium: {
      ...en.translation.premium,
      goldBadge: "프리미엄 계정",
      adFreeTag: "광고 없음",
      daysRemaining_one: "{{count}}일 남음",
      daysRemaining_other: "{{count}}일 남음",
      expiresOn: "만료일",
      expiredTitle: "구독 만료됨",
      renewNow: "지금 갱신",
      haveSubscription: "이미 구독이 있습니다 · 로그인",
      upgradePitch:
        "프리미엄 계정으로 업그레이드하여 광고 없는 경험과 독점 기능을 즐겨보세요.",
      adminBadge: "관리자 계정",
      adminHint: "모든 기능 잠금 해제, 광고 없음.",
      premiumSubscriber: "프리미엄 구독자",
      welcomeMessage:
        "프리미엄 버전을 사용 중입니다! 광고 없는 경험, 4K 지원을 위한 고급 하드웨어 가속, 우선 기술 지원을 즐기세요. (참고: NadiPlayer는 미디어 플레이어일 뿐이며 콘텐츠나 재생 목록은 제공되지 않습니다).",
    },
    noServer: {
      title: "프리미엄으로 업그레이드",
      titleSubscriber: "프로필 추가",
      alreadySubscribed: "이미 구독 중이신가요?",
      upgradeNow: "지금 업그레이드",
      signIn: "로그인",
      or: "또는",
      addOwnProfile: "프로필 추가",
      addOwnHint: "본인의 Xtream / M3U / Stalker 자격 증명을 사용하세요.",
      subscriberHint:
        "Xtream Codes, M3U 재생목록 또는 Stalker 포털 자격 증명을 연결하여 시청을 시작하세요.",
    },
    upgrade: {
      tag: "프리미엄 활성화",
      title: "프리미엄으로 업그레이드",
      intro:
        "프리미엄은 광고 없는 경험과 독점 기능을 제공합니다. 활성화는 앱 외부에서 진행됩니다.",
      howToTitle: "업그레이드 방법",
      instructions: "다음 페이지를 방문하세요",
      toActivate: "활성화하려면.",
      fromBrowser: "브라우저에서.",
      scanHint:
        "또는 휴대폰으로 QR 코드를 스캔하세요 — 활성화 페이지가 바로 열립니다.",
      deviceInfo: "기기 식별자",
      macAddress: "MAC 주소",
      deviceId: "기기 ID",
      devicePin: "기기 PIN",
      pairingHint:
        "MAC 주소와 기기 PIN을 웹사이트에서 사용하여 이 기기를 구독에 연결하세요.",
      deviceHint:
        "요청 시 웹사이트에 이 식별자를 제공하세요 — 프리미엄 활성화를 이 기기에 연결할 수 있습니다.",
      recheck: "구독 다시 확인",
      compliance: "앱 내 구매 없음 · 웹사이트를 통한 활성화",
    },
    trial: {
      expiredTitle: "체험판 만료",
      expiredDescription:
        "30일 무료 체험판이 만료되었습니다. 광고 없이 NadiPlayer를 계속 사용하려면 1년 프리미엄 계정으로 업그레이드하세요.",
      daysUsed: "{{used}}일 사용됨 · {{date}} 시작",
      loginAlready: "이미 구독이 있습니다 · 로그인",
      upgradeInfo: "업그레이드 정보 및 기기 ID",
      visitWebsiteHint:
        "프리미엄으로 업그레이드하고 광고를 제거하려면 다음 웹사이트를 방문하세요",
      fromBrowser: "브라우저에서.",
      recheck: "구독 다시 확인",
      footnote: "앱 내 구매 없음 · 웹사이트를 통한 활성화",
    },
  },
};

const fil = {
  translation: {
    ...en.translation,
    welcome: {
      ...en.translation.welcome,
      chooseHowToContinue: "Pumili kung paano magpatuloy",
      guest: "BISITA",
      guestHint: "Pumasok gamit ang sarili mong Xtream server.",
      enter: "Pumasok",
      login: "MAG-LOGIN",
      loginHint:
        "Mga Subscriber: mag-sign in gamit ang username at password mula sa admin.",
      signIn: "Mag-Sign In",
      premiumTag: "Premium IPTV Experience",
      language: "Wika",
    },
    login: {
      ...en.translation.login,
      subtitle: "Subscriber Sign-In",
      submit: "Mag-Sign In",
      submitting: "Nag-sa-sign in...",
      contactAdmin:
        "Walang account? Makipag-ugnayan sa iyong NADIPLAYER administrator.",
      back: "Bumalik",
    },
    home: {
      ...en.translation.home,
      logout: "Mag-Log Out",
      profile: "Profile",
      guestMode: "Guest Mode",
      connected: "Nakakonekta.",
      awaiting: "Naghihintay ng server sync.",
      waiting: "Naghihintay na kumonekta.",
      subscriber: "Subscriber",
      expires: "Mag-e-expire",
      noExpiry: "Walang takdang expiry",
      daysRemaining_one: "{{count}} araw na natitira",
      daysRemaining_other: "{{count}} araw na natitira",
      expired: "EXPIRED",
      categories: {
        ...en.translation.home.categories,
        liveTv: "Live TV",
        movies: "Pelikula",
        series: "Series",
        liveTvCount: "+5000 Channel",
        moviesCount: "+1200 Pelikula",
        seriesCount: "+500 Series",
      },
      infoBar: "LIVE: +5000 Channel. PELIKULA: +1200. SERIES: +500.",
    },
    expired: {
      ...en.translation.expired,
      title: "EXPIRED ANG SUBSCRIPTION",
      hi: "Hi",
      message:
        "Natapos na ang iyong NADIPLAYER subscription. Makipag-ugnayan sa WhatsApp upang mag-renew.",
      contactWhatsapp: "Customer Support",
      signOut: "Mag-Sign Out",
      whatsappPrefill:
        "Hi, expired na ang aking NADIPLAYER subscription ({{username}}). Gusto kong mag-renew.",
    },
    splash: { tagline: "I-tune in sa Sanlibutan", premiumTag: "Premium IPTV Experience" },
    firstRun: {
      title: "Pumili ng iyong wika",
      subtitle: "Gamitin ang ← → para magpalit ng flag, pagkatapos ay pindutin ang Magpatuloy",
      continue: "Magpatuloy",
      hint: "Maaari mo itong palitan mamaya sa Settings",
    },
    update: {
      titleNormal: "May bagong update",
      titleForced: "Kailangan ng update",
      forcedNotice: "Kailangang i-install ang pinakabagong bersyon para magpatuloy sa paggamit ng app.",
      adminPreview:
        "Admin preview. Ang popup na ito ay sapilitan para sa mga regular na user (naka-install v{{installed}} < min v{{min}}). Maaari mong i-dismiss ng walang problema — hindi naka-lock ang mga admin.",
      loginPreview:
        "Laging maa-access ang login para ma-update ng admin ang bersyon ng app. Pindutin ang \"Mamaya\" para magpatuloy sa login form.",
      needPermission:
        "Paki-enable ang \"Allow install from this source\" para sa Nadiplayer sa screen na binuksan natin, pagkatapos ay bumalik at pindutin ulit ang button.",
      installerOpened: "Bukas na ang installer. Sundin ang on-screen na panuto upang i-install.",
      whatsNew: "Ano ang bago",
      noUrl: "Walang naka-configure na download link. Kontakin ang admin.",
      downloadingPercent: "Nagda-download {{percent}}%…",
      downloading: "Nagda-download…",
      openingInstaller: "Binubuksan ang installer…",
      allowInstallRetry: "Payagan ang install — subukan muli",
      installerLaunched: "Pinagana ang installer",
      retry: "Subukan muli ang update",
      updateNow: "Mag-update ngayon",
      downloadUpdate: "I-download ang update",
      openInPlayStore: "Buksan sa Play Store",
      later: "Mamaya",
      closeAria: "Isara ang update notice",
    },
    notFound: {
      ...en.translation.notFound,
      message: "Hindi nahanap ang pahina",
      goHome: "Bumalik sa home",
    },
    liveTV: {
      ...en.translation.liveTV,
      title: "LIVE TV",
      searchPlaceholder: "Hanapin ang channel…",
      noActiveServer: "Walang aktibong server.",
      addProfile: "Magdagdag ng profile",
      favs: "Favs",
      selectChannel: "Pumili ng channel",
      noChannels: "Walang nakitang channel.",
      channels_one: "{{count}} channel",
      channels_other: "{{count}} channels",
    },
    movies: {
      ...en.translation.movies,
      title: "MGA PELIKULA",
      searchPlaceholder: "Hanapin ang pelikula...",
      noActiveServer: "Walang aktibong server.",
      addProfile: "Magdagdag ng profile",
      failedLoad: "Hindi ma-load ang mga pelikula.",
    },
    series: {
      ...en.translation.series,
      title: "SERIES",
      searchPlaceholder: "Hanapin ang series...",
      noActiveServer: "Walang aktibong server.",
      addProfile: "Magdagdag ng profile",
      failedLoad: "Hindi ma-load ang series.",
      season: "Season {{n}}",
    },
    addServer: {
      ...en.translation.addServer,
      title: "MAGDAGDAG NG PLAYLIST",
      advanced: "Advanced",
      shared: "Shared",
      ownServer: "Sariling server",
    },
    admin: {
      ...en.translation.admin,
      subtitle: "Subscriber Control Panel",
      settingsHeading: "GLOBAL SETTINGS",
      createHeading: "GUMAWA NG SUBSCRIBER",
      subscribersHeading: "MGA SUBSCRIBER ({{count}})",
      createUser: "Gumawa ng user",
      saveSettings: "I-save",
    },
    account: {
      ...en.translation.account,
      title: "ACCOUNT",
      addServer: "Magdagdag ng server",
      devicePairing: "Pairing ng Device",
      playbackMode: "Playback Mode",
      externalPlayer: "External Player",
      playerIdentity: "Identity ng Player",
    },
    premium: {
      ...en.translation.premium,
      goldBadge: "Premium Account",
      adFreeTag: "Walang ads",
      daysRemaining_one: "{{count}} araw natitira",
      daysRemaining_other: "{{count}} araw natitira",
      expiresOn: "Mag-e-expire sa",
      expiredTitle: "Expired ang subscription",
      renewNow: "I-renew ngayon",
      haveSubscription: "Mayroon na akong subscription · Mag-Sign in",
      upgradePitch:
        "Mag-upgrade sa Premium Account para tamasahin ang karanasang walang ads at mga eksklusibong feature.",
      adminBadge: "Administrator account",
      adminHint: "Buo ang access, walang ads.",
      premiumSubscriber: "Premium Subscriber",
    },
  },
};

// Romanian
const ro = {
  translation: {
    ...en.translation,
    welcome: {
      ...en.translation.welcome,
      chooseHowToContinue: "Alege cum vrei să continui",
      guest: "INVITAT",
      guestHint: "Intră cu propriul tău server Xtream — gestionează totul local.",
      enter: "Intră",
      login: "AUTENTIFICARE",
      loginHint:
        "Abonați: autentifică-te cu utilizatorul și parola primite de la administrator.",
      signIn: "Autentificare",
      premiumTag: "Experiență IPTV Premium",
      language: "Limbă",
    },
    menu: {
      title: "Meniu",
      home: "Acasă",
      liveTv: "TV Live",
      movies: "Filme",
      series: "Seriale",
      account: "Cont",
      settings: "Setări",
      open: "Deschide meniul",
      close: "Închide meniul",
    },
    login: {
      ...en.translation.login,
      subtitle: "Autentificare abonat",
      submit: "Autentificare",
      submitting: "Se autentifică...",
      contactAdmin:
        "Nu ai cont? Contactează administratorul NADIPLAYER pentru credențiale.",
      back: "Înapoi",
    },
    home: {
      ...en.translation.home,
      logout: "Deconectare",
      profile: "Profil",
      guestMode: "Mod invitat",
      connected: "Conectat.",
      awaiting: "Se așteaptă sincronizarea.",
      waiting: "Se așteaptă conexiunea.",
      subscriber: "Abonat",
      expires: "Expiră la",
      noExpiry: "Fără dată de expirare",
      daysRemaining_one: "{{count}} zi rămasă",
      daysRemaining_other: "{{count}} zile rămase",
      expired: "EXPIRAT",
      categories: {
        ...en.translation.home.categories,
        liveTv: "TV Live",
        movies: "Filme",
        series: "Seriale",
        liveTvCount: "+5000 canale",
        moviesCount: "+1200 filme",
        seriesCount: "+500 seriale",
      },
      infoBar: "LIVE: +5000 canale. FILME: +1200. SERIALE: +500.",
    },
    expired: {
      ...en.translation.expired,
      title: "ABONAMENT EXPIRAT",
      hi: "Salut",
      message:
        "Abonamentul NADIPLAYER s-a încheiat. Pentru a continua, contactează-ne pe WhatsApp pentru reînnoire.",
      contactWhatsapp: "Asistență clienți",
      signOut: "Deconectare",
      whatsappPrefill:
        "Salut, abonamentul meu NADIPLAYER ({{username}}) a expirat. Aș dori să-l reînnoiesc.",
    },
    splash: { tagline: "Conectează-te la univers", premiumTag: "Experiență IPTV Premium" },
    firstRun: {
      title: "Alege limba",
      subtitle: "Folosește ← → pentru a schimba steagul, apoi apasă Continuă",
      continue: "Continuă",
      hint: "Poți schimba mai târziu din Setări",
    },
    notFound: {
      ...en.translation.notFound,
      message: "Hopa! Pagina nu a fost găsită",
      goHome: "Înapoi la pagina principală",
    },
    liveTV: {
      ...en.translation.liveTV,
      title: "TV LIVE",
      searchPlaceholder: "Caută canale…",
      noActiveServer: "Niciun server activ.",
      addProfile: "Adaugă un profil",
      favs: "Favorite",
      selectChannel: "Selectează un canal",
      noChannels: "Nu s-au găsit canale.",
      channels_one: "{{count}} canal",
      channels_other: "{{count}} canale",
    },
    movies: {
      ...en.translation.movies,
      title: "FILME",
      searchPlaceholder: "Caută filme...",
      noActiveServer: "Niciun server activ.",
      addProfile: "Adaugă un profil",
      failedLoad: "Nu s-au putut încărca filmele.",
    },
    series: {
      ...en.translation.series,
      title: "SERIALE",
      searchPlaceholder: "Caută seriale...",
      noActiveServer: "Niciun server activ.",
      addProfile: "Adaugă un profil",
      failedLoad: "Nu s-au putut încărca serialele.",
      season: "Sezonul {{n}}",
    },
    addServer: {
      ...en.translation.addServer,
      title: "ADAUGĂ PLAYLIST",
      advanced: "Avansat",
      shared: "Partajat",
      ownServer: "Server propriu",
    },
    admin: {
      ...en.translation.admin,
      subtitle: "Panou de control abonați",
      settingsHeading: "SETĂRI GLOBALE",
      createHeading: "CREEAZĂ ABONAT",
      subscribersHeading: "ABONAȚI ({{count}})",
      createUser: "Creează utilizator",
      saveSettings: "Salvează",
    },
    account: {
      ...en.translation.account,
      title: "CONT",
      addServer: "Adaugă server",
      devicePairing: "Asociere dispozitiv",
      playbackMode: "Mod redare",
      externalPlayer: "Player extern",
      playerIdentity: "Identitate player",
    },
    premium: {
      ...en.translation.premium,
      goldBadge: "Cont Premium",
      adFreeTag: "Fără reclame",
      daysRemaining_one: "{{count}} zi rămasă",
      daysRemaining_other: "{{count}} zile rămase",
      expiresOn: "Expiră la",
      expiredTitle: "Abonament expirat",
      renewNow: "Reînnoiește acum",
      haveSubscription: "Am deja un abonament · Autentificare",
      upgradePitch:
        "Trecerea la un cont Premium îți oferă o experiență fără reclame și funcții exclusive.",
      adminBadge: "Cont administrator",
      adminHint: "Toate funcțiile deblocate, fără reclame.",
      premiumSubscriber: "Abonat Premium",
      welcomeMessage:
        "Folosești versiunea Premium! Bucură-te de o experiență fără reclame, accelerare hardware avansată pentru suport 4K și asistență tehnică prioritară. (Notă: NadiPlayer este doar un player media; nu sunt furnizate conținut sau liste de redare).",
    },
    noServer: {
      title: "Treci la Premium",
      titleSubscriber: "Adaugă un profil",
      alreadySubscribed: "Ai deja un abonament?",
      upgradeNow: "Upgrade acum",
      signIn: "Autentificare",
      or: "sau",
      addOwnProfile: "Adaugă un profil",
      addOwnHint: "Folosește propriile credențiale Xtream / M3U / Stalker.",
      subscriberHint:
        "Conectează propriile credențiale Xtream Codes, lista M3U sau portalul Stalker pentru a începe să vizionezi.",
    },
    upgrade: {
      tag: "Activare Premium",
      title: "TRECI LA PREMIUM",
      intro:
        "Premium îți oferă o experiență fără reclame și funcții exclusive. Activarea se face în afara aplicației.",
      howToTitle: "Cum faci upgrade",
      instructions: "Vizitează",
      toActivate: "pentru a activa.",
      fromBrowser: "din browser.",
      scanHint:
        "Sau scanează codul QR cu telefonul — deschide pagina de activare direct.",
      deviceInfo: "Identificatorii dispozitivului tău",
      macAddress: "Adresă MAC",
      deviceId: "ID dispozitiv",
      devicePin: "PIN dispozitiv",
      pairingHint:
        "Folosește adresa MAC și PIN-ul dispozitivului pe site pentru a asocia acest dispozitiv abonamentului tău.",
      deviceHint:
        "Furnizează acești identificatori pe site la cerere — ne permit să asociem activarea Premium acestui dispozitiv.",
      recheck: "Reverifică abonamentul",
      compliance: "Fără achiziții în aplicație · Activare prin site",
    },
    trial: {
      expiredTitle: "PERIOADA DE PROBĂ EXPIRATĂ",
      expiredDescription:
        "Perioada ta de probă gratuită de 30 de zile a expirat. Treci la un cont Premium de 1 an pentru a continua fără reclame.",
      daysUsed: "{{used}} zile folosite · început la {{date}}",
      loginAlready: "Am deja un abonament · Autentificare",
      upgradeInfo: "Info upgrade și ID dispozitiv",
      visitWebsiteHint:
        "Pentru a trece la Premium și a elimina reclamele, vizitează site-ul nostru",
      fromBrowser: "din browser.",
      recheck: "Reverifică abonamentul",
      footnote: "Fără achiziții în aplicație · Activare prin site",
    },
  },
};

// German
const de = {
  translation: {
    ...en.translation,
    welcome: {
      ...en.translation.welcome,
      chooseHowToContinue: "Wähle, wie du fortfahren möchtest",
      guest: "GAST",
      guestHint: "Mit eigenem Xtream-Server eintreten — alles lokal verwalten.",
      enter: "Eintreten",
      login: "ANMELDUNG",
      loginHint:
        "Abonnenten: Mit den Zugangsdaten deines Administrators anmelden.",
      signIn: "Anmelden",
      premiumTag: "Premium IPTV-Erlebnis",
      language: "Sprache",
    },
    login: {
      ...en.translation.login,
      subtitle: "Abonnenten-Anmeldung",
      submit: "Anmelden",
      submitting: "Wird angemeldet...",
      contactAdmin:
        "Kein Konto? Wende dich an deinen NADIPLAYER-Administrator für Zugangsdaten.",
      back: "Zurück",
    },
    home: {
      ...en.translation.home,
      logout: "Abmelden",
      profile: "Profil",
      guestMode: "Gastmodus",
      connected: "Verbunden.",
      awaiting: "Warte auf Server-Sync.",
      waiting: "Warte auf Verbindung.",
      subscriber: "Abonnent",
      expires: "Läuft ab am",
      noExpiry: "Kein Ablaufdatum",
      daysRemaining_one: "Noch {{count}} Tag",
      daysRemaining_other: "Noch {{count}} Tage",
      expired: "ABGELAUFEN",
      categories: {
        ...en.translation.home.categories,
        liveTv: "Live TV",
        movies: "Filme",
        series: "Serien",
        liveTvCount: "+5000 Kanäle",
        moviesCount: "+1200 Filme",
        seriesCount: "+500 Serien",
      },
      infoBar: "LIVE: +5000 Kanäle. FILME: +1200. SERIEN: +500.",
    },
    expired: {
      ...en.translation.expired,
      title: "ABONNEMENT ABGELAUFEN",
      hi: "Hallo",
      message:
        "Dein NADIPLAYER-Abonnement ist beendet. Kontaktiere uns auf WhatsApp zur Verlängerung.",
      contactWhatsapp: "Kundensupport",
      signOut: "Abmelden",
      whatsappPrefill:
        "Hallo, mein NADIPLAYER-Abonnement ({{username}}) ist abgelaufen. Ich möchte verlängern.",
    },
    splash: { tagline: "Stelle dich auf das Universum ein", premiumTag: "Premium IPTV-Erlebnis" },
    firstRun: {
      title: "Wähle deine Sprache",
      subtitle: "Mit ← → Flaggen wechseln, dann auf Weiter drücken",
      continue: "Weiter",
      hint: "Du kannst dies später in den Einstellungen ändern",
    },
    notFound: {
      ...en.translation.notFound,
      message: "Ups! Seite nicht gefunden",
      goHome: "Zur Startseite",
    },
    liveTV: {
      ...en.translation.liveTV,
      title: "LIVE TV",
      searchPlaceholder: "Kanäle suchen…",
      noActiveServer: "Kein aktiver Server.",
      addProfile: "Profil hinzufügen",
      favs: "Favoriten",
      selectChannel: "Kanal auswählen",
      noChannels: "Keine Kanäle gefunden.",
      channels_one: "{{count}} Kanal",
      channels_other: "{{count}} Kanäle",
    },
    movies: {
      ...en.translation.movies,
      title: "FILME",
      searchPlaceholder: "Filme suchen...",
      noActiveServer: "Kein aktiver Server.",
      addProfile: "Profil hinzufügen",
      failedLoad: "Filme konnten nicht geladen werden.",
    },
    series: {
      ...en.translation.series,
      title: "SERIEN",
      searchPlaceholder: "Serien suchen...",
      noActiveServer: "Kein aktiver Server.",
      addProfile: "Profil hinzufügen",
      failedLoad: "Serien konnten nicht geladen werden.",
      season: "Staffel {{n}}",
    },
    addServer: {
      ...en.translation.addServer,
      title: "PLAYLIST HINZUFÜGEN",
      advanced: "Erweitert",
      shared: "Geteilt",
      ownServer: "Eigener Server",
    },
    admin: {
      ...en.translation.admin,
      subtitle: "Abonnenten-Steuerpanel",
      settingsHeading: "GLOBALE EINSTELLUNGEN",
      createHeading: "ABONNENT ERSTELLEN",
      subscribersHeading: "ABONNENTEN ({{count}})",
      createUser: "Benutzer erstellen",
      saveSettings: "Speichern",
    },
    account: {
      ...en.translation.account,
      title: "KONTO",
      addServer: "Server hinzufügen",
      devicePairing: "Gerät koppeln",
      playbackMode: "Wiedergabemodus",
      externalPlayer: "Externer Player",
      playerIdentity: "Player-Identität",
    },
    premium: {
      ...en.translation.premium,
      goldBadge: "Premium-Konto",
      adFreeTag: "Werbefrei",
      daysRemaining_one: "Noch {{count}} Tag",
      daysRemaining_other: "Noch {{count}} Tage",
      expiresOn: "Läuft ab am",
      expiredTitle: "Abonnement abgelaufen",
      renewNow: "Jetzt verlängern",
      haveSubscription: "Ich habe bereits ein Abo · Anmelden",
      upgradePitch:
        "Aktualisiere auf ein Premium-Konto für ein werbefreies Erlebnis und exklusive Funktionen.",
      adminBadge: "Administrator-Konto",
      adminHint: "Alle Funktionen freigeschaltet, keine Werbung.",
      premiumSubscriber: "Premium-Abonnent",
    },
  },
};

const resources = { en, ar, fr, es, ro, de, ru, ko, fil };

void i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    fallbackLng: "en",
    supportedLngs: LANGUAGES.map((l) => l.code),
    interpolation: { escapeValue: false },
    detection: {
      order: ["localStorage", "navigator"],
      lookupLocalStorage: "nadiplay_lang",
      caches: ["localStorage"],
    },
  });

// Apply RTL/LTR dir on <html>
const applyDir = (lng: string) => {
  const entry = LANGUAGES.find((l) => l.code === lng);
  if (typeof document !== "undefined") {
    document.documentElement.dir = entry?.dir ?? "ltr";
    document.documentElement.lang = lng;
  }
};
applyDir(i18n.language || "en");
i18n.on("languageChanged", applyDir);

export default i18n;
