import {
  createContext,
  ReactNode,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from "react";

/**
 * Supported UI languages.
 * - `en`: English, left-to-right.
 * - `ar`: Arabic, right-to-left.
 */
export type AppLanguage = "en" | "ar";

interface LanguageContextValue {
  lang: AppLanguage;
  dir: "ltr" | "rtl";
  setLang: (lang: AppLanguage) => void;
  toggleLang: () => void;
  /**
   * Translate a key using the built-in catalog. If the key is not found,
   * the key itself is returned — so strings that have not yet been
   * translated still render in plain English rather than blank.
   */
  t: (key: string) => string;
  /**
   * Translate an already-English string. We build the reverse lookup from
   * the `en` catalog at startup so components can pass their existing
   * English copy directly: `<span>{tr("Get Started")}</span>` and still
   * get the Arabic equivalent when available. Unknown strings are
   * returned unchanged.
   */
  tr: (englishString: string) => string;
}

const STORAGE_KEY = "doiteasy.lang";

/**
 * Full translation catalog.
 *
 * The English catalog is the source of truth. We expose translations via:
 *   - `t("key")` — structured key lookup (used by components opting in).
 *   - `tr("English sentence")` — reverse lookup using the English value
 *     as the key. Any component already rendering plain English can call
 *     `tr()` and get the Arabic equivalent when available.
 *
 * We also attach `TRANSLATION_MAP` (English -> Arabic) on `window` so
 * the runtime auto-translator in `SiteLayout` can swap DOM text nodes
 * for content that doesn't go through React props directly (e.g. data
 * coming from 3rd-party widgets). The auto-translator only activates
 * when `lang === "ar"`.
 */
const CATALOG: Record<AppLanguage, Record<string, string>> = {
  en: {
    // ---------- Top-level navigation ----------
    "nav.home": "Home",
    "nav.hosting": "Hosting Services",
    "nav.cloud": "Cloud Services",
    "nav.web": "Web Services",
    "nav.shop": "Shop",
    "nav.support": "Support",
    "nav.login": "LOGIN",
    "nav.client_area": "CLIENT AREA",
    "nav.cart": "Cart",
    "nav.account": "My Account",
    "nav.sign_in": "Sign in",
    "nav.logout": "Logout",
    "nav.welcome": "Welcome",
    "nav.welcome_back": "Welcome back",
    "nav.menu": "Menu",
    "nav.close": "Close",

    // ---------- Hosting submenu ----------
    "nav.shared_hosting": "Shared Hosting",
    "nav.cpanel_hosting": "cPanel Hosting",
    "nav.plesk_hosting": "Plesk Hosting",
    "nav.aapanel_hosting": "aaPanel Hosting",
    "nav.windows_hosting": "Windows Hosting",
    "nav.wordpress_hosting": "WordPress Hosting",
    "nav.reseller_hosting": "Reseller Hosting",
    "nav.vps_hosting": "VPS Hosting",
    "nav.dedicated_servers": "Dedicated Servers",

    // ---------- Cloud submenu ----------
    "nav.cloud_hosting": "Cloud Hosting",
    "nav.cloud_servers": "Cloud Servers",
    "nav.cloud_storage": "Cloud Storage",
    "nav.cloud_backup": "Cloud Backup",

    // ---------- Web submenu ----------
    "nav.domain_registration": "Domain Registration",
    "nav.domain_transfer": "Domain Transfer",
    "nav.ssl_certificates": "SSL Certificates",
    "nav.website_builder": "Website Builder",
    "nav.email_hosting": "Email Hosting",

    // ---------- Support submenu ----------
    "nav.tickets": "Support Tickets",
    "nav.knowledge_base": "Knowledge Base",
    "nav.faq": "FAQ",
    "nav.service_catalog": "Services Catalog",
    "nav.contact": "Contact Us",
    "nav.remote_support": "Remote Support",
    "nav.uptime_monitor": "Uptime Monitor",
    "nav.about_us": "About Us",

    // ---------- Language switcher ----------
    "lang.label": "Language",
    "lang.english": "English",
    "lang.arabic": "العربية",

    // ---------- Footer ----------
    "footer.about_title": "About Doiteasy",
    "footer.terms_title": "Terms & Conditions",
    "footer.clients_title": "Clients Accounts",
    "footer.country": "Saudi Arabia",
    "footer.address_line1": "Address : Al Hawtah street 3939",
    "footer.address_line2": "Al Shifa District Code 14721",
    "footer.address_line3": "Riyadh Saudi Arabia",
    "footer.phone": "Tel : 0112018568",
    "footer.service_terms": "Services Terms",
    "footer.refund_policy": "Refund Policy",
    "footer.privacy_center": "Privacy Center",
    "footer.customer_support": "Customer Support",
    "footer.knowledge_base": "Knowledge Base",
    "footer.faq": "FAQ",
    "footer.services_catalog": "Services Catalog",
    "footer.account_dashboard": "Account Dashboard",
    "footer.new_client": "New Client",
    "footer.affiliate_program": "Affiliate Program",
    "footer.rate_us": "Rate us on Trustpilot",
    "footer.copyright": "Copyright © {year} Doiteasy All rights reserved.",
    "footer.get_it_on": "Get it on",
    "footer.google_play": "Google Play",
    "footer.app_store": "App Store",
    "footer.download_on": "Download on the",

    // ---------- Common CTAs ----------
    "cta.get_started": "Get Started",
    "cta.learn_more": "Learn More",
    "cta.view_plans": "View Plans",
    "cta.buy_now": "Buy Now",
    "cta.order_now": "Order Now",
    "cta.contact_sales": "Contact Sales",
    "cta.read_more": "Read More",
    "cta.back_to_top": "Back to top",
    "cta.try_free": "Try Free",
    "cta.start_free_trial": "Start Free Trial",
    "cta.open_ticket": "Open a Ticket",
    "cta.chat_with_us": "Chat with Us",

    // ---------- Hero (homepage) ----------
    "hero.badge": "Saudi-Hosted · 24/7 Support",
    "hero.title": "Reliable Hosting, Powerful Cloud, Simple Setup",
    "hero.subtitle":
      "High-performance hosting and cloud infrastructure, crafted for businesses that demand speed, security and uptime.",
    "hero.cta_primary": "Explore Plans",
    "hero.cta_secondary": "Talk to an Expert",
    "hero.stat_uptime": "99.9% Uptime",
    "hero.stat_support": "24/7 Support",
    "hero.stat_datacenters": "Global Data Centers",

    // ---------- Shop ----------
    "shop.title": "Shop",
    "shop.featured": "Featured Products",
    "shop.all_products": "All Products",
    "shop.categories": "Categories",
    "shop.price_range": "Price Range",
    "shop.sort_by": "Sort by",
    "shop.newest": "Newest",
    "shop.price_low": "Price: Low to High",
    "shop.price_high": "Price: High to Low",
    "shop.add_to_cart": "Add to Cart",
    "shop.out_of_stock": "Out of Stock",
    "shop.in_stock": "In Stock",
    "shop.cart_title": "Your Cart",
    "shop.cart_empty": "Your cart is empty",
    "shop.continue_shopping": "Continue Shopping",
    "shop.checkout": "Checkout",
    "shop.subtotal": "Subtotal",
    "shop.total": "Total",
    "shop.quantity": "Quantity",
    "shop.remove": "Remove",
    "shop.order_success": "Order placed successfully!",
    "shop.order_summary": "Order Summary",
    "shop.shipping_info": "Shipping Information",
    "shop.payment": "Payment",
    "shop.place_order": "Place Order",
    "shop.my_orders": "My Orders",
    "shop.order_id": "Order ID",
    "shop.order_date": "Date",
    "shop.order_status": "Status",

    // ---------- Forms / common labels ----------
    "form.name": "Name",
    "form.first_name": "First Name",
    "form.last_name": "Last Name",
    "form.email": "Email",
    "form.phone": "Phone",
    "form.company": "Company",
    "form.address": "Address",
    "form.city": "City",
    "form.country": "Country",
    "form.postal_code": "Postal Code",
    "form.subject": "Subject",
    "form.message": "Message",
    "form.password": "Password",
    "form.confirm_password": "Confirm Password",
    "form.submit": "Submit",
    "form.cancel": "Cancel",
    "form.save": "Save",
    "form.edit": "Edit",
    "form.delete": "Delete",
    "form.search": "Search",
    "form.required": "Required",
    "form.optional": "Optional",
    "form.loading": "Loading...",
    "form.success": "Success",
    "form.error": "An error occurred",

    // ---------- Legal / support page titles ----------
    "legal.service_terms": "Service Terms",
    "legal.refund_policy": "Refund Policy",
    "legal.privacy_center": "Privacy Center",
    "legal.last_updated": "Last updated",
    "legal.table_of_contents": "Table of Contents",
    "support.title": "Support",
    "support.need_help": "Need help?",
    "support.talk_to_expert":
      "Talk to an expert — our support team is available 24/7.",
    "support.open_ticket_desc":
      "Open a support ticket and we'll get back to you shortly.",
    "kb.title": "Knowledge Base",
    "kb.search_placeholder": "Search articles...",
    "faq.title": "Frequently Asked Questions",

    // ---------- Service catalog ----------
    "services.title": "Services Catalog",
    "services.subtitle":
      "Browse our complete lineup of hosting, cloud and managed services.",
    "services.testimonials_title": "What Our Customers Say",

    // ---------- Chat widget ----------
    "chat.title": "Live Support",
    "chat.placeholder": "Type your message...",
    "chat.send": "Send",
    "chat.online": "Online",
    "chat.offline": "Offline",

    // ---------- Generic labels ----------
    "label.new": "New",
    "label.popular": "Popular",
    "label.recommended": "Recommended",
    "label.free": "Free",
    "label.per_month": "/ month",
    "label.per_year": "/ year",
    "label.from": "From",
    "label.save": "Save",
    "label.off": "off",

    // ---------- NAV exact strings (reverse-lookup friendly) ----------
    "exact.home": "Home",
    "exact.hosting_services": "Hosting Services",
    "exact.cloud_services": "Cloud Services",
    "exact.web_services": "Web Services",
    "exact.shop": "Shop",
    "exact.support": "Support",
    "exact.shared_hosting": "Shared Hosting",
    "exact.wordpress_hosting": "WordPress Hosting",
    "exact.reseller_hosting": "Reseller Hosting",
    "exact.cloud_vps": "Cloud VPS",
    "exact.dedicated_servers": "Dedicated Servers",
    "exact.vds": "VDS",
    "exact.service_catalog": "Service Catalog",
    "exact.bizmail360": "Bizmail360 Collaboration Mail",
    "exact.business_email": "Business Email",
    "exact.cloud_managed": "Cloud Managed Services",
    "exact.whatsapp_api": "WhatsApp API Service",
    "exact.uptime_monitor": "Uptime Monitor",
    "exact.sd_wan": "SD-WAN Services",
    "exact.managed_it": "Managed IT",
    "exact.remote_support": "Remote Support",
    "exact.on_premises": "On-Premises Managed",
    "exact.domain_registration": "Domain Registration",
    "exact.knowledge_base": "Knowledge Base",
    "exact.faq": "FAQ",
    "exact.ticket_system": "Ticket System",
    "exact.contact_us": "Contact Us",
    "exact.about_us": "About Us",
    "exact.client_area": "CLIENT AREA",
    "exact.login": "LOGIN",
    "exact.logout": "Logout",
    "exact.sign_in": "Sign in",
    "exact.my_account": "My Account",
    "exact.guest_user": "Guest User",
    "exact.welcome": "Welcome",
    "exact.welcome_back": "Welcome back",
    "exact.menu": "Menu",
    "exact.cart": "Cart",
    "exact.back_to_top": "Back to top",

    // ---------- Homepage hero & body copy (reverse-lookup friendly) ----------
    "hp.hero.trusted": "Trusted by 10,000+ businesses across the Gulf",
    "hp.hero.infra_scale": "Infrastructure built for scale",
    "hp.hero.enterprise": "Enterprise-grade reliability",
    "hp.hero.dedicated_with": "Dedicated With",
    "hp.hero.confidence": "Confidence.",
    "hp.hero.virtual": "Virtual",
    "hp.hero.cloud_servers": "Cloud Servers",
    "hp.hero.managed_it_title": "Managed IT",
    "hp.hero.done_right": "Done Right.",
    "hp.hero.dedicated_desc":
      "Powerful cloud servers, dedicated hardware and managed IT services with resource exclusivity — starting at just $12.99/mo.",
    "hp.hero.vps_desc":
      "NVMe-powered Cloud VPS with per-second billing, one-click OS reinstall and 60-second provisioning through Virtualizor automation.",
    "hp.hero.managed_desc":
      "24/7 monitoring, proactive patching, secure backups and expert engineers on call — so your team can focus on the business.",
    "hp.hero.bullet.money_back": "30-day money back",
    "hp.hero.bullet.sla": "99.99% SLA",
    "hp.hero.bullet.free_migration": "Free migration",
    "hp.hero.bullet.scalability": "Immediate scalability",
    "hp.hero.bullet.performance": "High performance",
    "hp.hero.bullet.deployment": "Fast deployment",
    "hp.hero.bullet.proactive": "Proactive monitoring",
    "hp.hero.bullet.zero_downtime": "Zero-downtime migration",
    "hp.hero.bullet.247": "24/7 expert support",
    "hp.hero.btn.get_prices": "Get Prices",
    "hp.hero.btn.dedicated_servers": "Dedicated Servers",
    "hp.hero.btn.vps_servers": "VPS Servers",
    "hp.hero.btn.talk_sales": "Talk to Sales",
    "hp.hero.btn.managed_it": "Managed IT",

    // Homepage "Why" section
    "hp.why.eyebrow": "Why Choose",
    "hp.why.title": "Why Leading Businesses Pick DoItEasy",
    "hp.why.all_systems": "All systems operational",
    "hp.why.business": "BUSINESS",
    "hp.why.infrastructure": "Infrastructure",
    "hp.why.business_suite": "Business Suite",
    "hp.why.cloud_vps_vds": "Cloud VPS, VDS & Dedicated",
    "hp.why.client_portal": "Client Portal",
    "hp.why.free_ssl": "Free SSL + DDoS Protection",
    "hp.why.builtin_ticket": "Built-in Ticketing & SLA Tracking",
    "hp.why.manage_desc": "Manage all your services from one unified dashboard",
    "hp.why.managing": "Managing Your Services",
    "hp.why.mfa": "Protected by MFA & Zero-Trust",
    "hp.why.recent_tickets": "Recent Tickets",
    "hp.why.remember_me": "Remember me",
    "hp.why.security": "Security Shield",
    "hp.why.support_sla": "Support & SLA",

    // Homepage managing-features section
    "hp.mf.proactive_title": "Proactive Monitoring & 24/7 Support",
    "hp.mf.proactive_desc":
      "Real-time alerts (including mobile WhatsApp notifications), rapid response, and issue resolution before they impact operations.",
    "hp.mf.email_migration_title": "Business Email Migration",
    "hp.mf.email_migration_desc":
      "Zero-downtime migrations between Exchange / Microsoft 365, Google Workspace, SmarterMail, and IMAP — mailbox data, calendars, contacts, and DNS cutover.",
    "hp.mf.tenant_title": "Cloud Tenant Management",
    "hp.mf.tenant_desc":
      "Managing Microsoft Azure and Google Cloud tenants: identity & access (AAD/IAM), cost control, networking, backups, and policy baselines.",
    "hp.mf.remote_title": "Remote Support",
    "hp.mf.remote_desc":
      "Secure remote assistance for servers and endpoints to investigate, troubleshoot, and remediate issues quickly.",
    "hp.mf.enduser_title": "End-User Support",
    "hp.mf.enduser_desc":
      "Helpdesk for your team: onboarding, email & device setup, desktop apps, password resets, and day-to-day assistance.",
    "hp.mf.optim_title": "Server & Cloud Optimization",
    "hp.mf.optim_desc":
      "Performance tuning, capacity planning, security patching, and automated upgrades.",
    "hp.mf.security_title": "Data Security & Backup",
    "hp.mf.security_desc":
      "Hardened configurations, WAF/anti-bot, backup strategies, and disaster recovery.",
    "hp.mf.scalable_title": "Scalable Solutions",
    "hp.mf.scalable_desc":
      "From a few desktops to complex multi-region deployments — pay only for what you need.",

    // ---------- Shop cards & chrome ----------
    "shop.eyebrow": "DoItEasy Shop",
    "shop.hero_title": "Premium tech, curated for businesses",
    "shop.hero_subtitle":
      "Laptops, workstations, networking gear and accessories — hand-picked and ready to ship.",
    "shop.search_placeholder": "Search products, tags or categories...",
    "shop.no_results": "No products match your filters",
    "shop.try_clear": "Try clearing the search or adjusting the price range.",
    "shop.clear_filters": "Clear filters",
    "shop.results_count": "results",
    "shop.featured_badge": "Featured",
    "shop.new_badge": "New",
    "shop.view_details": "View Details",
    "shop.category_all": "All",
    "shop.min_price": "Min",
    "shop.max_price": "Max",
    "shop.apply": "Apply",
    "shop.reset": "Reset",

    // ---------- Cart ----------
    "cart.title": "Your Cart",
    "cart.empty_title": "Your cart is empty",
    "cart.empty_desc":
      "Looks like you haven't added anything yet. Browse the shop to get started.",
    "cart.browse_shop": "Browse Shop",
    "cart.items": "Items",
    "cart.qty": "Qty",
    "cart.unit_price": "Unit Price",
    "cart.line_total": "Line Total",
    "cart.remove": "Remove",
    "cart.proceed_checkout": "Proceed to Checkout",
    "cart.shipping_free": "Free shipping",
    "cart.shipping_calc": "Shipping calculated at checkout",
    "cart.estimated_total": "Estimated Total",

    // ---------- Checkout ----------
    "checkout.title": "Checkout",
    "checkout.signin_cta":
      "Have an account? Sign in for a faster checkout experience.",
    "checkout.guest_mode": "Guest checkout",
    "checkout.billing_email": "Billing email",
    "checkout.shipping_address": "Shipping Address",
    "checkout.full_name": "Full Name",
    "checkout.address_line1": "Address Line 1",
    "checkout.address_line2": "Address Line 2 (optional)",
    "checkout.city": "City",
    "checkout.state": "State / Region",
    "checkout.postal_code": "Postal Code",
    "checkout.country": "Country",
    "checkout.phone_number": "Phone Number",
    "checkout.order_notes": "Order Notes",
    "checkout.notes_placeholder": "Any delivery instructions?",
    "checkout.pay_with_card": "Pay with Card",
    "checkout.secure_payment": "Secure payment powered by Stripe",
    "checkout.back_to_cart": "Back to Cart",
    "checkout.shipping": "Shipping",
    "checkout.free": "Free",
    "checkout.tax": "Tax",
    "checkout.creating_order": "Creating your order...",

    // ---------- Payment success ----------
    "paysucc.title": "Thank you for your order!",
    "paysucc.subtitle":
      "Your payment was successful. A confirmation email is on the way.",
    "paysucc.order_number": "Order number",
    "paysucc.items": "Items",
    "paysucc.view_orders": "View my orders",
    "paysucc.continue_shopping": "Continue shopping",

    // ---------- Orders page ----------
    "orders.title": "My Orders",
    "orders.empty": "You haven't placed any orders yet.",
    "orders.start_shopping": "Start shopping",
    "orders.placed_on": "Placed on",
    "orders.view_details": "View Details",
    "orders.status.pending": "Pending",
    "orders.status.paid": "Paid",
    "orders.status.shipped": "Shipped",
    "orders.status.delivered": "Delivered",
    "orders.status.cancelled": "Cancelled",
    "orders.status.refunded": "Refunded",

    // ---------- Contact / lead forms ----------
    "forms.contact.title": "Contact Us",
    "forms.contact.subtitle": "Our team will get back to you within one business day.",
    "forms.get_price.title": "Get a Price",
    "forms.get_price.subtitle":
      "Tell us what you need and we'll send a tailored quote.",
    "forms.support.title": "Contact Support",
    "forms.support.subtitle":
      "Describe your issue and our support team will help you quickly.",
    "forms.placeholder.name": "Your full name",
    "forms.placeholder.email": "you@example.com",
    "forms.placeholder.phone": "+966 …",
    "forms.placeholder.company": "Company name",
    "forms.placeholder.message": "How can we help?",
    "forms.send": "Send Message",
    "forms.sending": "Sending...",
    "forms.thanks": "Thanks! We'll be in touch.",

    // ---------- Misc CTAs often seen in pages ----------
    "cta.explore": "Explore",
    "cta.see_plans": "See plans",
    "cta.request_quote": "Request a Quote",
    "cta.upgrade": "Upgrade",
    "cta.manage": "Manage",
    "cta.open": "Open",
    "cta.close": "Close",
  },
  ar: {
    // ---------- Top-level navigation ----------
    "nav.home": "الرئيسية",
    "nav.hosting": "خدمات الاستضافة",
    "nav.cloud": "الخدمات السحابية",
    "nav.web": "خدمات الويب",
    "nav.shop": "المتجر",
    "nav.support": "الدعم",
    "nav.login": "تسجيل الدخول",
    "nav.client_area": "منطقة العميل",
    "nav.cart": "السلة",
    "nav.account": "حسابي",
    "nav.sign_in": "تسجيل الدخول",
    "nav.logout": "تسجيل الخروج",
    "nav.welcome": "مرحبا",
    "nav.welcome_back": "مرحبا بعودتك",
    "nav.menu": "القائمة",
    "nav.close": "إغلاق",

    // ---------- Hosting submenu ----------
    "nav.shared_hosting": "الاستضافة المشتركة",
    "nav.cpanel_hosting": "استضافة cPanel",
    "nav.plesk_hosting": "استضافة Plesk",
    "nav.aapanel_hosting": "استضافة aaPanel",
    "nav.windows_hosting": "استضافة ويندوز",
    "nav.wordpress_hosting": "استضافة ووردبريس",
    "nav.reseller_hosting": "استضافة الموزعين",
    "nav.vps_hosting": "استضافة VPS",
    "nav.dedicated_servers": "السيرفرات المخصصة",

    // ---------- Cloud submenu ----------
    "nav.cloud_hosting": "الاستضافة السحابية",
    "nav.cloud_servers": "السيرفرات السحابية",
    "nav.cloud_storage": "التخزين السحابي",
    "nav.cloud_backup": "النسخ الاحتياطي السحابي",

    // ---------- Web submenu ----------
    "nav.domain_registration": "تسجيل النطاقات",
    "nav.domain_transfer": "نقل النطاقات",
    "nav.ssl_certificates": "شهادات SSL",
    "nav.website_builder": "منشئ المواقع",
    "nav.email_hosting": "استضافة البريد الإلكتروني",

    // ---------- Support submenu ----------
    "nav.tickets": "تذاكر الدعم",
    "nav.knowledge_base": "قاعدة المعرفة",
    "nav.faq": "الأسئلة الشائعة",
    "nav.service_catalog": "كتالوج الخدمات",
    "nav.contact": "تواصل معنا",
    "nav.remote_support": "الدعم عن بُعد",
    "nav.uptime_monitor": "مراقب التشغيل",
    "nav.about_us": "من نحن",

    // ---------- Language switcher ----------
    "lang.label": "اللغة",
    "lang.english": "English",
    "lang.arabic": "العربية",

    // ---------- Footer ----------
    "footer.about_title": "عن Doiteasy",
    "footer.terms_title": "الشروط والأحكام",
    "footer.clients_title": "حسابات العملاء",
    "footer.country": "المملكة العربية السعودية",
    "footer.address_line1": "العنوان: شارع الحوطة 3939",
    "footer.address_line2": "حي الشفا - الرمز 14721",
    "footer.address_line3": "الرياض، المملكة العربية السعودية",
    "footer.phone": "هاتف: 0112018568",
    "footer.service_terms": "شروط الخدمة",
    "footer.refund_policy": "سياسة الاسترداد",
    "footer.privacy_center": "مركز الخصوصية",
    "footer.customer_support": "دعم العملاء",
    "footer.knowledge_base": "قاعدة المعرفة",
    "footer.faq": "الأسئلة الشائعة",
    "footer.services_catalog": "كتالوج الخدمات",
    "footer.account_dashboard": "لوحة الحساب",
    "footer.new_client": "عميل جديد",
    "footer.affiliate_program": "برنامج الشركاء",
    "footer.rate_us": "قيّمنا على Trustpilot",
    "footer.copyright": "جميع الحقوق محفوظة © {year} Doiteasy.",
    "footer.get_it_on": "حمّله من",
    "footer.google_play": "Google Play",
    "footer.app_store": "App Store",
    "footer.download_on": "حمّل من",

    // ---------- Common CTAs ----------
    "cta.get_started": "ابدأ الآن",
    "cta.learn_more": "اعرف المزيد",
    "cta.view_plans": "عرض الخطط",
    "cta.buy_now": "اشتري الآن",
    "cta.order_now": "اطلب الآن",
    "cta.contact_sales": "تواصل مع المبيعات",
    "cta.read_more": "اقرأ المزيد",
    "cta.back_to_top": "العودة للأعلى",
    "cta.try_free": "جرّب مجانًا",
    "cta.start_free_trial": "ابدأ النسخة التجريبية المجانية",
    "cta.open_ticket": "فتح تذكرة دعم",
    "cta.chat_with_us": "تواصل عبر الدردشة",

    // ---------- Hero (homepage) ----------
    "hero.badge": "استضافة سعودية · دعم 24/7",
    "hero.title": "استضافة موثوقة وسحابة قوية وإعداد بسيط",
    "hero.subtitle":
      "بنية استضافة وسحابة عالية الأداء مصممة للشركات التي تتطلب السرعة والأمان والاستمرارية.",
    "hero.cta_primary": "استعرض الخطط",
    "hero.cta_secondary": "تحدث مع خبير",
    "hero.stat_uptime": "جاهزية 99.9٪",
    "hero.stat_support": "دعم 24/7",
    "hero.stat_datacenters": "مراكز بيانات عالمية",

    // ---------- Shop ----------
    "shop.title": "المتجر",
    "shop.featured": "المنتجات المميزة",
    "shop.all_products": "جميع المنتجات",
    "shop.categories": "الفئات",
    "shop.price_range": "نطاق السعر",
    "shop.sort_by": "الترتيب حسب",
    "shop.newest": "الأحدث",
    "shop.price_low": "السعر: من الأقل للأعلى",
    "shop.price_high": "السعر: من الأعلى للأقل",
    "shop.add_to_cart": "أضف إلى السلة",
    "shop.out_of_stock": "غير متوفر",
    "shop.in_stock": "متوفر",
    "shop.cart_title": "سلتك",
    "shop.cart_empty": "سلتك فارغة",
    "shop.continue_shopping": "مواصلة التسوق",
    "shop.checkout": "إتمام الشراء",
    "shop.subtotal": "الإجمالي الفرعي",
    "shop.total": "الإجمالي",
    "shop.quantity": "الكمية",
    "shop.remove": "إزالة",
    "shop.order_success": "تم إنشاء الطلب بنجاح!",
    "shop.order_summary": "ملخص الطلب",
    "shop.shipping_info": "معلومات الشحن",
    "shop.payment": "الدفع",
    "shop.place_order": "تأكيد الطلب",
    "shop.my_orders": "طلباتي",
    "shop.order_id": "رقم الطلب",
    "shop.order_date": "التاريخ",
    "shop.order_status": "الحالة",

    // ---------- Forms / common labels ----------
    "form.name": "الاسم",
    "form.first_name": "الاسم الأول",
    "form.last_name": "اسم العائلة",
    "form.email": "البريد الإلكتروني",
    "form.phone": "الهاتف",
    "form.company": "الشركة",
    "form.address": "العنوان",
    "form.city": "المدينة",
    "form.country": "الدولة",
    "form.postal_code": "الرمز البريدي",
    "form.subject": "الموضوع",
    "form.message": "الرسالة",
    "form.password": "كلمة المرور",
    "form.confirm_password": "تأكيد كلمة المرور",
    "form.submit": "إرسال",
    "form.cancel": "إلغاء",
    "form.save": "حفظ",
    "form.edit": "تعديل",
    "form.delete": "حذف",
    "form.search": "بحث",
    "form.required": "مطلوب",
    "form.optional": "اختياري",
    "form.loading": "جارٍ التحميل...",
    "form.success": "تم بنجاح",
    "form.error": "حدث خطأ",

    // ---------- Legal / support page titles ----------
    "legal.service_terms": "شروط الخدمة",
    "legal.refund_policy": "سياسة الاسترداد",
    "legal.privacy_center": "مركز الخصوصية",
    "legal.last_updated": "آخر تحديث",
    "legal.table_of_contents": "جدول المحتويات",
    "support.title": "الدعم",
    "support.need_help": "تحتاج مساعدة؟",
    "support.talk_to_expert":
      "تحدث مع أحد خبرائنا — فريق الدعم متاح على مدار الساعة.",
    "support.open_ticket_desc":
      "افتح تذكرة دعم وسنعاود التواصل معك خلال وقت قصير.",
    "kb.title": "قاعدة المعرفة",
    "kb.search_placeholder": "ابحث في المقالات...",
    "faq.title": "الأسئلة الشائعة",

    // ---------- Service catalog ----------
    "services.title": "كتالوج الخدمات",
    "services.subtitle":
      "تصفح مجموعتنا الكاملة من خدمات الاستضافة والسحابة والخدمات المُدارة.",
    "services.testimonials_title": "ماذا يقول عملاؤنا",

    // ---------- Chat widget ----------
    "chat.title": "الدعم المباشر",
    "chat.placeholder": "اكتب رسالتك...",
    "chat.send": "إرسال",
    "chat.online": "متصل",
    "chat.offline": "غير متصل",

    // ---------- Generic labels ----------
    "label.new": "جديد",
    "label.popular": "الأكثر شيوعًا",
    "label.recommended": "موصى به",
    "label.free": "مجاني",
    "label.per_month": "/ شهرياً",
    "label.per_year": "/ سنوياً",
    "label.from": "ابتداءً من",
    "label.save": "وفّر",
    "label.off": "خصم",

    // ---------- NAV exact strings (reverse-lookup friendly) ----------
    "exact.home": "الرئيسية",
    "exact.hosting_services": "خدمات الاستضافة",
    "exact.cloud_services": "الخدمات السحابية",
    "exact.web_services": "خدمات الويب",
    "exact.shop": "المتجر",
    "exact.support": "الدعم",
    "exact.shared_hosting": "الاستضافة المشتركة",
    "exact.wordpress_hosting": "استضافة ووردبريس",
    "exact.reseller_hosting": "استضافة الموزعين",
    "exact.cloud_vps": "VPS سحابي",
    "exact.dedicated_servers": "السيرفرات المخصصة",
    "exact.vds": "VDS",
    "exact.service_catalog": "كتالوج الخدمات",
    "exact.bizmail360": "Bizmail360 - بريد التعاون",
    "exact.business_email": "بريد الأعمال",
    "exact.cloud_managed": "خدمات سحابية مُدارة",
    "exact.whatsapp_api": "خدمة WhatsApp API",
    "exact.uptime_monitor": "مراقب التشغيل",
    "exact.sd_wan": "خدمات SD-WAN",
    "exact.managed_it": "الإدارة التقنية",
    "exact.remote_support": "الدعم عن بُعد",
    "exact.on_premises": "إدارة المحلي",
    "exact.domain_registration": "تسجيل النطاقات",
    "exact.knowledge_base": "قاعدة المعرفة",
    "exact.faq": "الأسئلة الشائعة",
    "exact.ticket_system": "نظام التذاكر",
    "exact.contact_us": "تواصل معنا",
    "exact.about_us": "من نحن",
    "exact.client_area": "منطقة العميل",
    "exact.login": "تسجيل الدخول",
    "exact.logout": "تسجيل الخروج",
    "exact.sign_in": "تسجيل الدخول",
    "exact.my_account": "حسابي",
    "exact.guest_user": "ضيف",
    "exact.welcome": "مرحبا",
    "exact.welcome_back": "مرحبا بعودتك",
    "exact.menu": "القائمة",
    "exact.cart": "السلة",
    "exact.back_to_top": "العودة للأعلى",

    // ---------- Homepage hero & body copy (reverse-lookup friendly) ----------
    "hp.hero.trusted": "موثوق به من قبل أكثر من 10,000 شركة عبر الخليج",
    "hp.hero.infra_scale": "بنية تحتية مصممة للنمو",
    "hp.hero.enterprise": "موثوقية على مستوى المؤسسات",
    "hp.hero.dedicated_with": "مخصص بـ",
    "hp.hero.confidence": "ثقة.",
    "hp.hero.virtual": "افتراضي",
    "hp.hero.cloud_servers": "سيرفرات سحابية",
    "hp.hero.managed_it_title": "إدارة تقنية",
    "hp.hero.done_right": "بأفضل صورة.",
    "hp.hero.dedicated_desc":
      "سيرفرات سحابية قوية وعتاد مخصص وخدمات إدارة تقنية بموارد حصرية — تبدأ من 12.99$ شهرياً فقط.",
    "hp.hero.vps_desc":
      "سيرفرات VPS سحابية بتقنية NVMe مع فوترة بالثانية وإعادة تثبيت بنقرة واحدة وتوفير خلال 60 ثانية عبر أتمتة Virtualizor.",
    "hp.hero.managed_desc":
      "مراقبة 24/7 وتحديثات استباقية ونسخ احتياطية آمنة ومهندسون خبراء جاهزون — حتى يتفرغ فريقك للأعمال.",
    "hp.hero.bullet.money_back": "استرداد المبلغ خلال 30 يوماً",
    "hp.hero.bullet.sla": "ضمان خدمة 99.99٪",
    "hp.hero.bullet.free_migration": "ترحيل مجاني",
    "hp.hero.bullet.scalability": "توسعة فورية",
    "hp.hero.bullet.performance": "أداء عالٍ",
    "hp.hero.bullet.deployment": "نشر سريع",
    "hp.hero.bullet.proactive": "مراقبة استباقية",
    "hp.hero.bullet.zero_downtime": "ترحيل دون انقطاع",
    "hp.hero.bullet.247": "دعم خبراء 24/7",
    "hp.hero.btn.get_prices": "اطلب الأسعار",
    "hp.hero.btn.dedicated_servers": "السيرفرات المخصصة",
    "hp.hero.btn.vps_servers": "سيرفرات VPS",
    "hp.hero.btn.talk_sales": "تحدث مع المبيعات",
    "hp.hero.btn.managed_it": "الإدارة التقنية",

    // Homepage "Why" section
    "hp.why.eyebrow": "لماذا تختار",
    "hp.why.title": "لماذا تختار كبرى الشركات DoItEasy",
    "hp.why.all_systems": "جميع الأنظمة تعمل",
    "hp.why.business": "أعمال",
    "hp.why.infrastructure": "البنية التحتية",
    "hp.why.business_suite": "حزمة الأعمال",
    "hp.why.cloud_vps_vds": "VPS سحابي و VDS وسيرفرات مخصصة",
    "hp.why.client_portal": "بوابة العملاء",
    "hp.why.free_ssl": "SSL مجاني + حماية DDoS",
    "hp.why.builtin_ticket": "نظام تذاكر مدمج ومتابعة SLA",
    "hp.why.manage_desc": "أدر جميع خدماتك من لوحة موحدة واحدة",
    "hp.why.managing": "إدارة خدماتك",
    "hp.why.mfa": "محمي بـ MFA وسياسة Zero-Trust",
    "hp.why.recent_tickets": "التذاكر الحديثة",
    "hp.why.remember_me": "تذكرني",
    "hp.why.security": "درع الأمان",
    "hp.why.support_sla": "الدعم و SLA",

    // Homepage managing-features section
    "hp.mf.proactive_title": "مراقبة استباقية ودعم 24/7",
    "hp.mf.proactive_desc":
      "تنبيهات فورية (بما فيها إشعارات WhatsApp)، استجابة سريعة وحل المشكلات قبل أن تؤثر على العمليات.",
    "hp.mf.email_migration_title": "ترحيل بريد الأعمال",
    "hp.mf.email_migration_desc":
      "ترحيل دون انقطاع بين Exchange / Microsoft 365 و Google Workspace و SmarterMail و IMAP — بيانات البريد والتقويمات وجهات الاتصال وتحويل DNS.",
    "hp.mf.tenant_title": "إدارة المستأجرين السحابيين",
    "hp.mf.tenant_desc":
      "إدارة مستأجري Microsoft Azure و Google Cloud: الهوية والوصول (AAD/IAM)، ضبط التكاليف، الشبكات، النسخ الاحتياطي ومعايير السياسات.",
    "hp.mf.remote_title": "الدعم عن بُعد",
    "hp.mf.remote_desc":
      "مساعدة آمنة عن بُعد للسيرفرات والأجهزة لفحص المشكلات وتشخيصها ومعالجتها بسرعة.",
    "hp.mf.enduser_title": "دعم المستخدمين النهائيين",
    "hp.mf.enduser_desc":
      "مكتب مساعدة لفريقك: التهيئة وإعداد البريد والأجهزة وتطبيقات سطح المكتب وإعادة تعيين كلمات المرور والمساعدة اليومية.",
    "hp.mf.optim_title": "تحسين السيرفرات والسحابة",
    "hp.mf.optim_desc":
      "ضبط الأداء والتخطيط للسعة والتحديثات الأمنية والترقيات التلقائية.",
    "hp.mf.security_title": "أمن البيانات والنسخ الاحتياطي",
    "hp.mf.security_desc":
      "إعدادات محصّنة، WAF/مكافحة البوت، استراتيجيات النسخ الاحتياطي والتعافي من الكوارث.",
    "hp.mf.scalable_title": "حلول قابلة للتوسّع",
    "hp.mf.scalable_desc":
      "من بضع أجهزة إلى نشر معقد متعدد المناطق — ادفع فقط مقابل ما تحتاج.",

    // ---------- Shop cards & chrome ----------
    "shop.eyebrow": "متجر DoItEasy",
    "shop.hero_title": "تقنيات متميزة مختارة للشركات",
    "shop.hero_subtitle":
      "حواسيب محمولة ومحطات عمل ومعدات شبكات وملحقات — مختارة بعناية وجاهزة للشحن.",
    "shop.search_placeholder": "ابحث في المنتجات أو الوسوم أو الفئات...",
    "shop.no_results": "لا توجد منتجات تطابق الفلاتر",
    "shop.try_clear": "جرّب مسح البحث أو تعديل نطاق السعر.",
    "shop.clear_filters": "مسح الفلاتر",
    "shop.results_count": "نتيجة",
    "shop.featured_badge": "مميز",
    "shop.new_badge": "جديد",
    "shop.view_details": "عرض التفاصيل",
    "shop.category_all": "الكل",
    "shop.min_price": "الحد الأدنى",
    "shop.max_price": "الحد الأعلى",
    "shop.apply": "تطبيق",
    "shop.reset": "إعادة تعيين",

    // ---------- Cart ----------
    "cart.title": "سلتك",
    "cart.empty_title": "سلتك فارغة",
    "cart.empty_desc":
      "يبدو أنك لم تُضف أي منتجات بعد. تصفّح المتجر لتبدأ.",
    "cart.browse_shop": "تصفّح المتجر",
    "cart.items": "المنتجات",
    "cart.qty": "الكمية",
    "cart.unit_price": "سعر الوحدة",
    "cart.line_total": "إجمالي السطر",
    "cart.remove": "إزالة",
    "cart.proceed_checkout": "المتابعة لإتمام الشراء",
    "cart.shipping_free": "شحن مجاني",
    "cart.shipping_calc": "تُحسب تكلفة الشحن عند الدفع",
    "cart.estimated_total": "الإجمالي المقدَّر",

    // ---------- Checkout ----------
    "checkout.title": "إتمام الشراء",
    "checkout.signin_cta":
      "لديك حساب؟ سجّل الدخول لتجربة دفع أسرع.",
    "checkout.guest_mode": "الدفع كضيف",
    "checkout.billing_email": "بريد الفوترة",
    "checkout.shipping_address": "عنوان الشحن",
    "checkout.full_name": "الاسم الكامل",
    "checkout.address_line1": "سطر العنوان 1",
    "checkout.address_line2": "سطر العنوان 2 (اختياري)",
    "checkout.city": "المدينة",
    "checkout.state": "المنطقة / الولاية",
    "checkout.postal_code": "الرمز البريدي",
    "checkout.country": "الدولة",
    "checkout.phone_number": "رقم الهاتف",
    "checkout.order_notes": "ملاحظات الطلب",
    "checkout.notes_placeholder": "هل لديك تعليمات توصيل؟",
    "checkout.pay_with_card": "ادفع بالبطاقة",
    "checkout.secure_payment": "دفع آمن بواسطة Stripe",
    "checkout.back_to_cart": "العودة للسلة",
    "checkout.shipping": "الشحن",
    "checkout.free": "مجاني",
    "checkout.tax": "الضريبة",
    "checkout.creating_order": "جارٍ إنشاء طلبك...",

    // ---------- Payment success ----------
    "paysucc.title": "شكراً لطلبك!",
    "paysucc.subtitle":
      "تم الدفع بنجاح. بريد التأكيد في طريقه إليك.",
    "paysucc.order_number": "رقم الطلب",
    "paysucc.items": "المنتجات",
    "paysucc.view_orders": "عرض طلباتي",
    "paysucc.continue_shopping": "مواصلة التسوق",

    // ---------- Orders page ----------
    "orders.title": "طلباتي",
    "orders.empty": "لم تقم بأي طلب بعد.",
    "orders.start_shopping": "ابدأ التسوق",
    "orders.placed_on": "تم الطلب في",
    "orders.view_details": "عرض التفاصيل",
    "orders.status.pending": "قيد الانتظار",
    "orders.status.paid": "مدفوع",
    "orders.status.shipped": "تم الشحن",
    "orders.status.delivered": "تم التسليم",
    "orders.status.cancelled": "ملغي",
    "orders.status.refunded": "مُسترد",

    // ---------- Contact / lead forms ----------
    "forms.contact.title": "تواصل معنا",
    "forms.contact.subtitle":
      "سيعاود فريقنا التواصل معك خلال يوم عمل واحد.",
    "forms.get_price.title": "اطلب السعر",
    "forms.get_price.subtitle":
      "أخبرنا بما تحتاج وسنرسل لك عرض سعر مخصصاً.",
    "forms.support.title": "تواصل مع الدعم",
    "forms.support.subtitle":
      "اشرح مشكلتك وسيساعدك فريق الدعم بسرعة.",
    "forms.placeholder.name": "اسمك الكامل",
    "forms.placeholder.email": "you@example.com",
    "forms.placeholder.phone": "‎+966 …",
    "forms.placeholder.company": "اسم الشركة",
    "forms.placeholder.message": "كيف يمكننا مساعدتك؟",
    "forms.send": "إرسال الرسالة",
    "forms.sending": "جارٍ الإرسال...",
    "forms.thanks": "شكراً! سنتواصل معك.",

    // ---------- Misc CTAs often seen in pages ----------
    "cta.explore": "استعرض",
    "cta.see_plans": "انظر الخطط",
    "cta.request_quote": "اطلب عرض سعر",
    "cta.upgrade": "ترقية",
    "cta.manage": "إدارة",
    "cta.open": "فتح",
    "cta.close": "إغلاق",
  },
};

/**
 * Reverse-lookup table: English string -> translation key.
 * Built once at module load so `tr("Get Started")` is O(1).
 */
const EN_TO_KEY: Record<string, string> = (() => {
  const out: Record<string, string> = {};
  for (const [key, value] of Object.entries(CATALOG.en)) {
    if (!(value in out)) out[value] = key;
  }
  return out;
})();

/**
 * Flat English -> Arabic dictionary. The DOM auto-translator in
 * SiteLayout reads this at runtime to swap untranslated text nodes in
 * components that still render raw English.
 */
const EN_TO_AR: Record<string, string> = (() => {
  const out: Record<string, string> = {};
  for (const [key, english] of Object.entries(CATALOG.en)) {
    const arabic = CATALOG.ar[key];
    if (arabic && !(english in out)) out[english] = arabic;
  }
  return out;
})();

// Expose dictionary to the auto-translator (client-side only).
if (typeof window !== "undefined") {
  (window as any).__DOITEASY_EN_TO_AR__ = EN_TO_AR;
}

const LanguageContext = createContext<LanguageContextValue | undefined>(
  undefined,
);

function readInitialLang(): AppLanguage {
  if (typeof window === "undefined") return "en";
  try {
    const stored = window.localStorage.getItem(STORAGE_KEY);
    if (stored === "en" || stored === "ar") return stored;
  } catch {
    /* ignore */
  }
  const browser = (navigator.language || "").toLowerCase();
  if (browser.startsWith("ar")) return "ar";
  return "en";
}

function applyLangToDocument(lang: AppLanguage) {
  if (typeof document === "undefined") return;
  const dir = lang === "ar" ? "rtl" : "ltr";
  document.documentElement.setAttribute("lang", lang);
  document.documentElement.setAttribute("dir", dir);
  document.documentElement.setAttribute("data-lang", lang);
}

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [lang, setLangState] = useState<AppLanguage>(() => readInitialLang());

  useEffect(() => {
    applyLangToDocument(lang);
    try {
      window.localStorage.setItem(STORAGE_KEY, lang);
    } catch {
      /* ignore */
    }
  }, [lang]);

  const setLang = useCallback((next: AppLanguage) => {
    setLangState(next);
  }, []);

  const toggleLang = useCallback(() => {
    setLangState((prev) => (prev === "en" ? "ar" : "en"));
  }, []);

  const t = useCallback(
    (key: string) => {
      const table = CATALOG[lang] ?? CATALOG.en;
      return table[key] ?? CATALOG.en[key] ?? key;
    },
    [lang],
  );

  const tr = useCallback(
    (englishString: string) => {
      if (lang === "en") return englishString;
      const key = EN_TO_KEY[englishString];
      if (!key) return englishString;
      return CATALOG.ar[key] ?? englishString;
    },
    [lang],
  );

  const value = useMemo<LanguageContextValue>(
    () => ({
      lang,
      dir: lang === "ar" ? "rtl" : "ltr",
      setLang,
      toggleLang,
      t,
      tr,
    }),
    [lang, setLang, toggleLang, t, tr],
  );

  return (
    <LanguageContext.Provider value={value}>
      {children}
    </LanguageContext.Provider>
  );
}

export function useLanguage(): LanguageContextValue {
  const ctx = useContext(LanguageContext);
  if (!ctx) {
    throw new Error("useLanguage must be used within a LanguageProvider");
  }
  return ctx;
}

/**
 * Small helper component to translate inline text.
 * Usage: <T>Get Started</T>
 * When Arabic is active, any exact English match in the catalog is
 * replaced with its Arabic translation; otherwise the children are
 * returned unchanged.
 */
export function T({ children }: { children: string }) {
  const { tr } = useLanguage();
  return <>{tr(children)}</>;
}