/* global window */
// ─────────────────────────────────────────────────────────
// Senan Clinic — i18n Translation Dictionary (AR ↔ EN)
// Usage:  window.T('key')  →  translated string
//         window.T('key', 'Fallback')
// ─────────────────────────────────────────────────────────

window._senanLang = localStorage.getItem('senan-lang') || 'ar';

const AR = {}; // identity — Arabic keys ARE the source
const EN = {
  // ── Navigation ──────────────────────────────────────────
  'لوحة التحكم':            'Dashboard',
  'الاستقبال':              'Reception',
  'الجلسات':               'Sessions',
  'المرضى':                'Patients',
  'الفواتير والمدفوعات':    'Billing & Payments',
  'تذكيرات واتساب':        'WhatsApp Reminders',
  'الطلبات المخبرية':      'Lab Orders',
  'المحاسبة':              'Accounting',
  'التسعير والربحية':       'Pricing & Profitability',
  'المخزون والخدمات':       'Inventory & Services',
  'التأمين الطبي':          'Medical Insurance',
  'التقارير':              'Reports',
  'الموظفين':              'Staff',
  'بوابة المريض':           'Patient Portal',
  'الإعدادات':             'Settings',
  'العمليات اليومية':       'Daily Operations',
  'الإدارة المالية':        'Financial Management',
  'النظام والتحليل':        'System & Analytics',
  'إدارة عيادة متكاملة':    'Integrated Clinic Management',

  // ── Common UI ────────────────────────────────────────────
  'حفظ':                   'Save',
  'إلغاء':                 'Cancel',
  'تأكيد':                 'Confirm',
  'حذف':                   'Delete',
  'تعديل':                 'Edit',
  'إضافة':                 'Add',
  'إضافة جديد':            'Add New',
  'بحث':                   'Search',
  'تحميل':                 'Loading',
  'جاري التحميل...':       'Loading...',
  'لا توجد بيانات':         'No data',
  'طباعة':                 'Print',
  'تصدير':                 'Export',
  'نسخ':                   'Copy',
  'مسح':                   'Clear',
  'تحديث':                 'Refresh',
  'إغلاق':                 'Close',
  'تسجيل الخروج':          'Sign Out',
  'هل تريد تسجيل الخروج؟': 'Are you sure you want to sign out?',
  'نعم':                   'Yes',
  'لا':                    'No',
  'حضر الآن':              'Walk-In',
  'موعد جديد':             'New Appointment',
  'مريض جديد':             'New Patient',
  'فاتورة جديدة':          'New Invoice',

  // ── Status ───────────────────────────────────────────────
  'مكتمل':                 'Completed',
  'مكتملة':                'Completed',
  'قيد الانتظار':          'Pending',
  'ملغي':                  'Cancelled',
  'ملغية':                 'Cancelled',
  'مدفوع':                 'Paid',
  'مدفوعة':                'Paid',
  'غير مدفوع':             'Unpaid',
  'جارية':                 'In Progress',
  'جاري':                  'In Progress',
  'منتهي':                 'Expired',
  'نشط':                   'Active',
  'موقوف':                 'Suspended',
  'جديد':                  'New',
  'مكتمل جزئيًا':          'Partially Paid',

  // ── Dashboard ─────────────────────────────────────────────
  'إيراد اليوم':           'Today\'s Revenue',
  'فواتير اليوم':          'Today\'s Invoices',
  'مواعيد اليوم':          'Today\'s Appointments',
  'مخزون منخفض':           'Low Stock',
  'إيراد هذا الشهر':       'This Month\'s Revenue',
  'مرضى الشهر':            'Month Patients',
  'نسبة التحصيل':          'Collection Rate',
  'إجمالي المديونيات':     'Total Receivables',
  'أداء هذا الأسبوع':      'This Week\'s Performance',
  'آخر 7 أيام':            'Last 7 Days',

  // ── Reports ───────────────────────────────────────────────
  'التقارير والتحليلات':   'Reports & Analytics',
  'فترة التقرير':          'Report Period',
  'اضغط أي شريط للتصفية الفورية': 'Click any bar to instantly filter',
  'تصفية حسب:':            'Filtered by:',
  'مسح ×':                 'Clear ×',
  'تصفية نشطة':            'Filter active',
  '💰 المالية':            '💰 Financial',
  '👥 المرضى':             '👥 Patients',
  '⚕️ الخدمات':           '⚕️ Services',
  '📋 يومي':              '📋 Daily',
  'إجمالي الإيرادات':      'Total Revenue',
  'إجمالي التحصيل':        'Total Collections',
  'الرصيد الصافي':         'Net Balance',
  'إجمالي المصروفات':      'Total Expenses',
  'عمولات الأطباء':        'Doctor Commissions',
  'مرضى نشطون':            'Active Patients',
  'جلسات مكتملة':          'Completed Sessions',
  'خدمات مقدمة':           'Services Rendered',
  'الإيرادات الأسبوعية':   'Weekly Revenue',
  'آخر 8 أسابيع':          'Last 8 weeks',
  'الاستحقاق':             'Billed',
  'التحصيل':               'Collected',
  'الإيرادات حسب الطبيب': 'Revenue by Doctor',
  'انقر للتصفية':          'Click to filter',
  'لا توجد بيانات — اربط الطبيب بالفاتورة': 'No data — link doctor to invoice',
  'توزيع المصروفات':       'Expense Breakdown',
  'لا توجد مصروفات في هذه الفترة': 'No expenses in this period',
  'أكثر الخدمات إيراداً':  'Top Revenue Services',
  'لا توجد فواتير':         'No invoices',
  'إجمالي المرضى':         'Total Patients',
  'مرضى جدد (الفترة)':    'New Patients (Period)',
  'متوسط الزيارات':        'Avg. Visits',
  'أكثر المرضى زيارة':     'Most Visited Patients',
  'لا توجد مواعيد مكتملة في هذه الفترة': 'No completed appointments in this period',
  'المريض':                'Patient',
  'الإيرادات':             'Revenue',
  'الجلسات':               'Sessions',
  'المديونيات':            'Receivables',
  'لا توجد مديونيات':      'No receivables',
  'المرضى حسب الطبيب':    'Patients by Doctor',
  'أضف الطبيب المعالج في ملف المريض': 'Add treating doctor in patient profile',
  'التوزيع حسب المنطقة':  'Distribution by Region',
  'أضف العنوان في ملف المريض': 'Add address in patient profile',
  'توزيع النوع':           'Gender Distribution',
  'ذكر':                   'Male',
  'أنثى':                  'Female',
  'التوزيع العمري':        'Age Distribution',
  'أداء الخدمات':          'Service Performance',
  'الخدمة':                'Service',
  'الإيراد':               'Revenue',
  'العدد':                 'Count',
  'متوسط السعر':           'Avg. Price',
  'لا توجد بيانات خدمات': 'No service data',
  'ملخص يومي — آخر 14 يوم': 'Daily Summary — Last 14 Days',
  'لا توجد بيانات في هذه الفترة': 'No data in this period',
  'اليوم':                 'Today',
  'أمس':                   'Yesterday',
  'الفواتير':              'Invoices',
  'الخدمات والجلسات والمرضى يومياً': 'Daily Patients, Sessions & Invoices',
  'انقر يوم لعرض تفاصيل المرضى': 'Click a day to view patient details',
  'لا توجد فواتير في هذه الفترة': 'No invoices in this period',
  'المريض':                'Patient',
  'الطبيب':                'Doctor',
  'المديونية':             'Balance Due',
  'الحالة':                'Status',
  'مواعيد الغد':           'Tomorrow\'s Appointments',
  'لا توجد مواعيد':        'No appointments',
  'مخزون منخفض':           'Low Stock',
  'كل الأصناف بمستوى كافٍ': 'All items at sufficient levels',
  'ملخص للواتساب':         'WhatsApp Summary',
  'ربح ✅':                'Profit ✅',
  'خسارة 🚨':             'Loss 🚨',

  // ── Accounting ───────────────────────────────────────────
  'الإيرادات':             'Revenue',
  'المدفوعات':             'Payments',
  'المصروفات':             'Expenses',
  'الرواتب':               'Salaries',
  'مصروفات متنوعة':        'Miscellaneous Expenses',
  'المخزون والمشتريات':    'Inventory & Purchases',
  'صافي الربح':            'Net Profit',
  'نسبة الهامش':           'Margin Rate',
  'إجمالي التحصيل':        'Total Collections',
  'إجمالي المدفوعات':      'Total Payments',
  'ذمم مدينة':             'Accounts Receivable',

  // ── Patients ─────────────────────────────────────────────
  'بحث عن مريض':          'Search for patient',
  'الاسم':                 'Name',
  'الهاتف':                'Phone',
  'العمر':                 'Age',
  'الجنس':                 'Gender',
  'المنطقة':               'Region',
  'الطبيب المعالج':        'Treating Doctor',
  'تاريخ الإضافة':         'Date Added',
  'آخر زيارة':             'Last Visit',
  'ملف المريض':            'Patient File',
  'السجل الطبي':           'Medical Record',
  'مخطط الأسنان':          'Dental Chart',
  'الأشعة':                'X-Rays',
  'المستندات':             'Documents',
  'الوصفات':               'Prescriptions',
  'التاريخ المرضي':        'Medical History',

  // ── Appointments ─────────────────────────────────────────
  'جدول المواعيد':         'Appointment Schedule',
  'موعد':                  'Appointment',
  'التاريخ':               'Date',
  'الوقت':                 'Time',
  'النوع':                 'Type',
  'الغرفة':                'Room',
  'الدكتور':               'Doctor',
  'تأكيد':                 'Confirm',
  'إلغاء الموعد':          'Cancel Appointment',
  'إتمام الجلسة':          'Complete Session',
  'غائب':                  'Absent',

  // ── Billing / Invoices ───────────────────────────────────
  'فاتورة':                'Invoice',
  'الخدمات':               'Services',
  'الإجمالي':              'Total',
  'المدفوع':               'Paid',
  'المتبقي':               'Balance',
  'خصم':                   'Discount',
  'إيصال':                 'Receipt',
  'تفاصيل الفاتورة':       'Invoice Details',
  'طريقة الدفع':           'Payment Method',
  'نقدي':                  'Cash',
  'بطاقة':                 'Card',
  'تحويل':                 'Transfer',

  // ── Inventory ────────────────────────────────────────────
  'الصنف':                 'Item',
  'الفئة':                 'Category',
  'الكمية':                'Quantity',
  'الحد الأدنى':           'Min. Level',
  'الوحدة':                'Unit',
  'المورد':                'Supplier',
  'تاريخ الانتهاء':        'Expiry Date',
  'في المخزون':            'In Stock',
  'منخفض':                 'Low',
  'نفد من المخزون':        'Out of Stock',

  // ── Pricing / Services ───────────────────────────────────
  'تسعير الخدمات':         'Service Pricing',
  'اسم الخدمة':            'Service Name',
  'السعر':                 'Price',
  'المدة':                 'Duration',
  'التكلفة':               'Cost',
  'الربح':                 'Profit',
  'هامش الربح':            'Profit Margin',
  'تكاليف مواد':           'Material Costs',
  'الربحية':               'Profitability',

  // ── Staff / Doctors ──────────────────────────────────────
  'اسم الطبيب':            'Doctor Name',
  'التخصص':               'Specialty',
  'نسبة العمولة':          'Commission Rate',
  'موظف':                  'Staff Member',
  'دوام':                  'Schedule',

  // ── Settings ─────────────────────────────────────────────
  'اسم العيادة':           'Clinic Name',
  'المظهر':                'Appearance',
  'اللغة':                 'Language',
  'المنطقة الزمنية':       'Timezone',
  'الكثافة':               'Density',
  'مدمجة':                 'Compact',
  'مريحة':                 'Comfortable',
  'الدعم الفني':           'Technical Support',

  // ── Date/Time ────────────────────────────────────────────
  'اليوم':                 'Today',
  'أمس':                   'Yesterday',
  'هذا الأسبوع':           'This Week',
  'الأسبوع الماضي':        'Last Week',
  'هذا الشهر':             'This Month',
  'الشهر الماضي':          'Last Month',
  'هذا العام':             'This Year',
  'كل الفترات':            'All Time',
  'من':                    'From',
  'إلى':                   'To',
  'تطبيق':                 'Apply',
  'فترة مخصصة':            'Custom Range',

  // ── Misc ─────────────────────────────────────────────────
  'غير محدد':              'Not Set',
  'بدون طبيب':             'No Doctor',
  'بدون مريض':             'No Patient',
  'مريض':                  'patient',
  'جلسة':                  'session',
  'فاتورة':                'invoice',
  'ج.م':                   'EGP',
  'ممتاز':                 'Excellent',
  'مقبول':                 'Acceptable',
  'يحتاج تدخل':            'Needs Attention',
  'طبيب':                  'Doctor',
  'خدمة':                  'Service',
  'أخرى':                  'Other',
  'إجمالي':                'Total',
};

/**
 * Translate a string based on current language setting.
 * Falls back to the key itself if no translation found.
 */
window.T = function(key, fallback) {
  const lang = window._senanLang || localStorage.getItem('senan-lang') || 'ar';
  if (lang === 'ar') return key; // Arabic is the source language
  const dict = EN;
  return dict[key] !== undefined ? dict[key] : (fallback !== undefined ? fallback : key);
};

/**
 * Update language globally. Saves current screen then reloads the page
 * so ALL screens re-render in the new language from scratch.
 */
window._setSenanLang = function(lang, currentScreen) {
  localStorage.setItem('senan-lang', lang);
  if (currentScreen) localStorage.setItem('senan-lang-screen', currentScreen);
  document.documentElement.dir  = lang === 'ar' ? 'rtl' : 'ltr';
  document.documentElement.lang = lang;
  window._senanLang = lang;
  // Short delay so the React state update has time to save, then reload
  setTimeout(() => window.location.reload(), 60);
};

// Apply saved lang on script load
(function() {
  const saved = localStorage.getItem('senan-lang') || 'ar';
  window._senanLang = saved;
  document.documentElement.dir  = saved === 'ar' ? 'rtl' : 'ltr';
  document.documentElement.lang = saved;
})();
