// AppContext.tsx — Single unified context for the entire app
import { createContext, useContext, useState, useEffect } from 'react';
import defaultProducts from '../data/defaultProducts';

// Types
export interface Product {
  id: string;
  name: string;
  slug: string;
  category: string;
  subcategory: string;
  image: string;
  badge?: string;
  shortDesc: string;
  description: string;
  features: string[];
  benefits: string[];
  plans: string[];
  activation: string;
  deliveryTime: string;
  faqs: { question: string; answer: string }[];
  reviews: { name: string; location: string; rating: number; text: string; verified: boolean }[];
  metaTitle: string;
  metaDesc: string;
  h1: string;
}

export type Currency = 'INR' | 'USD';
export type Language = 'en' | 'hi' | 'zh';

interface AppState {
  // Products
  products: Product[];
  addProduct: (product: Product) => void;
  updateProduct: (id: string, product: Partial<Product>) => void;
  deleteProduct: (id: string) => void;
  getProductBySlug: (slug: string) => Product | undefined;
  getProductsByCategory: (category: string) => Product[];

  // Currency
  currency: Currency;
  setCurrency: (c: Currency) => void;

  // Language
  language: Language;
  setLanguage: (l: Language) => void;
  t: (key: string) => string;

  // Admin
  isAdmin: boolean;
  adminLogin: (email: string, password: string) => boolean;
  adminLogout: () => void;
}

const AppContext = createContext<AppState | null>(null);

// Translation dictionaries — 150+ keys per language
const translations: Record<Language, Record<string, string>> = {
  en: {
    // Navbar
    home: 'Home',
    shop: 'Shop',
    blog: 'Blog',
    reviews: 'Reviews',
    about: 'About',
    faq: 'FAQ',
    contact: 'Contact',
    categories: 'Categories',
    search: 'Search',
    shopNow: 'Shop Now',

    // Product
    buyOnWhatsApp: 'Buy on WhatsApp',
    buyOnTelegram: 'Buy on Telegram',
    viewDetails: 'View Details',
    features: 'Features',
    benefits: 'Benefits',
    plans: 'Plans',
    activation: 'Activation',
    delivery: 'Delivery',
    relatedProducts: 'Related Products',
    worldwideDelivery: 'Worldwide Delivery',
    genuineLicense: 'Genuine License',
    instantDelivery: 'Instant Delivery',
    sevenDayRefund: '7-Day Refund',
    twentyFourHourFix: '24h Fix Guarantee',
    securePayment: 'Secure Payment',
    deliveryTime: 'Delivery Time',
    youMayAlsoLike: 'You May Also Like',
    commonQuestions: 'Common Questions',
    whatBuyersSay: 'What Buyers Say',

    // Shop
    allProducts: 'All Products',
    searchProducts: 'Search products...',
    browseAll: 'Browse All',
    designTools: 'Design Tools',
    aiTools: 'AI Tools',
    videoAudio: 'Video & Audio',
    creativeAssets: 'Creative Assets',
    featured: 'Featured',
    mostPopular: 'Most Popular',
    filterBy: 'Filter by',
    noProductsFound: 'No products found',
    clearFilters: 'Clear Filters',
    products: 'Products',

    // Footer
    quickLinks: 'Quick Links',
    legal: 'Legal',
    contactUs: 'Contact Us',
    terms: 'Terms of Service',
    privacy: 'Privacy Policy',
    refund: 'Refund Policy',
    deliveryPolicy: 'Delivery Policy',
    responseTime: 'Response: < 10 min',
    worldwideFooter: 'Delivered to 40+ countries worldwide | Free global support',

    // Home
    trustedBy: 'Trusted by 50,000+ Customers',
    heroTitle: "India's Most Trusted",
    heroSubtitle: 'Digital Tools Store',
    trendingProducts: 'Trending Products This Week',
    viewAll: 'View All',
    howItWorks: 'How It Works',
    step1: 'Choose Your Product',
    step2: 'Order via WhatsApp',
    step3: 'Get Instant Access',
    testimonials: 'Testimonials',
    blogPreview: 'From the Blog',
    ctaTitle: 'Ready to Get Started?',
    whyChooseUs: 'Why Choose Us',
    browseCategories: 'Browse Categories',
    mostPopularLabel: 'Most Popular',
    ordersDelivered: 'Orders Delivered',
    happyUsers: 'Happy Users',
    countriesServed: 'Countries',
    averageRating: 'Average Rating',
    findPerfectTool: 'Find Your Perfect Tool',
    tipsGuidesComparisons: 'Tips, Guides & Comparisons',
    getToolsIn3Steps: 'Get Your Tools in 3 Simple Steps',
    whatCustomersSay: 'What Our Customers Say',

    // Admin
    dashboard: 'Dashboard',
    addProduct: 'Add Product',
    editProduct: 'Edit Product',
    delete: 'Delete',
    save: 'Save',
    cancel: 'Cancel',
    name: 'Name',
    price: 'Price',
    category: 'Category',
    description: 'Description',
    login: 'Login',
    password: 'Password',
    adminPanel: 'Admin Panel',
    totalProducts: 'Total Products',
    totalCategories: 'Total Categories',
    recentProducts: 'Recent Products',
    quickActions: 'Quick Actions',
    viewAllProducts: 'View All Products',
    actions: 'Actions',
    badge: 'Badge',
    searchProductsAdmin: 'Search products...',
    addNewProduct: 'Add New Product',
    slug: 'Slug',
    subcategory: 'Subcategory',
    shortDesc: 'Short Description',
    fullDescription: 'Full Description',
    featureList: 'Features',
    benefitList: 'Benefits',
    planList: 'Available Plans',
    activationMethod: 'Activation Method',
    deliveryTimeLabel: 'Delivery Time',
    faqList: 'FAQs',
    reviewList: 'Reviews',
    verified: 'Verified',
    rating: 'Rating',

    // Common
    loading: 'Loading...',
    error: 'Error',
    notFound: 'Not Found',
    back: 'Back',
    submit: 'Submit',
    close: 'Close',
    open: 'Open',
    yes: 'Yes',
    no: 'No',
    confirm: 'Confirm',
    areYouSure: 'Are you sure?',
    deleteConfirm: 'This action cannot be undone.',

    // Free Tools
    freeToolsTitle: 'Free Premium Tools for Students & Creators',
    getFreeAccess: 'Get Free Access',

    // Thank You
    thankYouTitle: 'Your order request has been sent!',
    thankYouSubtitle: 'We will contact you on WhatsApp within 10 minutes',
    backToShop: 'Back to Shop',

    // FAQ specific (used by FAQ page)
    whatPaymentMethods: 'What payment methods do you accept?',
    howFastDelivery: 'How fast is the delivery?',
    areTheseGenuine: 'Are these products genuine?',
    whatRefundPolicy: 'What is your refund policy?',
    howGetSupport: 'How do I get support?',
    canTrust: 'Can I trust MFA Tools Net?',

    // Worldwide
    worldwideBanner: 'We deliver genuine digital tools worldwide — 40+ countries served | 24/7 Global Support',
    worldwideHeader: 'We deliver worldwide!',

    // Currency / Language
    currency: 'Currency',
    language: 'Language',
    inr: 'INR',
    usd: 'USD',
    en: 'EN',
    hi: 'HI',
    zh: '中文',

    // Misc
    chooseProduct: 'Choose Your Product',
    orderViaWhatsApp: 'Order via WhatsApp',
    getInstantAccess: 'Get Instant Access',
    noCreditCard: 'No credit card needed',
    twoTenMinDelivery: '2-10 min delivery',
    safeGenuine: '100% safe & genuine',
    fourPointNine: '4.9/5 rated',
    followUs: 'Follow us:',
    joinCommunity: 'Join Our Community',
    shareExperience: 'Share Your Experience',
    writeReview: 'Write a Review on Trustpilot',
    stillHaveQuestions: 'Still Have Questions?',
    chatWhatsApp: 'Chat on WhatsApp',
    messageTelegram: 'Message on Telegram',
    genuineOnly: 'Genuine Only',
    honestPricing: 'Honest Pricing',
    realSupport: 'Real Support',
    ourStory: 'Our Story',
    ourValues: 'What We Stand For',
    milestones: 'Milestones',
    getTouch: 'Get in Touch',
    orderInSeconds: 'Order in Seconds',
    selectProduct: 'Select a product',
    yourName: 'Your Name (optional)',
    messagePreview: 'Message Preview',
    orderOnWhatsApp: 'Order on WhatsApp',
    orderOnTelegram: 'Order on Telegram',
    supportDetails: 'Support Details',
    howWeHelp: 'How We Help',
    businessInfo: 'Business Information',
    quickStats: 'Quick Stats',
  },
  hi: {
    // Navbar
    home: 'होम',
    shop: 'दुकान',
    blog: 'ब्लॉग',
    reviews: 'समीक्षाएं',
    about: 'हमारे बारे में',
    faq: 'अक्सर पूछे जाने वाले प्रश्न',
    contact: 'संपर्क करें',
    categories: 'श्रेणियां',
    search: 'खोजें',
    shopNow: 'अभी खरीदें',

    // Product
    buyOnWhatsApp: 'WhatsApp पर खरीदें',
    buyOnTelegram: 'Telegram पर खरीदें',
    viewDetails: 'विवरण देखें',
    features: 'विशेषताएं',
    benefits: 'लाभ',
    plans: 'योजनाएं',
    activation: 'सक्रियण',
    delivery: 'डिलीवरी',
    relatedProducts: 'संबंधित उत्पाद',
    worldwideDelivery: 'विश्वव्यापी डिलीवरी',
    genuineLicense: 'वास्तविक लाइसेंस',
    instantDelivery: 'त्वरित डिलीवरी',
    sevenDayRefund: '7-दिन की धनवापसी',
    twentyFourHourFix: '24 घंटे में ठीक करने की गारंटी',
    securePayment: 'सुरक्षित भुगतान',
    deliveryTime: 'डिलीवरी का समय',
    youMayAlsoLike: 'आपको ये भी पसंद आ सकता है',
    commonQuestions: 'सामान्य प्रश्न',
    whatBuyersSay: 'खरीदार क्या कहते हैं',

    // Shop
    allProducts: 'सभी उत्पाद',
    searchProducts: 'उत्पाद खोजें...',
    browseAll: 'सब ब्राउज़ करें',
    designTools: 'डिजाइन टूल',
    aiTools: 'AI टूल',
    videoAudio: 'वीडियो और ऑडियो',
    creativeAssets: 'क्रिएटिव एसेट',
    featured: 'विशेष रुप से प्रदर्शित',
    mostPopular: 'सबसे लोकप्रिय',
    filterBy: 'फिल्टर करें',
    noProductsFound: 'कोई उत्पाद नहीं मिला',
    clearFilters: 'फिल्टर हटाएं',
    products: 'उत्पाद',

    // Footer
    quickLinks: 'त्वरित लिंक',
    legal: 'कानूनी',
    contactUs: 'हमसे संपर्क करें',
    terms: 'सेवा की शर्तें',
    privacy: 'गोपनीयता नीति',
    refund: 'धनवापसी नीति',
    deliveryPolicy: 'डिलीवरी नीति',
    responseTime: 'प्रतिक्रिया: < 10 मिनट',
    worldwideFooter: '40+ देशों में विश्वव्यापी डिलीवरी | मुफ्त वैश्विक सहायता',

    // Home
    trustedBy: '50,000+ ग्राहकों द्वारा भरोसा किया गया',
    heroTitle: 'भारत का सबसे भरोसेमंद',
    heroSubtitle: 'डिजिटल टूल स्टोर',
    trendingProducts: 'इस सप्ताह के ट्रेंडिंग उत्पाद',
    viewAll: 'सब देखें',
    howItWorks: 'यह कैसे काम करता है',
    step1: 'अपना उत्पाद चुनें',
    step2: 'WhatsApp पर ऑर्डर करें',
    step3: 'तुरंत एक्सेस पाएं',
    testimonials: 'प्रशंसापत्र',
    blogPreview: 'ब्लॉग से',
    ctaTitle: 'शुरू करने के लिए तैयार हैं?',
    whyChooseUs: 'हमें क्यों चुनें',
    browseCategories: 'श्रेणियां ब्राउज़ करें',
    mostPopularLabel: 'सबसे लोकप्रिय',
    ordersDelivered: 'ऑर्डर डिलीवर किए',
    happyUsers: 'खुश ग्राहक',
    countriesServed: 'देश',
    averageRating: 'औसत रेटिंग',
    findPerfectTool: 'अपना सही टूल खोजें',
    tipsGuidesComparisons: 'सुझाव, गाइड और तुलनाएं',
    getToolsIn3Steps: '3 सरल चरणों में अपने टूल प्राप्त करें',
    whatCustomersSay: 'हमारे ग्राहक क्या कहते हैं',

    // Admin
    dashboard: 'डैशबोर्ड',
    addProduct: 'उत्पाद जोड़ें',
    editProduct: 'उत्पाद संपादित करें',
    delete: 'हटाएं',
    save: 'सहेजें',
    cancel: 'रद्द करें',
    name: 'नाम',
    price: 'कीमत',
    category: 'श्रेणी',
    description: 'विवरण',
    login: 'लॉगिन',
    password: 'पासवर्ड',
    adminPanel: 'व्यवस्थापक पैनल',
    totalProducts: 'कुल उत्पाद',
    totalCategories: 'कुल श्रेणियां',
    recentProducts: 'हाल के उत्पाद',
    quickActions: 'त्वरित कार्रवाइयां',
    viewAllProducts: 'सभी उत्पाद देखें',
    actions: 'कार्रवाइयां',
    badge: 'बैज',
    searchProductsAdmin: 'उत्पाद खोजें...',
    addNewProduct: 'नया उत्पाद जोड़ें',
    slug: 'स्लग',
    subcategory: 'उपश्रेणी',
    shortDesc: 'संक्षिप्त विवरण',
    fullDescription: 'पूर्ण विवरण',
    featureList: 'विशेषताएं',
    benefitList: 'लाभ',
    planList: 'उपलब्ध योजनाएं',
    activationMethod: 'सक्रियण विधि',
    deliveryTimeLabel: 'डिलीवरी का समय',
    faqList: 'अक्सर पूछे जाने वाले प्रश्न',
    reviewList: 'समीक्षाएं',
    verified: 'सत्यापित',
    rating: 'रेटिंग',

    // Common
    loading: 'लोड हो रहा है...',
    error: 'त्रुटि',
    notFound: 'नहीं मिला',
    back: 'वापस',
    submit: 'जमा करें',
    close: 'बंद करें',
    open: 'खोलें',
    yes: 'हां',
    no: 'नहीं',
    confirm: 'पुष्टि करें',
    areYouSure: 'क्या आप निश्चित हैं?',
    deleteConfirm: 'यह कार्रवाई पूर्ववत नहीं की जा सकती।',

    // Free Tools
    freeToolsTitle: 'छात्रों और निर्माताओं के लिए मुफ्त प्रीमियम टूल',
    getFreeAccess: 'मुफ्त एक्सेस पाएं',

    // Thank You
    thankYouTitle: 'आपका ऑर्डर अनुरोध भेज दिया गया है!',
    thankYouSubtitle: 'हम 10 मिनट के भीतर आपसे WhatsApp पर संपर्क करेंगे',
    backToShop: 'दुकान पर वापस जाएं',

    // FAQ specific (used by FAQ page)
    whatPaymentMethods: 'आप कौन से भुगतान तरीके स्वीकार करते हैं?',
    howFastDelivery: 'डिलीवरी कितनी तेज़ है?',
    areTheseGenuine: 'क्या ये उत्पाद असली हैं?',
    whatRefundPolicy: 'आपकी धनवापसी नीति क्या है?',
    howGetSupport: 'मुझे सहायता कैसे मिलेगी?',
    canTrust: 'क्या मैं MFA Tools Net पर भरोसा कर सकता हूँ?',

    // Worldwide
    worldwideBanner: 'हम दुनिया भर में असली डिजिटल टूल डिलीवर करते हैं — 40+ देश | 24/7 वैश्विक सहायता',
    worldwideHeader: 'हम दुनिया भर में डिलीवर करते हैं!',

    // Currency / Language
    currency: 'मुद्रा',
    language: 'भाषा',
    inr: 'INR',
    usd: 'USD',
    en: 'EN',
    hi: 'HI',
    zh: '中文',

    // Misc
    chooseProduct: 'अपना उत्पाद चुनें',
    orderViaWhatsApp: 'WhatsApp पर ऑर्डर करें',
    getInstantAccess: 'तुरंत एक्सेस पाएं',
    noCreditCard: 'क्रेडिट कार्ड की आवश्यकता नहीं',
    twoTenMinDelivery: '2-10 मिनट डिलीवरी',
    safeGenuine: '100% सुरक्षित और असली',
    fourPointNine: '4.9/5 रेटेड',
    followUs: 'हमें फॉलो करें:',
    joinCommunity: 'हमारे समुदाय में शामिल हों',
    shareExperience: 'अपना अनुभव साझा करें',
    writeReview: 'Trustpilot पर समीक्षा लिखें',
    stillHaveQuestions: 'अभी भी सवाल हैं?',
    chatWhatsApp: 'WhatsApp पर चैट करें',
    messageTelegram: 'Telegram पर संदेश भेजें',
    genuineOnly: 'केवल असली',
    honestPricing: 'ईमानदार मूल्य निर्धारण',
    realSupport: 'वास्तविक सहायता',
    ourStory: 'हमारी कहानी',
    ourValues: 'हमारे मूल्य',
    milestones: 'मील के पत्थर',
    getTouch: 'संपर्क में रहें',
    orderInSeconds: 'सेकंड में ऑर्डर करें',
    selectProduct: 'एक उत्पाद चुनें',
    yourName: 'आपका नाम (वैकल्पिक)',
    messagePreview: 'संदेश पूर्वावलोकन',
    orderOnWhatsApp: 'WhatsApp पर ऑर्डर करें',
    orderOnTelegram: 'Telegram पर ऑर्डर करें',
    supportDetails: 'सहायता विवरण',
    howWeHelp: 'हम कैसे मदद करते हैं',
    businessInfo: 'व्यावसायिक जानकारी',
    quickStats: 'त्वरित आंकड़े',
  },
  zh: {
    // Navbar
    home: '首页',
    shop: '商店',
    blog: '博客',
    reviews: '评价',
    about: '关于我们',
    faq: '常见问题',
    contact: '联系我们',
    categories: '分类',
    search: '搜索',
    shopNow: '立即购买',

    // Product
    buyOnWhatsApp: 'WhatsApp购买',
    buyOnTelegram: 'Telegram购买',
    viewDetails: '查看详情',
    features: '功能',
    benefits: '优势',
    plans: '套餐',
    activation: '激活方式',
    delivery: '交付',
    relatedProducts: '相关产品',
    worldwideDelivery: '全球配送',
    genuineLicense: '正版授权',
    instantDelivery: '即时交付',
    sevenDayRefund: '7天退款',
    twentyFourHourFix: '24小时修复保证',
    securePayment: '安全支付',
    deliveryTime: '交付时间',
    youMayAlsoLike: '您可能还喜欢',
    commonQuestions: '常见问题',
    whatBuyersSay: '买家评价',

    // Shop
    allProducts: '所有产品',
    searchProducts: '搜索产品...',
    browseAll: '浏览全部',
    designTools: '设计工具',
    aiTools: 'AI工具',
    videoAudio: '视频与音频',
    creativeAssets: '创意素材',
    featured: '精选',
    mostPopular: '最受欢迎',
    filterBy: '筛选',
    noProductsFound: '未找到产品',
    clearFilters: '清除筛选',
    products: '产品',

    // Footer
    quickLinks: '快速链接',
    legal: '法律条款',
    contactUs: '联系我们',
    terms: '服务条款',
    privacy: '隐私政策',
    refund: '退款政策',
    deliveryPolicy: '配送政策',
    responseTime: '响应时间：<10分钟',
    worldwideFooter: '全球40+国家配送 | 免费全球支持',

    // Home
    trustedBy: '50,000+客户信赖',
    heroTitle: '印度最值得信赖的',
    heroSubtitle: '数字工具商店',
    trendingProducts: '本周热门产品',
    viewAll: '查看全部',
    howItWorks: '工作原理',
    step1: '选择您的产品',
    step2: '通过WhatsApp下单',
    step3: '立即获得访问权限',
    testimonials: '客户评价',
    blogPreview: '博客精选',
    ctaTitle: '准备好开始了吗？',
    whyChooseUs: '为什么选择我们',
    browseCategories: '浏览分类',
    mostPopularLabel: '最受欢迎',
    ordersDelivered: '已交付订单',
    happyUsers: '满意用户',
    countriesServed: '服务国家',
    averageRating: '平均评分',
    findPerfectTool: '找到您的完美工具',
    tipsGuidesComparisons: '技巧、指南与对比',
    getToolsIn3Steps: '3个简单步骤获取工具',
    whatCustomersSay: '客户评价',

    // Admin
    dashboard: '仪表盘',
    addProduct: '添加产品',
    editProduct: '编辑产品',
    delete: '删除',
    save: '保存',
    cancel: '取消',
    name: '名称',
    price: '价格',
    category: '分类',
    description: '描述',
    login: '登录',
    password: '密码',
    adminPanel: '管理后台',
    totalProducts: '产品总数',
    totalCategories: '分类总数',
    recentProducts: '最近产品',
    quickActions: '快捷操作',
    viewAllProducts: '查看所有产品',
    actions: '操作',
    badge: '徽章',
    searchProductsAdmin: '搜索产品...',
    addNewProduct: '添加新产品',
    slug: '链接标识',
    subcategory: '子分类',
    shortDesc: '简短描述',
    fullDescription: '完整描述',
    featureList: '功能列表',
    benefitList: '优势列表',
    planList: '可用套餐',
    activationMethod: '激活方式',
    deliveryTimeLabel: '交付时间',
    faqList: '常见问题',
    reviewList: '评价',
    verified: '已验证',
    rating: '评分',

    // Common
    loading: '加载中...',
    error: '错误',
    notFound: '未找到',
    back: '返回',
    submit: '提交',
    close: '关闭',
    open: '打开',
    yes: '是',
    no: '否',
    confirm: '确认',
    areYouSure: '您确定吗？',
    deleteConfirm: '此操作无法撤销。',

    // Free Tools
    freeToolsTitle: '学生和创作者的免费高级工具',
    getFreeAccess: '获取免费访问',

    // Thank You
    thankYouTitle: '您的订单请求已发送！',
    thankYouSubtitle: '我们将在10分钟内通过WhatsApp联系您',
    backToShop: '返回商店',

    // FAQ specific (used by FAQ page)
    whatPaymentMethods: '你们接受哪些付款方式？',
    howFastDelivery: '配送有多快？',
    areTheseGenuine: '这些产品是正版的吗？',
    whatRefundPolicy: '你们的退款政策是什么？',
    howGetSupport: '如何获得支持？',
    canTrust: '我可以信任MFA Tools Net吗？',

    // Worldwide
    worldwideBanner: '我们在全球40+国家提供正版数字工具 | 24/7全球支持',
    worldwideHeader: '我们提供全球配送！',

    // Currency / Language
    currency: '货币',
    language: '语言',
    inr: 'INR',
    usd: 'USD',
    en: 'EN',
    hi: 'HI',
    zh: '中文',

    // Misc
    chooseProduct: '选择您的产品',
    orderViaWhatsApp: '通过WhatsApp下单',
    getInstantAccess: '立即获得访问权限',
    noCreditCard: '无需信用卡',
    twoTenMinDelivery: '2-10分钟交付',
    safeGenuine: '100%安全正版',
    fourPointNine: '4.9/5评分',
    followUs: '关注我们：',
    joinCommunity: '加入我们的社区',
    shareExperience: '分享您的体验',
    writeReview: '在Trustpilot上写评价',
    stillHaveQuestions: '还有疑问？',
    chatWhatsApp: 'WhatsApp聊天',
    messageTelegram: 'Telegram留言',
    genuineOnly: '仅正版',
    honestPricing: '诚信定价',
    realSupport: '真实支持',
    ourStory: '我们的故事',
    ourValues: '我们的价值观',
    milestones: '里程碑',
    getTouch: '保持联系',
    orderInSeconds: '秒速下单',
    selectProduct: '选择产品',
    yourName: '您的姓名（可选）',
    messagePreview: '消息预览',
    orderOnWhatsApp: 'WhatsApp下单',
    orderOnTelegram: 'Telegram下单',
    supportDetails: '支持详情',
    howWeHelp: '我们如何帮助您',
    businessInfo: '商业信息',
    quickStats: '快速统计',
  },
};

export function AppProvider({ children }: { children: React.ReactNode }) {
  const [products, setProducts] = useState<Product[]>(() => {
    const saved = localStorage.getItem('mfa-products');
    return saved ? JSON.parse(saved) : defaultProducts;
  });

  const [currency, setCurrencyState] = useState<Currency>(() => {
    return (localStorage.getItem('mfa-currency') as Currency) || 'INR';
  });

  const [language, setLanguageState] = useState<Language>(() => {
    const saved = localStorage.getItem('mfa-language') as Language;
    if (saved) return saved;
    const browserLang = navigator.language.split('-')[0];
    if (browserLang === 'hi') return 'hi';
    if (browserLang === 'zh') return 'zh';
    return 'en';
  });

  const [isAdmin, setIsAdmin] = useState(() => {
    return localStorage.getItem('mfa-admin-auth') === 'true';
  });

  // Persist products to localStorage
  useEffect(() => {
    localStorage.setItem('mfa-products', JSON.stringify(products));
  }, [products]);

  useEffect(() => { localStorage.setItem('mfa-currency', currency); }, [currency]);
  useEffect(() => { localStorage.setItem('mfa-language', language); }, [language]);

  const addProduct = (product: Product) => setProducts(prev => [...prev, product]);
  const updateProduct = (id: string, updates: Partial<Product>) => {
    setProducts(prev => prev.map(p => p.id === id ? { ...p, ...updates } : p));
  };
  const deleteProduct = (id: string) => setProducts(prev => prev.filter(p => p.id !== id));
  const getProductBySlug = (slug: string) => products.find(p => p.slug === slug);
  const getProductsByCategory = (category: string) =>
    category === 'all' ? products : products.filter(p => p.category === category);

  const setCurrency = (c: Currency) => setCurrencyState(c);
  const setLanguage = (l: Language) => setLanguageState(l);

  const t = (key: string) => translations[language][key] || translations.en[key] || key;

  const adminLogin = (email: string, password: string) => {
    if (email === 'akashpatilkale1111@gmail.com' && password === 'Ayushi@0337') {
      setIsAdmin(true);
      localStorage.setItem('mfa-admin-auth', 'true');
      return true;
    }
    return false;
  };
  const adminLogout = () => {
    setIsAdmin(false);
    localStorage.removeItem('mfa-admin-auth');
  };

  return (
    <AppContext.Provider value={{
      products, addProduct, updateProduct, deleteProduct, getProductBySlug, getProductsByCategory,
      currency, setCurrency,
      language, setLanguage, t,
      isAdmin, adminLogin, adminLogout
    }}>
      {children}
    </AppContext.Provider>
  );
}

export const useApp = () => {
  const ctx = useContext(AppContext);
  if (!ctx) throw new Error('useApp must be used within AppProvider');
  return ctx;
};
