'use client';

import { useEffect } from 'react';

// This compatibility dictionary covers legacy screens that still contain
// Vietnamese literals. New UI should continue using next-intl messages.
const ENGLISH_UI: Record<string, string> = {
  'Tin Mới': 'News',
  'Trang chủ': 'Home',
  'Mua bán': 'Marketplace',
  'Diễn Đàn': 'Forum',
  'Hỗ trợ': 'Support',
  'Đăng nhập': 'Log in',
  'Đăng ký': 'Register',
  'Đăng xuất': 'Log out',
  'Tìm phần mềm, thẻ quà tặng, mã, dịch vụ...': 'Search software, gift cards, codes, services...',
  'Chọn ngôn ngữ': 'Language',
  'Hồ sơ': 'Profile',
  'Cài đặt': 'Settings',
  'Đơn hàng': 'Orders',
  'Đơn hàng của tôi': 'My orders',
  'Khiếu nại của tôi': 'My complaints',
  'Ví': 'Wallet',
  'Affiliate của tôi': 'My affiliate',
  'Kênh bán hàng': 'Seller Center',
  'Quản trị hệ thống': 'Administration',
  'Khách hàng': 'Customer',
  'Người dùng': 'User',
  'Tất cả': 'All',
  'Giao dịch': 'Transactions',
  'Hệ thống': 'System',
  'Khuyến mãi': 'Promotions',
  'Thông báo': 'Notifications',
  'Đánh dấu tất cả đã đọc': 'Mark all as read',
  'Chưa có thông báo nào.': 'No notifications yet.',
  'Cài đặt thông báo': 'Notification settings',
  'Xem tất cả thông báo': 'View all notifications',
  'Chăm sóc khách hàng': 'Customer support',
  'Trung tâm hỗ trợ': 'Help center',
  'Bảo vệ đơn hàng': 'Order protection',
  'Chính sách hoàn tiền': 'Refund policy',
  'Báo cáo sự cố': 'Report an issue',
  'Hướng dẫn sử dụng': 'User guide',
  'Câu hỏi thường gặp': 'Frequently asked questions',
  'Cài đặt tài khoản': 'Account settings',
  'Chính sách bảo mật': 'Privacy policy',
  'Điều khoản dịch vụ': 'Terms of service',
  'Về chúng tôi': 'About us',
  'Liên hệ': 'Contact',
  'Bảng điều khiển bán hàng': 'Seller dashboard',
  'Tạo sản phẩm': 'Create product',
  'Quản lý sản phẩm': 'Product management',
  'Doanh thu & Thanh toán': 'Revenue & payments',
  'Hướng dẫn người bán': 'Seller guide',
  'Phương thức thanh toán': 'Payment methods',
  'Theo dõi chúng tôi': 'Follow us',
  'Ứng dụng SHOP MMO': 'SHOP MMO application',
  'HỆ THỐNG': 'SYSTEM',
  'CẤU HÌNH': 'CONFIGURATION',
  'Quản lý Users': 'User management',
  'Quản lý Sản phẩm': 'Product management',
  'Quản lý Đơn hàng': 'Order management',
  'Quản lý Nạp tiền': 'Deposit management',
  'Quản lý Rút tiền': 'Withdrawal management',
  'Quản lý Khiếu nại': 'Dispute management',
  'Đơn xin làm Seller': 'Seller applications',
  'Quản lý Affiliate': 'Affiliate management',
  'Quản lý CMS': 'CMS management',
  'Cấu hình hệ thống': 'System settings',
  'TỔNG QUAN': 'OVERVIEW',
  'THIẾT LẬP GIAN HÀNG': 'STORE SETUP',
  'BÁN HÀNG': 'SALES',
  'TÀI CHÍNH': 'FINANCE',
  'Tổng quan': 'Overview',
  'Hồ sơ gian hàng': 'Store profile',
  'Hình ảnh': 'Images',
  'Sản phẩm': 'Products',
  'Đơn bán': 'Sales orders',
  'Khiếu nại': 'Complaints',
  'Mã giảm giá': 'Coupons',
  'Thanh toán': 'Payments',
  'Rút tiền': 'Withdrawals',
  'Sổ cái & Lịch sử': 'Ledger & history',
  'Đang kiểm tra quyền truy cập Seller...': 'Checking Seller access...',
  'Vui lòng chờ trong giây lát.': 'Please wait a moment.',
  'Không có quyền truy cập': 'Access denied',
  'Về trang chủ': 'Back to home',
  'Tổng sản phẩm': 'Total products',
  'Đang hiển thị': 'Visible',
  'Đã ẩn': 'Hidden',
  'Sắp hết hàng': 'Low stock',
  'Bộ lọc tìm kiếm': 'Search filters',
  'Tìm sản phẩm theo tên...': 'Search products by name...',
  'Tất cả trạng thái': 'All statuses',
  'Tất cả danh mục': 'All categories',
  'Danh mục': 'Category',
  'Trạng thái': 'Status',
  'Giá bán / Kho': 'Price / Stock',
  'Nổi bật': 'Featured',
  'Thao tác': 'Actions',
  'Cài đặt danh mục': 'Category settings',
  'Xóa marketplace': 'Clear marketplace',
  'Đưa lên sản phẩm nổi bật': 'Mark as featured',
  'Gỡ khỏi sản phẩm nổi bật': 'Remove from featured',
  'Ẩn sản phẩm': 'Hide product',
  'Hiện sản phẩm': 'Show product',
  'Xóa sản phẩm': 'Delete product',
  'Ấn để ẩn sản phẩm': 'Click to hide product',
  'Ấn để hiện sản phẩm': 'Click to show product',
  'Tìm kiếm': 'Search',
  'Đặt lại': 'Reset',
  'Làm mới': 'Refresh',
  'Lưu': 'Save',
  'Lưu thay đổi': 'Save changes',
  'Hủy': 'Cancel',
  'Đóng': 'Close',
  'Xóa': 'Delete',
  'Sửa': 'Edit',
  'Chi tiết': 'Details',
  'Xem chi tiết': 'View details',
  'Quay lại': 'Back',
  'Tiếp': 'Next',
  'Trước': 'Previous',
  'Ngày tạo': 'Created date',
  'Ngày cập nhật': 'Updated date',
  'Thời gian': 'Time',
  'Mật khẩu': 'Password',
  'Họ và tên': 'Full name',
  'Số điện thoại': 'Phone number',
  'Vai trò': 'Role',
  'Số dư': 'Balance',
  'Tổng nạp': 'Total deposits',
  'Hoạt động': 'Activity',
  'Trực tuyến': 'Online',
  'Ngoại tuyến': 'Offline',
  'Đang hoạt động': 'Active',
  'Đã khóa': 'Banned',
  'Thành viên': 'Members',
  'Quản lý thành viên': 'Member management',
  'Thông tin cơ bản': 'Basic information',
  'Bảo mật': 'Security',
  'Quyền hạn': 'Permissions',
  'Nhật ký hoạt động gần nhất': 'Recent activity log',
  'Biến động số dư gần nhất': 'Recent balance changes',
  'Cộng số dư': 'Add balance',
  'Trừ số dư': 'Deduct balance',
  'Tổng đơn hàng': 'Total orders',
  'Doanh thu': 'Revenue',
  'Phí sàn 5%': '5% platform fee',
  'Hôm nay': 'Today',
  'Tuần này': 'This week',
  'Tháng này': 'This month',
  'Toàn thời gian': 'All time',
  'Đơn hàng gần đây': 'Recent orders',
  'Nạp tiền gần đây': 'Recent deposits',
  'Chờ xử lý': 'Pending',
  'Đang giữ tiền': 'Funds held',
  'Đang xử lý': 'Processing',
  'Hoàn thành': 'Completed',
  'Đã hủy': 'Cancelled',
  'Tranh chấp': 'Disputed',
  'Đã giao': 'Delivered',
  'Chờ giao': 'Awaiting delivery',
  'Đang giao': 'Delivering',
  'Đã thanh toán': 'Paid',
  'Chưa thanh toán': 'Unpaid',
  'Hoàn tiền': 'Refund',
  'Đã hoàn tiền': 'Refunded',
  'Xác nhận đã nhận hàng': 'Confirm receipt',
  'Chat với người bán': 'Chat with seller',
  'Chat với người mua': 'Chat with buyer',
  'Đánh giá người bán': 'Rate seller',
  'Khiếu nại / mời admin hỗ trợ': 'Dispute / invite admin',
  'Chi tiết đơn hàng': 'Order details',
  'Mã đơn hàng': 'Order ID',
  'Người mua': 'Buyer',
  'Người bán': 'Seller',
  'Tổng tiền': 'Total',
  'Số lượng': 'Quantity',
  'Đơn giá': 'Unit price',
  'Thành tiền': 'Subtotal',
  'Sản phẩm đã mua': 'Purchased product',
  'Tải sản phẩm': 'Download product',
  'Mua ngay': 'Buy now',
  'Thêm vào giỏ': 'Add to cart',
  'Hết hàng': 'Out of stock',
  'Còn hàng': 'In stock',
  'Mô tả': 'Description',
  'Thông tin': 'Information',
  'Bàn giao & bảo hành': 'Delivery & warranty',
  'Đánh giá': 'Reviews',
  'Bảo hành': 'Warranty',
  'Thời gian giao': 'Delivery time',
  'Giao tự động': 'Automatic delivery',
  'Giao thủ công': 'Manual delivery',
  'Tự động': 'Automatic',
  'Thủ công': 'Manual',
  'Chưa có đánh giá': 'No reviews yet',
  'Đã bán': 'Sold',
  'Kho': 'Stock',
  'Danh sách sản phẩm': 'Product list',
  'Sản phẩm của tôi': 'My products',
  'Đăng sản phẩm': 'Publish product',
  'Đăng sản phẩm mới': 'Create product',
  'Chỉnh sửa sản phẩm': 'Edit product',
  'Quản lý kho': 'Inventory management',
  'Tồn kho': 'Stock',
  'Khả dụng': 'Available',
  'Đã đặt trước': 'Reserved',
  'Đã giao hàng': 'Delivered',
  'Đã vô hiệu hóa': 'Disabled',
  'Tải kho': 'Download inventory',
  'Tên sản phẩm': 'Product name',
  'Giá': 'Price',
  'Ảnh sản phẩm': 'Product image',
  'Mô tả sản phẩm': 'Product description',
  'Thẻ tìm kiếm': 'Search tags',
  'Cách giao hàng': 'Delivery method',
  'Thời gian giao dự kiến': 'Estimated delivery time',
  'Tạo yêu cầu rút': 'Create withdrawal request',
  'Có thể rút': 'Available to withdraw',
  'Đang chờ rút': 'Pending withdrawal',
  'Doanh thu hôm nay': 'Revenue today',
  'Doanh thu tháng': 'Monthly revenue',
  'Yêu cầu đang có': 'Active requests',
  'Điều kiện tạo yêu cầu': 'Withdrawal requirements',
  'Email xác minh': 'Email verification',
  'SĐT xác minh': 'Phone verification',
  'Đạt': 'Passed',
  'Cần bổ sung': 'Required',
  'Số tiền rút': 'Withdrawal amount',
  'Tài khoản nhận': 'Receiving account',
  'Tên ngân hàng': 'Bank name',
  'Tên chủ tài khoản': 'Account holder',
  'Số tài khoản': 'Account number',
  'Ghi chú (tùy chọn)': 'Note (optional)',
  'Gửi yêu cầu rút': 'Submit withdrawal',
  'Quy trình rút tiền': 'Withdrawal process',
  'Kiểm tra': 'Verification',
  'Chuyển tiền': 'Transfer',
  'Tổng quan Affiliate': 'Affiliate overview',
  'Liên kết giới thiệu': 'Referral link',
  'Hoa hồng': 'Commission',
  'Lượt giới thiệu': 'Referrals',
  'Sao chép': 'Copy',
  'Đã sao chép': 'Copied',
  'Giám sát tồn kho, trạng thái hiển thị và seller phát hành sản phẩm.': 'Monitor inventory, visibility, and the seller publishing each product.',
  'Mở chat': 'Open chat',
  'Theo dõi tài khoản, số dư, lịch sử nạp tiền và quyền truy cập.': 'Monitor accounts, balances, deposit history, and access permissions.',
  'Dữ liệu hiển thị theo bộ lọc hiện tại': 'Data shown for the current filters',
  'Tổng thành viên': 'Total members',
  'Số dư đang hiển thị': 'Displayed balance',
  'Quản trị viên': 'Administrators',
  'Tài khoản bị khóa': 'Banned accounts',
  'Danh sách thành viên': 'Member list',
  'Mở hồ sơ để kiểm tra lịch sử nạp tiền, đơn hàng và thay đổi trạng thái.': 'Open a profile to review deposits, orders, and status changes.',
  'Tìm và lọc ngay trên danh sách': 'Search and filter this list',
  'Tìm theo mã thành viên, tên hoặc email...': 'Search by member ID, name, or email...',
  'Hành động': 'Actions',
  'Xem': 'View',
  'Khóa tài khoản': 'Ban account',
  'Mở khóa tài khoản': 'Unban account',
  'Quản lý đơn đã thanh toán, bàn giao cho người mua và theo dõi doanh thu thực tế.': 'Manage paid orders, deliver to buyers, and track actual revenue.',
  'Tổng số đơn': 'Total orders',
  'Toàn bộ lịch sử': 'Full history',
  'Chờ thanh toán': 'Awaiting payment',
  'Cần theo dõi': 'Needs attention',
  'Đang bàn giao': 'Delivering',
  'Escrow đang giữ': 'Held in escrow',
  'Cần xử lý': 'Needs action',
  'Doanh thu hoàn về': 'Released revenue',
  'Số dư có thể rút': 'Available balance',
  'Đang giữ để payout': 'Held for payout',
  'Chờ xác nhận/release': 'Awaiting confirmation/release',
  'Xu hướng đơn hàng': 'Order trend',
  '14 ngày gần nhất · doanh thu chỉ tính đơn hoàn thành': 'Last 14 days · revenue includes completed orders only',
  '14 ngày': '14 days',
  'Tìm theo mã đơn, người mua hoặc sản phẩm...': 'Search order ID, buyer, or product...',
  'Mã đơn / Người mua': 'Order ID / Buyer',
  'Không có đơn hàng phù hợp.': 'No matching orders.',
  'Chọn một đơn hàng để xem chi tiết.': 'Select an order to view details.',
  'Sàn thương mại điện tử sản phẩm số hàng đầu': 'A leading digital product marketplace',
  'Mua bán sản phẩm số và dịch vụ số với hồ sơ người bán, bằng chứng bàn giao và quy trình hỗ trợ rõ ràng.': 'Trade digital products and services with seller profiles, delivery evidence, and a transparent support process.',
  'Giao dịch an toàn': 'Safe transactions',
  'Bảo vệ người mua': 'Buyer protection',
  'Quy trình rõ ràng': 'Clear process',
  'Minh bạch & dễ hiểu': 'Transparent and simple',
  'Thanh toán đa dạng': 'Flexible payments',
  'Nhanh chóng & tiện lợi': 'Fast and convenient',
  'Hỗ trợ tận tâm': 'Dedicated support',
  'Đồng hành 24/7': 'Available 24/7',
  'Không có dữ liệu': 'No data',
  'Đang tải...': 'Loading...',
  'Có lỗi xảy ra': 'An error occurred',
  'Thử lại': 'Try again',
};

const DYNAMIC_TRANSLATIONS: Array<[RegExp, string]> = [
  [/^(\d+) chưa đọc$/, '$1 unread'],
  [/^Kho:\s*(\d+)$/, 'Stock: $1'],
  [/^Còn:\s*(\d+)$/, '$1 available'],
  [/^Còn\s+(\d+)$/, '$1 available'],
  [/^Đã bán\s+(\d+)$/, '$1 sold'],
  [/^Hiển thị\s+(\d+)\s+dòng$/, 'Showing $1 rows'],
  [/^Tổng\s+(\d+)\s+kết quả$/, '$1 results'],
  [/^Trang\s+(\d+)$/, 'Page $1'],
];

function translated(value: string) {
  const trimmed = value.trim();
  if (!trimmed) return value;
  let result = ENGLISH_UI[trimmed];
  if (!result) {
    for (const [pattern, replacement] of DYNAMIC_TRANSLATIONS) {
      if (pattern.test(trimmed)) {
        result = trimmed.replace(pattern, replacement);
        break;
      }
    }
  }
  return result ? value.replace(trimmed, result) : value;
}

function translateTree(root: ParentNode) {
  const elements = root instanceof Element
    ? [root, ...Array.from(root.querySelectorAll('*'))]
    : Array.from(root.querySelectorAll('*'));

  for (const element of elements) {
    if (element.closest('[data-no-translate], script, style, code, pre')) continue;
    for (const attribute of ['placeholder', 'title', 'aria-label']) {
      const current = element.getAttribute(attribute);
      if (current) element.setAttribute(attribute, translated(current));
    }
    for (const node of Array.from(element.childNodes)) {
      if (node.nodeType === Node.TEXT_NODE && node.nodeValue) {
        node.nodeValue = translated(node.nodeValue);
      }
    }
  }
}

export default function LocaleDomTranslator({ locale }: { locale: string }) {
  useEffect(() => {
    if (locale !== 'en') return;
    translateTree(document.body);

    const observer = new MutationObserver((mutations) => {
      for (const mutation of mutations) {
        for (const node of Array.from(mutation.addedNodes)) {
          if (node instanceof Element) translateTree(node);
          else if (node.nodeType === Node.TEXT_NODE && node.nodeValue) node.nodeValue = translated(node.nodeValue);
        }
      }
    });
    observer.observe(document.body, { childList: true, subtree: true });
    return () => observer.disconnect();
  }, [locale]);

  return null;
}
