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

export type Lang = "bn" | "en";

const dict = {
  bn: {
    app_name: "Helpgate Inventory",
    tagline: "বাংলাদেশের জন্য পূর্ণাঙ্গ ইনভেন্টরি ও POS সিস্টেম",
    dashboard: "ড্যাশবোর্ড",
    products: "পণ্য",
    pos: "POS / বিক্রয়",
    sales: "বিক্রয় তালিকা",
    purchases: "ক্রয়",
    suppliers: "সাপ্লায়ার",
    customers: "কাস্টমার",
    categories: "ক্যাটাগরি",
    brands: "ব্র্যান্ড",
    expenses: "খরচ",
    reports: "রিপোর্ট",
    settings: "সেটিংস",
    logout: "লগ আউট",
    welcome: "স্বাগতম",
    today: "আজ",
    this_month: "এই মাস",
    this_year: "এই বছর",
    today_sales: "আজকের বিক্রি",
    today_profit: "আজকের লাভ",
    month_sales: "মাসের বিক্রি",
    month_profit: "মাসের লাভ",
    total_products: "মোট পণ্য",
    total_customers: "মোট কাস্টমার",
    customer_due: "কাস্টমার বকেয়া",
    supplier_due: "সাপ্লায়ার বকেয়া",
    low_stock: "স্টক কম",
    low_stock_items: "স্টক কম এমন পণ্য",
    recent_sales: "সাম্প্রতিক বিক্রি",
    top_products: "সেরা পণ্য",
    new_sale: "নতুন বিক্রয়",
    new_purchase: "নতুন ক্রয়",
    add_product: "নতুন পণ্য",
    add_supplier: "নতুন সাপ্লায়ার",
    add_customer: "নতুন কাস্টমার",
    add_category: "নতুন ক্যাটাগরি",
    add_brand: "নতুন ব্র্যান্ড",
    add_expense: "নতুন খরচ",
    name: "নাম",
    phone: "ফোন",
    address: "ঠিকানা",
    note: "নোট",
    save: "সংরক্ষণ",
    cancel: "বাতিল",
    edit: "সম্পাদনা",
    delete: "মুছুন",
    search: "খুঁজুন...",
    no_data: "কোনো তথ্য নেই",
    sku: "SKU / কোড",
    barcode: "বারকোড",
    cost_price: "ক্রয়মূল্য",
    sale_price: "বিক্রয়মূল্য",
    stock: "স্টক",
    category: "ক্যাটাগরি",
    brand: "ব্র্যান্ড",
    alert_threshold: "অ্যালার্ট সীমা",
    quantity: "পরিমাণ",
    price: "মূল্য",
    discount: "ডিসকাউন্ট",
    vat: "ভ্যাট",
    subtotal: "সাবটোটাল",
    total: "মোট",
    paid: "পরিশোধিত",
    due: "বকেয়া",
    payment_method: "পেমেন্ট মাধ্যম",
    cash: "ক্যাশ",
    bank: "ব্যাংক",
    mobile_banking: "মোবাইল ব্যাংকিং",
    customer: "কাস্টমার",
    supplier: "সাপ্লায়ার",
    walk_in: "ওয়াক-ইন কাস্টমার",
    invoice: "ইনভয়েস",
    print: "প্রিন্ট",
    complete_sale: "বিক্রয় সম্পন্ন",
    cart_empty: "কার্ট খালি",
    add_to_cart: "যোগ করুন",
    profit: "লাভ",
    revenue: "আয়",
    orders: "অর্ডার",
    amount: "পরিমাণ",
    date: "তারিখ",
    actions: "অ্যাকশন",
    confirm_delete: "নিশ্চিত মুছবেন?",
    saved: "সংরক্ষিত",
    deleted: "মুছে ফেলা হয়েছে",
    sign_in: "লগ ইন",
    sign_up: "সাইন আপ",
    email: "ইমেইল",
    password: "পাসওয়ার্ড",
    shop_name: "দোকানের নাম",
    new_account: "নতুন অ্যাকাউন্ট",
    have_account: "ইতিমধ্যে অ্যাকাউন্ট আছে",
    no_account: "নতুন ইউজার",
    expense_category: "খরচের ধরন",
    summary: "সারসংক্ষেপ",
    daily_breakdown: "দৈনিক বিভাজন",
    users: "ইউজার ও রোল",
    role: "ভূমিকা",
    super_admin: "সুপার অ্যাডমিন",
    salesman: "সেলসম্যান",
    change_role: "রোল পরিবর্তন",
    no_permission: "অনুমতি নেই",
    no_permission_desc: "এই পেজে প্রবেশের অনুমতি নেই। অ্যাডমিনের সাথে যোগাযোগ করুন।",
    unit: "একক",
    add_unit: "নতুন একক",
    pack_size: "প্যাক সাইজ (প্রতি কার্টন/বক্সে)",
    stock_adjust: "স্টক অ্যাডজাস্ট",
    adjust_in: "স্টক যোগ",
    adjust_out: "স্টক কমান",
    reason: "কারণ",
    auto: "অটো",
    cartons: "কার্টন সংখ্যা",
    units_per_carton: "প্রতি কার্টনে",
    total_stock: "মোট স্টক",
    direct_stock: "সরাসরি স্টক",
    carton_mode: "কার্টন হিসাবে",
    damaged: "নষ্ট পণ্য",
    add_damaged: "নষ্ট যোগ",
    daily_report: "দৈনিক রিপোর্ট",
    yesterday: "গতকাল",
    vs_yesterday: "গতকালের তুলনায়",
    deposit: "ডিপোজিট",
    pay_due: "বকেয়া পরিশোধ",
    new_supplier_quick: "+ নতুন সাপ্লায়ার",
    new_product_quick: "+ নতুন পণ্য",
    share_whatsapp: "WhatsApp এ শেয়ার",
    share_sms: "SMS পাঠাও",
    investments: "বিনিয়োগ",
    investor: "বিনিয়োগকারী",
    invested_at: "তারিখ",
    new_investment: "নতুন বিনিয়োগ",
    total_invested: "মোট বিনিয়োগ",
    per_carton: "প্রতি কার্টন/বস্তায়",
    unit_qty: "মোট পরিমাণ",
  },
  en: {
    app_name: "Helpgate Inventory",
    tagline: "Complete Inventory & POS System for Bangladesh",
    dashboard: "Dashboard",
    products: "Products",
    pos: "POS / Sale",
    sales: "Sales",
    purchases: "Purchases",
    suppliers: "Suppliers",
    customers: "Customers",
    categories: "Categories",
    brands: "Brands",
    expenses: "Expenses",
    reports: "Reports",
    settings: "Settings",
    logout: "Log out",
    welcome: "Welcome",
    today: "Today",
    this_month: "This Month",
    this_year: "This Year",
    today_sales: "Today's Sales",
    today_profit: "Today's Profit",
    month_sales: "Monthly Sales",
    month_profit: "Monthly Profit",
    total_products: "Total Products",
    total_customers: "Total Customers",
    customer_due: "Customer Due",
    supplier_due: "Supplier Due",
    low_stock: "Low Stock",
    low_stock_items: "Low Stock Items",
    recent_sales: "Recent Sales",
    top_products: "Top Products",
    new_sale: "New Sale",
    new_purchase: "New Purchase",
    add_product: "Add Product",
    add_supplier: "Add Supplier",
    add_customer: "Add Customer",
    add_category: "Add Category",
    add_brand: "Add Brand",
    add_expense: "Add Expense",
    name: "Name",
    phone: "Phone",
    address: "Address",
    note: "Note",
    save: "Save",
    cancel: "Cancel",
    edit: "Edit",
    delete: "Delete",
    search: "Search...",
    no_data: "No data",
    sku: "SKU",
    barcode: "Barcode",
    cost_price: "Cost Price",
    sale_price: "Sale Price",
    stock: "Stock",
    category: "Category",
    brand: "Brand",
    alert_threshold: "Alert Threshold",
    quantity: "Quantity",
    price: "Price",
    discount: "Discount",
    vat: "VAT",
    subtotal: "Subtotal",
    total: "Total",
    paid: "Paid",
    due: "Due",
    payment_method: "Payment Method",
    cash: "Cash",
    bank: "Bank",
    mobile_banking: "Mobile Banking",
    customer: "Customer",
    supplier: "Supplier",
    walk_in: "Walk-in Customer",
    invoice: "Invoice",
    print: "Print",
    complete_sale: "Complete Sale",
    cart_empty: "Cart is empty",
    add_to_cart: "Add",
    profit: "Profit",
    revenue: "Revenue",
    orders: "Orders",
    amount: "Amount",
    date: "Date",
    actions: "Actions",
    confirm_delete: "Confirm delete?",
    saved: "Saved",
    deleted: "Deleted",
    sign_in: "Sign In",
    sign_up: "Sign Up",
    email: "Email",
    password: "Password",
    shop_name: "Shop Name",
    new_account: "New Account",
    have_account: "Have an account?",
    no_account: "No account?",
    expense_category: "Expense Category",
    summary: "Summary",
    daily_breakdown: "Daily Breakdown",
    users: "Users & Roles",
    role: "Role",
    super_admin: "Super Admin",
    salesman: "Salesman",
    change_role: "Change Role",
    no_permission: "No Permission",
    no_permission_desc: "You do not have permission to access this page. Please contact your admin.",
    unit: "Unit",
    add_unit: "Add Unit",
    pack_size: "Pack Size (units per carton/box)",
    stock_adjust: "Stock Adjust",
    adjust_in: "Stock In",
    adjust_out: "Stock Out",
    reason: "Reason",
    auto: "Auto",
    cartons: "No. of Cartons",
    units_per_carton: "Units per Carton",
    total_stock: "Total Stock",
    direct_stock: "Direct Stock",
    carton_mode: "Carton Mode",
    damaged: "Damaged",
    add_damaged: "Add Damaged",
    daily_report: "Daily Report",
    yesterday: "Yesterday",
    vs_yesterday: "vs Yesterday",
    deposit: "Deposit",
    pay_due: "Pay Due",
    new_supplier_quick: "+ New Supplier",
    new_product_quick: "+ New Product",
    share_whatsapp: "Share on WhatsApp",
    share_sms: "Send SMS",
    investments: "Investments",
    investor: "Investor",
    invested_at: "Date",
    new_investment: "New Investment",
    total_invested: "Total Invested",
    per_carton: "Per Carton/Bag",
    unit_qty: "Total Qty",
  },
} as const;

export type TKey = keyof (typeof dict)["bn"];

type I18nCtx = { lang: Lang; setLang: (l: Lang) => void; t: (k: TKey) => string };
const Ctx = createContext<I18nCtx | null>(null);

export function I18nProvider({ children }: { children: ReactNode }) {
  const [lang, setLangState] = useState<Lang>(() => {
    if (typeof window === "undefined") return "bn";
    return (localStorage.getItem("lang") as Lang) || "bn";
  });
  useEffect(() => {
    document.documentElement.lang = lang;
  }, [lang]);
  const setLang = (l: Lang) => {
    setLangState(l);
    if (typeof window !== "undefined") localStorage.setItem("lang", l);
  };
  const t = (k: TKey) => dict[lang][k] ?? k;
  return <Ctx.Provider value={{ lang, setLang, t }}>{children}</Ctx.Provider>;
}

export const useT = () => {
  const c = useContext(Ctx);
  if (!c) throw new Error("useT outside I18nProvider");
  return c;
};

export const fmtMoney = (n: number, lang: Lang = "bn") =>
  `৳${Number(n || 0).toLocaleString(lang === "bn" ? "bn-BD" : "en-IN", { maximumFractionDigits: 2 })}`;
