// src/App.jsx — Audical Services main app
const { useState, useEffect, useContext, createContext, useCallback, useRef, useMemo } = React;

// ── Context ──────────────────────────────────────────────────
const AppContext = createContext(null);

const useApp = () => useContext(AppContext);

// ── i18n ─────────────────────────────────────────────────────
const TRANSLATIONS = {
  en: {
    home: 'Home', products: 'Products', cart: 'Cart', login: 'Login',
    logout: 'Logout', admin: 'Admin', search: 'Search products…',
    addToCart: 'Add to Cart', checkout: 'Checkout', total: 'Total',
    empty_cart: 'Your cart is empty', proceed: 'Proceed to Checkout',
    otp_sent: 'OTP sent to your email', verify: 'Verify', resend: 'Resend',
    name: 'Name', email: 'Email', price: 'Price', stock: 'In Stock',
    dashboard: 'Dashboard', orders: 'Orders', customers: 'Customers',
    settings: 'Settings', products_admin: 'Products', upload: 'Upload',
    save: 'Save', cancel: 'Cancel', delete: 'Delete', edit: 'Edit',
    add_product: 'Add Product', order_id: 'Order #', status: 'Status',
    revenue: 'Revenue', welcome: 'Welcome back,', theme_toggle: 'Toggle theme',
    language: 'Language', filter: 'Filter', all: 'All', category: 'Category',
    description: 'Description', quantity: 'Qty', remove: 'Remove',
    continue_shopping: 'Continue Shopping', place_order: 'Place Order',
    payment_method: 'Payment Method', shipping: 'Shipping Info',
    address: 'Address', phone: 'Phone', city: 'City', zip: 'ZIP',
    export_pdf: 'Export PDF', new: 'New', active: 'Active', inactive: 'Inactive',
    pending: 'Pending', completed: 'Completed', cancelled: 'Cancelled',
    upload_image: 'Upload Image', drag_drop: 'Drag & drop or click to upload',
    notifications: 'Notifications', mark_read: 'Mark all read',
    no_notifications: 'No new notifications', role: 'Role',
    password: 'Password', confirm_password: 'Confirm Password',
    search_placeholder: 'Search by name, category…',
  },
  es: {
    home: 'Inicio', products: 'Productos', cart: 'Carrito', login: 'Iniciar',
    logout: 'Salir', admin: 'Admin', search: 'Buscar productos…',
    addToCart: 'Agregar', checkout: 'Pagar', total: 'Total',
    empty_cart: 'Tu carrito está vacío', proceed: 'Proceder al pago',
    otp_sent: 'OTP enviado a tu correo', verify: 'Verificar', resend: 'Reenviar',
    name: 'Nombre', email: 'Correo', price: 'Precio', stock: 'Disponible',
    dashboard: 'Panel', orders: 'Pedidos', customers: 'Clientes',
    settings: 'Ajustes', products_admin: 'Productos', upload: 'Subir',
    save: 'Guardar', cancel: 'Cancelar', delete: 'Eliminar', edit: 'Editar',
    add_product: 'Agregar Producto', order_id: 'Pedido #', status: 'Estado',
    revenue: 'Ingresos', welcome: 'Bienvenido,', theme_toggle: 'Cambiar tema',
    language: 'Idioma', filter: 'Filtro', all: 'Todo', category: 'Categoría',
    description: 'Descripción', quantity: 'Cant', remove: 'Quitar',
    continue_shopping: 'Seguir comprando', place_order: 'Hacer pedido',
    payment_method: 'Método de pago', shipping: 'Envío',
    address: 'Dirección', phone: 'Teléfono', city: 'Ciudad', zip: 'CP',
    export_pdf: 'Exportar PDF', new: 'Nuevo', active: 'Activo', inactive: 'Inactivo',
    pending: 'Pendiente', completed: 'Completado', cancelled: 'Cancelado',
    upload_image: 'Subir imagen', drag_drop: 'Arrastra o haz clic',
    notifications: 'Notificaciones', mark_read: 'Marcar todo leído',
    no_notifications: 'Sin notificaciones', role: 'Rol',
    password: 'Contraseña', confirm_password: 'Confirmar contraseña',
    search_placeholder: 'Buscar por nombre, categoría…',
  },
  vi: {
    home: 'Trang chủ', products: 'Sản phẩm', cart: 'Giỏ hàng', login: 'Đăng nhập',
    logout: 'Đăng xuất', admin: 'Quản trị', search: 'Tìm sản phẩm…',
    addToCart: 'Thêm vào giỏ', checkout: 'Thanh toán', total: 'Tổng',
    empty_cart: 'Giỏ hàng trống', proceed: 'Tiến hành thanh toán',
    otp_sent: 'OTP đã gửi', verify: 'Xác nhận', resend: 'Gửi lại',
    name: 'Tên', email: 'Email', price: 'Giá', stock: 'Còn hàng',
    dashboard: 'Bảng điều khiển', orders: 'Đơn hàng', customers: 'Khách hàng',
    settings: 'Cài đặt', products_admin: 'Sản phẩm', upload: 'Tải lên',
    save: 'Lưu', cancel: 'Hủy', delete: 'Xóa', edit: 'Sửa',
    add_product: 'Thêm sản phẩm', order_id: 'Đơn #', status: 'Trạng thái',
    revenue: 'Doanh thu', welcome: 'Chào mừng,', theme_toggle: 'Đổi giao diện',
    language: 'Ngôn ngữ', filter: 'Lọc', all: 'Tất cả', category: 'Danh mục',
    description: 'Mô tả', quantity: 'SL', remove: 'Xóa',
    continue_shopping: 'Tiếp tục mua', place_order: 'Đặt hàng',
    payment_method: 'Phương thức', shipping: 'Vận chuyển',
    address: 'Địa chỉ', phone: 'SĐT', city: 'Thành phố', zip: 'Bưu chính',
    export_pdf: 'Xuất PDF', new: 'Mới', active: 'Hoạt động', inactive: 'Không hoạt động',
    pending: 'Chờ xử lý', completed: 'Hoàn thành', cancelled: 'Đã hủy',
    upload_image: 'Tải ảnh', drag_drop: 'Kéo thả hoặc nhấn để tải',
    notifications: 'Thông báo', mark_read: 'Đánh dấu đã đọc',
    no_notifications: 'Không có thông báo', role: 'Vai trò',
    password: 'Mật khẩu', confirm_password: 'Xác nhận mật khẩu',
    search_placeholder: 'Tìm theo tên, danh mục…',
  }
};

// ── Mock Data ─────────────────────────────────────────────────
const MOCK_PRODUCTS = [
  { id:1, name:'Digital Audiometer DA-500', category:'Audiometry', price:2499, image:'https://picsum.photos/seed/aud1/480/360', description:'Professional-grade digital audiometer for comprehensive hearing assessments.', stock:14, active:true },
  { id:2, name:'Hearing Aid HX Pro Max', category:'Hearing Aids', price:899, image:'https://picsum.photos/seed/aud2/480/360', description:'Advanced behind-the-ear hearing aid with Bluetooth connectivity.', stock:31, active:true },
  { id:3, name:'Otoscope OtoVision 3', category:'Diagnostic', price:349, image:'https://picsum.photos/seed/aud3/480/360', description:'LED fiber-optic otoscope with HD video capture.', stock:8, active:true },
  { id:4, name:'Tympanometer TM-200', category:'Audiometry', price:3199, image:'https://picsum.photos/seed/aud4/480/360', description:'Multi-frequency tympanometer with automated test sequences.', stock:5, active:true },
  { id:5, name:'Ear Cleaning Kit Pro', category:'Accessories', price:49, image:'https://picsum.photos/seed/aud5/480/360', description:'Professional irrigation kit with 3 tip sizes and pressure control.', stock:200, active:true },
  { id:6, name:'Sound Booth SB-Mini', category:'Audiometry', price:7499, image:'https://picsum.photos/seed/aud6/480/360', description:'Portable sound-attenuation booth for in-clinic audiometric testing.', stock:2, active:true },
  { id:7, name:'OAE Screener Swift', category:'Diagnostic', price:1850, image:'https://picsum.photos/seed/aud7/480/360', description:'Automated OAE hearing screening for newborn and pediatric use.', stock:12, active:true },
  { id:8, name:'Earmold Impression Kit', category:'Accessories', price:89, image:'https://picsum.photos/seed/aud8/480/360', description:'Silicone impression material set with mixing tips, 20 pairs.', stock:75, active:true },
  { id:9, name:'ABR System NeuroAud', category:'Diagnostic', price:12500, image:'https://picsum.photos/seed/aud9/480/360', description:'Auditory Brainstem Response system for neurodiagnostic testing.', stock:3, active:true },
];

const MOCK_ORDERS = [
  { id:'ORD-0041', customer:'Maria Lopez', email:'m.lopez@email.com', total:2499, status:'completed', date:'2025-05-18', items:1 },
  { id:'ORD-0042', customer:'James Kim', email:'j.kim@email.com', total:349, status:'pending', date:'2025-05-19', items:2 },
  { id:'ORD-0043', customer:'Sarah Chen', email:'s.chen@email.com', total:7499, status:'completed', date:'2025-05-20', items:1 },
  { id:'ORD-0044', customer:'Ahmed Osei', email:'a.osei@email.com', total:938, status:'cancelled', date:'2025-05-21', items:3 },
  { id:'ORD-0045', customer:'Lin Nguyen', email:'l.nguyen@email.com', total:1850, status:'pending', date:'2025-05-22', items:1 },
  { id:'ORD-0046', customer:'Tom Blake', email:'t.blake@email.com', total:138, status:'completed', date:'2025-05-23', items:4 },
];

const MOCK_CUSTOMERS = [
  { id:1, name:'Maria Lopez', email:'m.lopez@email.com', role:'customer', orders:4, joined:'2024-11-02', active:true },
  { id:2, name:'James Kim', email:'j.kim@email.com', role:'customer', orders:2, joined:'2025-01-15', active:true },
  { id:3, name:'Sarah Chen', email:'s.chen@email.com', role:'customer', orders:7, joined:'2024-08-30', active:true },
  { id:4, name:'Ahmed Osei', email:'a.osei@email.com', role:'customer', orders:1, joined:'2025-03-10', active:false },
  { id:5, name:'Lin Nguyen', email:'l.nguyen@email.com', role:'admin', orders:0, joined:'2024-06-01', active:true },
];

const CATEGORIES = ['All', 'Audiometry', 'Hearing Aids', 'Diagnostic', 'Accessories'];

// ── Icons ─────────────────────────────────────────────────────
const Icon = ({ name, size = 18, cls = '' }) => {
  const icons = {
    home: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>,
    products: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>,
    cart: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>,
    user: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
    sun: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>,
    moon: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>,
    search: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>,
    plus: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>,
    minus: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/></svg>,
    trash: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>,
    edit: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
    x: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
    check: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
    chevron_right: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>,
    chevron_left: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>,
    bell: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>,
    upload: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/><path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"/></svg>,
    download: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="8 17 12 21 16 17"/><line x1="12" y1="12" x2="12" y2="21"/><path d="M20.88 18.09A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.29"/></svg>,
    bar_chart: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/><line x1="2" y1="20" x2="22" y2="20"/></svg>,
    users: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>,
    settings: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93a9 9 0 0 1 1.6 12.94M4.93 19.07a9 9 0 0 1 1.6-12.94M19.07 19.07a9 9 0 0 1-12.94 1.6M4.93 4.93a9 9 0 0 1 12.94 1.6"/></svg>,
    credit_card: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>,
    package: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="16.5" y1="9.4" x2="7.5" y2="4.21"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>,
    globe: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>,
    arrow_up: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>,
    arrow_down: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>,
    filter: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>,
    menu: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/></svg>,
    mail: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>,
    lock: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>,
    star: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth="1"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>,
    activity: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>,
    trending_up: <svg width={size} height={size} className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>,
  };
  return icons[name] || <span>{name}</span>;
};

// ── Toast System ──────────────────────────────────────────────
let toastCounter = 0;
const toastListeners = [];
const addToast = (msg, type = 'info', duration = 3500) => {
  const id = ++toastCounter;
  toastListeners.forEach(fn => fn({ id, msg, type, duration }));
};

const PORTAL54_URL = 'https://portal54.audicalservices.com';

let csrfToken = null;

const apiRequest = async (path, options = {}) => {
  const method = (options.method || 'GET').toUpperCase();
  const headers = { ...(options.headers || {}) };

  if (method !== 'GET' && method !== 'HEAD') {
    if (!csrfToken) {
      const csrfRes = await fetch('/api/csrf', { credentials: 'include' });
      const csrfJson = await csrfRes.json().catch(() => ({}));
      if (!csrfRes.ok || !csrfJson?.success) {
        throw new Error(csrfJson?.error || 'Unable to initialize security token');
      }
      csrfToken = csrfJson.data.token;
    }
    headers['X-CSRF-Token'] = csrfToken;
  }

  const res = await fetch(path, {
    credentials: 'include',
    ...options,
    headers,
  });
  const json = await res.json().catch(() => ({}));

  if (!res.ok || json?.success === false) {
    throw new Error(json?.error || json?.message || 'Request failed');
  }

  if (json?.data?.csrf) csrfToken = json.data.csrf;
  return json;
};

const ToastContainer = () => {
  const [toasts, setToasts] = useState([]);
  useEffect(() => {
    const fn = t => setToasts(prev => [...prev, t]);
    toastListeners.push(fn);
    return () => toastListeners.splice(toastListeners.indexOf(fn), 1);
  }, []);
  const remove = id => setToasts(prev => prev.filter(t => t.id !== id));
  const colors = { success: '#22c55e', error: '#ef4444', info: '#01c7fc', warning: '#f59e0b' };
  return (
    <div className="toast-container">
      {toasts.map(t => (
        <div key={t.id} className="toast" style={{ borderLeft: `3px solid ${colors[t.type] || colors.info}` }}>
          <span style={{ color: colors[t.type] || colors.info, flexShrink: 0 }}>
            {t.type === 'success' ? <Icon name="check" size={16} /> : t.type === 'error' ? <Icon name="x" size={16} /> : <Icon name="activity" size={16} />}
          </span>
          <span style={{ flex: 1, fontSize: 13 }}>{t.msg}</span>
          <button onClick={() => remove(t.id)} className="btn-ghost btn-sm" style={{ padding:'2px', minHeight:'unset' }}>
            <Icon name="x" size={14} />
          </button>
          {setTimeout(() => remove(t.id), t.duration) && null}
        </div>
      ))}
    </div>
  );
};

// ── Navbar ────────────────────────────────────────────────────
const Navbar = () => {
  const { page, setPage, cart, dark, setDark, lang, setLang, user, setUser, t, notifications } = useApp();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const unread = notifications.filter(n => !n.read).length;
  return (
    <nav className="nav">
      <div className="container nav-inner" style={{ position:'relative' }}>
        {/* Logo */}
        <button onClick={() => { setPage('home'); setMobileOpen(false); }} className="nav-logo" style={{ background:'none', border:'none', cursor:'pointer' }}>
          <Icon name="activity" size={22} cls="" /> Audical<span>Services</span>
        </button>

        {/* Desktop links */}
        <div className={`nav-links${mobileOpen ? ' open' : ''}`}>
          {[['home','home'],['products','products'],].map(([k,p]) => (
            <button key={k} onClick={() => { setPage(p); setMobileOpen(false); }}
              className={`nav-link${page===p?' active':''}`}>{t[k]}</button>
          ))}
          {user?.role === 'admin' && (
            <button onClick={() => { setPage('admin'); setMobileOpen(false); }}
              className={`nav-link${page==='admin'?' active':''}`}>{t.admin}</button>
          )}

          {/* Language */}
          <div style={{ position:'relative' }}>
            <select value={lang} onChange={e => setLang(e.target.value)}
              style={{ background:'var(--color-surface)', border:'1px solid var(--color-border)', borderRadius:'var(--radius-md)', padding:'6px 10px', fontSize:13, color:'var(--color-text)', cursor:'pointer' }}>
              <option value="en">🇺🇸 EN</option>
              <option value="es">🇪🇸 ES</option>
              <option value="vi">🇻🇳 VI</option>
            </select>
          </div>

          {/* Theme */}
          <button onClick={() => setDark(!dark)} className="btn btn-ghost btn-sm" title={t.theme_toggle}>
            {dark ? <Icon name="sun" size={16} /> : <Icon name="moon" size={16} />}
          </button>

          {/* Notifications */}
          <div style={{ position:'relative' }}>
            <button onClick={() => setNotifOpen(!notifOpen)} className="btn btn-ghost btn-sm" style={{ position:'relative' }}>
              <Icon name="bell" size={16} />
              {unread > 0 && (
                <span style={{ position:'absolute', top:4, right:4, width:8, height:8, borderRadius:'50%', background:'var(--color-danger)' }} />
              )}
            </button>
            {notifOpen && (
              <div style={{ position:'absolute', right:0, top:'calc(100% + 8px)', width:300, background:'var(--color-bg)', border:'1px solid var(--color-border)', borderRadius:'var(--radius-lg)', boxShadow:'var(--shadow-xl)', zIndex:200, overflow:'hidden' }}>
                <div style={{ padding:'14px 16px', borderBottom:'1px solid var(--color-border)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                  <span style={{ fontFamily:'Poppins', fontWeight:700, fontSize:14 }}>{t.notifications}</span>
                  <span className="badge badge-primary">{unread}</span>
                </div>
                {notifications.slice(0,5).map(n => (
                  <div key={n.id} style={{ padding:'12px 16px', borderBottom:'1px solid var(--color-border)', display:'flex', gap:10, opacity: n.read ? 0.6 : 1 }}>
                    <span style={{ color:'var(--color-primary)', flexShrink:0 }}><Icon name="package" size={16} /></span>
                    <div>
                      <div style={{ fontSize:13, fontWeight:500 }}>{n.msg}</div>
                      <div style={{ fontSize:11, color:'var(--color-muted)', marginTop:2 }}>{n.time}</div>
                    </div>
                  </div>
                ))}
                {notifications.length === 0 && (
                  <div style={{ padding:'24px 16px', textAlign:'center', color:'var(--color-muted)', fontSize:13 }}>{t.no_notifications}</div>
                )}
                <button onClick={() => setNotifOpen(false)} style={{ display:'block', width:'100%', padding:'10px', fontSize:13, color:'var(--color-primary)', fontWeight:600, background:'none', border:'none', cursor:'pointer' }}>{t.mark_read}</button>
              </div>
            )}
          </div>

          {/* Cart */}
          <button onClick={() => setPage('cart')} className="btn btn-outline btn-sm" style={{ position:'relative', gap:6 }}>
            <Icon name="cart" size={16} />
            {cartCount > 0 && (
              <span style={{ background:'var(--color-primary)', color:'#fff', borderRadius:'99px', fontSize:10, fontWeight:700, padding:'1px 6px', minWidth:18, textAlign:'center' }}>{cartCount}</span>
            )}
          </button>

          {/* Auth */}
          {user ? (
            <button onClick={() => { setUser(null); addToast('Logged out', 'info'); }} className="btn btn-ghost btn-sm">
              <Icon name="user" size={16} /> {t.logout}
            </button>
          ) : (
            <button onClick={() => setPage('login')} className="btn btn-primary btn-sm">
              <Icon name="lock" size={14} /> {t.login}
            </button>
          )}
        </div>

        {/* Hamburger */}
        <button className="nav-hamburger" onClick={() => setMobileOpen(!mobileOpen)}>
          <span /><span /><span />
        </button>
      </div>
    </nav>
  );
};

// ── Home Page ─────────────────────────────────────────────────
const HomePage = () => {
  const { t, setPage } = useApp();
  const features = [
    { icon:'package', title:'Professional Equipment', desc:'Sourced directly from leading manufacturers with full warranty.' },
    { icon:'check', title:'Fast Shipping', desc:'Next-day delivery on most items to your clinic or practice.' },
    { icon:'star', title:'Expert Support', desc:'Certified audiologists available for product guidance.' },
    { icon:'credit_card', title:'Flexible Payment', desc:'Accept Stripe and Square with installment options.' },
  ];
  return (
    <main>
      {/* Hero */}
      <section className="hero">
        <div className="container" style={{ textAlign:'center' }}>
          <div className="badge badge-primary" style={{ margin:'0 auto 20px' }}>
            <Icon name="activity" size={12} /> Professional Audiological Supplies
          </div>
          <h1 style={{ maxWidth:700, margin:'0 auto 24px' }}>
            Premium Audiology Equipment & Supplies
          </h1>
          <p style={{ fontSize:'clamp(15px,2vw,18px)', color:'var(--color-muted)', maxWidth:520, margin:'0 auto 36px', lineHeight:1.7 }}>
            Complete solutions for hearing clinics, hospitals, and private practices. Shop our curated catalog of audiometric tools and accessories.
          </p>
          <div style={{ display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap' }}>
            <button onClick={() => setPage('products')} className="btn btn-primary btn-lg">
              <Icon name="products" size={18} /> {t.products}
            </button>
            <button onClick={() => setPage('login')} className="btn btn-outline btn-lg">
              {t.login} <Icon name="chevron_right" size={18} />
            </button>
          </div>
        </div>
      </section>

      {/* Features */}
      <section className="section" style={{ background:'var(--color-surface)' }}>
        <div className="container">
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(220px, 1fr))', gap:24 }}>
            {features.map((f, i) => (
              <div key={i} className="card" style={{ display:'flex', flexDirection:'column', gap:12 }}>
                <div style={{ width:44, height:44, borderRadius:'var(--radius-md)', background:'rgba(1,199,252,0.12)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--color-primary)' }}>
                  <Icon name={f.icon} size={20} />
                </div>
                <h4 style={{ marginBottom:4 }}>{f.title}</h4>
                <p style={{ fontSize:14, color:'var(--color-muted)', lineHeight:1.6 }}>{f.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Featured Products */}
      <section className="section">
        <div className="container">
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:32, flexWrap:'wrap', gap:12 }}>
            <h2>Featured Products</h2>
            <button onClick={() => setPage('products')} className="btn btn-outline btn-sm">
              View All <Icon name="chevron_right" size={14} />
            </button>
          </div>
          <div className="product-grid">
            {MOCK_PRODUCTS.slice(0,3).map(p => <ProductCard key={p.id} product={p} />)}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="section" style={{ background:'linear-gradient(135deg, rgba(1,199,252,0.1), rgba(254,251,65,0.06))' }}>
        <div className="container" style={{ textAlign:'center' }}>
          <h2 style={{ marginBottom:16 }}>Ready to Upgrade Your Practice?</h2>
          <p style={{ color:'var(--color-muted)', marginBottom:32, fontSize:16 }}>
            Create an account for exclusive pricing and expedited ordering.
          </p>
          <button onClick={() => setPage('login')} className="btn btn-accent btn-lg">
            <Icon name="user" size={18} /> Get Started
          </button>
        </div>
      </section>
    </main>
  );
};

// ── Product Card ──────────────────────────────────────────────
const ProductCard = ({ product }) => {
  const { addToCart, t } = useApp();
  return (
    <div className="product-card">
      <img src={product.image} alt={product.name} className="product-card-img" loading="lazy" />
      <div className="product-card-body">
        <span className="badge badge-primary" style={{ marginBottom:8 }}>{product.category}</span>
        <div className="product-card-title">{product.name}</div>
        <p style={{ fontSize:13, color:'var(--color-muted)', marginTop:4, marginBottom:12, lineHeight:1.5 }}>
          {product.description.slice(0, 80)}…
        </p>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:8 }}>
          <div className="product-card-price">${product.price.toLocaleString()}</div>
          <button onClick={() => addToCart(product)} className="btn btn-primary btn-sm">
            <Icon name="plus" size={14} /> {t.addToCart}
          </button>
        </div>
        <div style={{ fontSize:12, color:'var(--color-muted)', marginTop:8 }}>
          <Icon name="check" size={12} cls="" /> {t.stock}: {product.stock}
        </div>
      </div>
    </div>
  );
};

// ── Products Page ─────────────────────────────────────────────
const ProductsPage = () => {
  const { t } = useApp();
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState('All');
  const [page, setPage] = useState(1);
  const PER_PAGE = 6;

  const filtered = useMemo(() => MOCK_PRODUCTS.filter(p =>
    (category === 'All' || p.category === category) &&
    p.name.toLowerCase().includes(query.toLowerCase())
  ), [query, category]);

  const pages = Math.ceil(filtered.length / PER_PAGE);
  const paginated = filtered.slice((page-1)*PER_PAGE, page*PER_PAGE);

  return (
    <main className="section">
      <div className="container">
        <h2 style={{ marginBottom:24 }}>{t.products}</h2>

        {/* Search & Filter */}
        <div style={{ display:'flex', gap:12, marginBottom:24, flexWrap:'wrap', alignItems:'center' }}>
          <div className="search-bar" style={{ flex:1, minWidth:200 }}>
            <Icon name="search" size={16} />
            <input className="form-input" style={{ paddingLeft:40 }}
              placeholder={t.search_placeholder} value={query}
              onChange={e => { setQuery(e.target.value); setPage(1); }} />
          </div>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            {CATEGORIES.map(c => (
              <button key={c} onClick={() => { setCategory(c); setPage(1); }}
                className={`tag${category===c?' active':''}`}>{c}</button>
            ))}
          </div>
        </div>

        {/* Results */}
        <div style={{ marginBottom:12, color:'var(--color-muted)', fontSize:13 }}>
          {filtered.length} product{filtered.length !== 1 ? 's' : ''} found
        </div>

        {paginated.length > 0 ? (
          <div className="product-grid">
            {paginated.map(p => <ProductCard key={p.id} product={p} />)}
          </div>
        ) : (
          <div style={{ textAlign:'center', padding:'60px 16px', color:'var(--color-muted)' }}>
            <Icon name="search" size={40} /><br /><br />No products match your search.
          </div>
        )}

        {/* Pagination */}
        {pages > 1 && (
          <div style={{ display:'flex', justifyContent:'center', marginTop:32 }}>
            <div className="pagination">
              <button className="page-btn" onClick={() => setPage(p=>Math.max(1,p-1))} disabled={page===1}>
                <Icon name="chevron_left" size={14} />
              </button>
              {Array.from({length:pages},(_,i)=>i+1).map(n => (
                <button key={n} className={`page-btn${page===n?' active':''}`} onClick={() => setPage(n)}>{n}</button>
              ))}
              <button className="page-btn" onClick={() => setPage(p=>Math.min(pages,p+1))} disabled={page===pages}>
                <Icon name="chevron_right" size={14} />
              </button>
            </div>
          </div>
        )}
      </div>
    </main>
  );
};

// ── Cart Page ─────────────────────────────────────────────────
const CartPage = () => {
  const { cart, setCart, t, setPage } = useApp();
  const total = cart.reduce((s, i) => s + i.price * i.qty, 0);

  const updateQty = (id, qty) => {
    if (qty < 1) return setCart(c => c.filter(i => i.id !== id));
    setCart(c => c.map(i => i.id === id ? {...i, qty} : i));
  };

  if (cart.length === 0) return (
    <main className="section">
      <div className="container" style={{ textAlign:'center', padding:'80px 16px' }}>
        <Icon name="cart" size={56} cls="" />
        <h3 style={{ margin:'16px 0 8px' }}>{t.empty_cart}</h3>
        <p style={{ color:'var(--color-muted)', marginBottom:28 }}>Add some products to get started</p>
        <button onClick={() => setPage('products')} className="btn btn-primary">
          <Icon name="products" size={16} /> {t.continue_shopping}
        </button>
      </div>
    </main>
  );

  return (
    <main className="section">
      <div className="container">
        <h2 style={{ marginBottom:28 }}>{t.cart}</h2>
        <div style={{ display:'grid', gridTemplateColumns:'1fr min(360px, 100%)', gap:28, alignItems:'start' }}>
          {/* Items */}
          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            {cart.map(item => (
              <div key={item.id} className="card" style={{ display:'flex', gap:16, alignItems:'center', flexWrap:'wrap' }}>
                <img src={item.image} alt={item.name} style={{ width:80, height:60, objectFit:'cover', borderRadius:'var(--radius-md)', flexShrink:0 }} />
                <div style={{ flex:1, minWidth:140 }}>
                  <div style={{ fontFamily:'Poppins', fontWeight:600, fontSize:14, marginBottom:4 }}>{item.name}</div>
                  <div style={{ color:'var(--color-primary)', fontWeight:700, fontFamily:'Poppins' }}>${item.price.toLocaleString()}</div>
                </div>
                <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                  <button onClick={() => updateQty(item.id, item.qty-1)} className="btn btn-outline btn-sm" style={{ padding:'4px 8px', minHeight:'unset' }}><Icon name="minus" size={12} /></button>
                  <span style={{ fontFamily:'Fira Code', fontWeight:600, minWidth:24, textAlign:'center' }}>{item.qty}</span>
                  <button onClick={() => updateQty(item.id, item.qty+1)} className="btn btn-outline btn-sm" style={{ padding:'4px 8px', minHeight:'unset' }}><Icon name="plus" size={12} /></button>
                </div>
                <div style={{ fontFamily:'Poppins', fontWeight:700, minWidth:80, textAlign:'right' }}>
                  ${(item.price * item.qty).toLocaleString()}
                </div>
                <button onClick={() => setCart(c => c.filter(i => i.id !== item.id))} className="btn btn-ghost btn-sm" style={{ color:'var(--color-danger)' }}>
                  <Icon name="trash" size={14} />
                </button>
              </div>
            ))}
          </div>

          {/* Summary */}
          <div className="card" style={{ position:'sticky', top:80 }}>
            <h4 style={{ marginBottom:16 }}>Order Summary</h4>
            {cart.map(i => (
              <div key={i.id} style={{ display:'flex', justifyContent:'space-between', fontSize:13, marginBottom:8, color:'var(--color-muted)' }}>
                <span>{i.name} × {i.qty}</span>
                <span>${(i.price * i.qty).toLocaleString()}</span>
              </div>
            ))}
            <div className="divider" />
            <div style={{ display:'flex', justifyContent:'space-between', fontFamily:'Poppins', fontWeight:700, fontSize:18, marginBottom:24 }}>
              <span>{t.total}</span>
              <span style={{ color:'var(--color-primary)' }}>${total.toLocaleString()}</span>
            </div>
            <button onClick={() => setPage('checkout')} className="btn btn-primary btn-full btn-lg">
              {t.proceed} <Icon name="chevron_right" size={16} />
            </button>
            <button onClick={() => setPage('products')} className="btn btn-ghost btn-full" style={{ marginTop:8, fontSize:13 }}>
              {t.continue_shopping}
            </button>
          </div>
        </div>
      </div>
    </main>
  );
};

// ── Checkout Page ─────────────────────────────────────────────
const CheckoutPage = () => {
  const { cart, setCart, t, user, setPage, addNotification } = useApp();
  const [step, setStep] = useState(1);
  const [method, setMethod] = useState('stripe');
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({ name: user?.name||'', email: user?.email||'', address:'', city:'', zip:'', phone:'' });
  const total = cart.reduce((s, i) => s + i.price * i.qty, 0);

  const field = (k, label, type='text') => (
    <div className="form-group">
      <label className="form-label">{label}</label>
      <input className="form-input" type={type} value={form[k]} onChange={e => setForm({...form,[k]:e.target.value})} />
    </div>
  );

  const placeOrder = async () => {
    setLoading(true);
    await new Promise(r => setTimeout(r, 1800));
    setLoading(false);
    setCart([]);
    addNotification(`Order placed for $${total.toLocaleString()}`);
    addToast('Order placed successfully!', 'success');
    setStep(3);
  };

  if (cart.length === 0 && step !== 3) return (
    <main className="section"><div className="container" style={{ textAlign:'center', padding:60 }}>
      <h3>No items in cart</h3>
      <button onClick={() => setPage('products')} className="btn btn-primary" style={{ marginTop:20 }}>Shop Now</button>
    </div></main>
  );

  return (
    <main className="section">
      <div className="container" style={{ maxWidth:700 }}>
        {/* Steps */}
        <div style={{ display:'flex', gap:0, marginBottom:36 }}>
          {[1,2,3].map((s,i) => (
            <React.Fragment key={s}>
              <div style={{ display:'flex', flexDirection:'column', alignItems:'center', flex:1 }}>
                <div style={{ width:36, height:36, borderRadius:'50%', background: step >= s ? 'var(--color-primary)' : 'var(--color-surface)', border: `2px solid ${step >= s ? 'var(--color-primary)' : 'var(--color-border)'}`, display:'flex', alignItems:'center', justifyContent:'center', color: step >= s ? '#fff' : 'var(--color-muted)', fontFamily:'Poppins', fontWeight:700, fontSize:14 }}>
                  {step > s ? <Icon name="check" size={16} /> : s}
                </div>
                <div style={{ fontSize:11, marginTop:6, fontWeight:600, color: step >= s ? 'var(--color-primary)' : 'var(--color-muted)', textTransform:'uppercase', letterSpacing:'0.06em' }}>
                  {['Shipping','Payment','Confirm'][i]}
                </div>
              </div>
              {i < 2 && <div style={{ flex:2, height:2, background: step > s+0.5 ? 'var(--color-primary)' : 'var(--color-border)', marginTop:17, alignSelf:'flex-start' }} />}
            </React.Fragment>
          ))}
        </div>

        {step === 1 && (
          <div className="card">
            <h3 style={{ marginBottom:20 }}><Icon name="package" size={18} /> {t.shipping}</h3>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
              {field('name', t.name)}
              {field('email', t.email, 'email')}
              {field('phone', t.phone, 'tel')}
              {field('address', t.address)}
              {field('city', t.city)}
              {field('zip', t.zip)}
            </div>
            <button onClick={() => setStep(2)} className="btn btn-primary btn-full btn-lg" style={{ marginTop:24 }}>
              Continue to Payment <Icon name="chevron_right" size={16} />
            </button>
          </div>
        )}

        {step === 2 && (
          <div className="card">
            <h3 style={{ marginBottom:20 }}><Icon name="credit_card" size={18} /> {t.payment_method}</h3>
            <div style={{ display:'flex', gap:12, marginBottom:24 }}>
              {['stripe','square'].map(m => (
                <button key={m} onClick={() => setMethod(m)} style={{ flex:1, padding:'16px', border:`2px solid ${method===m?'var(--color-primary)':'var(--color-border)'}`, borderRadius:'var(--radius-lg)', background: method===m ? 'rgba(1,199,252,0.06)' : 'var(--color-surface)', cursor:'pointer', fontFamily:'Poppins', fontWeight:700, fontSize:15, color: method===m ? 'var(--color-primary)' : 'var(--color-text)', transition:'all 0.2s' }}>
                  {m === 'stripe' ? '💳 Stripe' : '🟦 Square'}
                </button>
              ))}
            </div>
            {/* Mock card inputs */}
            <div style={{ display:'grid', gap:16 }}>
              <div className="form-group">
                <label className="form-label">Card Number</label>
                <input className="form-input" style={{ fontFamily:'Fira Code' }} placeholder="4242 4242 4242 4242" maxLength={19} />
              </div>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
                <div className="form-group">
                  <label className="form-label">Expiry</label>
                  <input className="form-input" style={{ fontFamily:'Fira Code' }} placeholder="MM / YY" />
                </div>
                <div className="form-group">
                  <label className="form-label">CVV</label>
                  <input className="form-input" style={{ fontFamily:'Fira Code' }} placeholder="•••" maxLength={4} />
                </div>
              </div>
            </div>
            <div className="divider" />
            <div style={{ display:'flex', justifyContent:'space-between', fontFamily:'Poppins', fontWeight:700, fontSize:18, marginBottom:20 }}>
              <span>{t.total}</span>
              <span style={{ color:'var(--color-primary)' }}>${total.toLocaleString()}</span>
            </div>
            <div style={{ display:'flex', gap:10 }}>
              <button onClick={() => setStep(1)} className="btn btn-outline" style={{ flex:1 }}>
                <Icon name="chevron_left" size={14} /> Back
              </button>
              <button onClick={placeOrder} disabled={loading} className="btn btn-primary" style={{ flex:2 }}>
                {loading ? <><span className="spinner" /> Processing…</> : <><Icon name="check" size={16} /> {t.place_order}</>}
              </button>
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="card" style={{ textAlign:'center', padding:'48px 32px' }}>
            <div style={{ width:72, height:72, borderRadius:'50%', background:'rgba(34,197,94,0.15)', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 20px', color:'var(--color-success)' }}>
              <Icon name="check" size={36} />
            </div>
            <h2 style={{ marginBottom:8 }}>Order Confirmed!</h2>
            <p style={{ color:'var(--color-muted)', marginBottom:32 }}>Thank you for your order. A confirmation email has been sent.</p>
            <div style={{ display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap' }}>
              <button onClick={() => setPage('products')} className="btn btn-primary">
                <Icon name="products" size={16} /> Continue Shopping
              </button>
              <button onClick={() => setPage('home')} className="btn btn-outline">
                <Icon name="home" size={16} /> Home
              </button>
            </div>
          </div>
        )}
      </div>
    </main>
  );
};

// ── OTP Login ─────────────────────────────────────────────────
const LoginPage = () => {
  const { setUser, setPage, t } = useApp();
  const [stage, setStage] = useState('email');
  const [email, setEmail] = useState('');
  const [otp, setOtp] = useState(['','','','','','']);
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const inputRefs = useRef([]);

  const sendOtp = async (e) => {
    e.preventDefault();
    if (!email) return;
    setLoading(true);
    try {
      await apiRequest('/api/auth/otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      setStage('otp');
      setCountdown(60);
      addToast(t.otp_sent, 'success');
    } catch (err) {
      addToast(err.message || 'Unable to send OTP', 'error');
    } finally {
      setLoading(false);
    }
  };

  const resendOtp = async () => {
    if (!email || loading || countdown > 0) return;
    setLoading(true);
    try {
      await apiRequest('/api/auth/otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      setOtp(['','','','','','']);
      setCountdown(60);
      addToast('New OTP sent!', 'info');
    } catch (err) {
      addToast(err.message || 'Unable to resend OTP', 'error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (countdown > 0) {
      const t = setTimeout(() => setCountdown(c => c-1), 1000);
      return () => clearTimeout(t);
    }
  }, [countdown]);

  const handleOtpKey = (i, val) => {
    if (!/^\d?$/.test(val)) return;
    const next = [...otp];
    next[i] = val;
    setOtp(next);
    if (val && i < 5) inputRefs.current[i+1]?.focus();
  };

  const handleOtpPaste = (e) => {
    const text = e.clipboardData.getData('text').replace(/\D/g, '').slice(0,6);
    if (text.length === 6) {
      setOtp(text.split(''));
      inputRefs.current[5]?.focus();
    }
  };

  const verifyOtp = async (e) => {
    e.preventDefault();
    const code = otp.join('');
    if (code.length < 6) return;
    setLoading(true);
    try {
      const json = await apiRequest('/api/auth/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, otp: code }),
      });
      const verifiedUser = json.data.user;
      setUser(verifiedUser);
      addToast(`Welcome, ${verifiedUser.name}!`, 'success');
      if (verifiedUser.role === 'admin') {
        window.location.assign(json.data.sso_url || PORTAL54_URL);
        return;
      }
      setPage('home');
    } catch (err) {
      addToast(err.message || 'Unable to verify OTP', 'error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <main style={{ minHeight:'80vh', display:'flex', alignItems:'center', justifyContent:'center', padding:16, background:'var(--color-bg)' }}>
      <div style={{ width:'100%', maxWidth:420 }}>
        <div className="card" style={{ padding:'clamp(24px,5vw,44px)' }}>
          <div style={{ textAlign:'center', marginBottom:28 }}>
            <div style={{ width:52, height:52, borderRadius:'var(--radius-lg)', background:'rgba(1,199,252,0.12)', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 14px', color:'var(--color-primary)' }}>
              <Icon name="lock" size={24} />
            </div>
            <h3>{stage === 'email' ? t.login : 'Verify OTP'}</h3>
            <p style={{ fontSize:13, color:'var(--color-muted)', marginTop:6 }}>
              {stage === 'email' ? 'Enter your email to receive a one-time code' : `Code sent to ${email}`}
            </p>
          </div>

          {stage === 'email' ? (
            <form onSubmit={sendOtp}>
              <div className="form-group" style={{ marginBottom:20 }}>
                <label className="form-label"><Icon name="mail" size={12} /> {t.email}</label>
                <input className="form-input" type="email" value={email}
                  onChange={e => setEmail(e.target.value)}
                  placeholder="you@example.com" required />
              </div>
              <button type="submit" disabled={loading} className="btn btn-primary btn-full btn-lg">
                {loading ? <><span className="spinner" /> Sending…</> : <><Icon name="mail" size={16} /> Send OTP</>}
              </button>
            </form>
          ) : (
            <form onSubmit={verifyOtp}>
              <div className="otp-inputs" style={{ marginBottom:24 }} onPaste={handleOtpPaste}>
                {otp.map((d,i) => (
                  <input key={i} ref={el => inputRefs.current[i] = el}
                    className={`otp-input${d?' filled':''}`}
                    type="text" inputMode="numeric" maxLength={1}
                    value={d} onChange={e => handleOtpKey(i, e.target.value)}
                    onKeyDown={e => { if (e.key === 'Backspace' && !d && i > 0) inputRefs.current[i-1]?.focus(); }} />
                ))}
              </div>
              <button type="submit" disabled={loading || otp.join('').length < 6} className="btn btn-primary btn-full btn-lg">
                {loading ? <><span className="spinner" /> Verifying…</> : <><Icon name="check" size={16} /> {t.verify}</>}
              </button>
              <div style={{ textAlign:'center', marginTop:16 }}>
                {countdown > 0 ? (
                  <span style={{ fontSize:13, color:'var(--color-muted)' }}>Resend in {countdown}s</span>
                ) : (
                  <button type="button" onClick={resendOtp} disabled={loading} className="btn btn-ghost btn-sm">
                    {t.resend} OTP
                  </button>
                )}
              </div>
              <button type="button" onClick={() => setStage('email')} className="btn btn-ghost btn-full" style={{ marginTop:8, fontSize:13 }}>
                <Icon name="chevron_left" size={14} /> Change email
              </button>
            </form>
          )}
        </div>
      </div>
    </main>
  );
};

// ── Admin Layout ──────────────────────────────────────────────
const AdminLayout = ({ children, activeTab, setActiveTab }) => {
  const { t, user } = useApp();
  const nav = [
    { key:'dashboard', icon:'bar_chart', label: t.dashboard },
    { key:'products',  icon:'package',   label: t.products_admin },
    { key:'orders',    icon:'trending_up', label: t.orders },
    { key:'customers', icon:'users',      label: t.customers },
    { key:'upload',    icon:'upload',     label: t.upload },
    { key:'settings',  icon:'settings',   label: t.settings },
  ];
  return (
    <div className="admin-layout">
      <aside className="admin-sidebar">
        <div style={{ marginBottom:24, padding:'0 8px' }}>
          <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.1em', textTransform:'uppercase', color:'var(--color-muted)', marginBottom:8 }}>
            {t.welcome} {user?.name}
          </div>
          <div className="badge badge-primary"><Icon name="activity" size={10} /> Admin</div>
        </div>
        {nav.map(item => (
          <button key={item.key} onClick={() => setActiveTab(item.key)}
            style={{ display:'flex', alignItems:'center', gap:10, width:'100%', padding:'10px 12px', borderRadius:'var(--radius-md)', border:'none', cursor:'pointer', background: activeTab===item.key ? 'rgba(1,199,252,0.1)' : 'transparent', color: activeTab===item.key ? 'var(--color-primary)' : 'var(--color-muted)', fontFamily:'Poppins', fontWeight: activeTab===item.key ? 600 : 500, fontSize:14, transition:'all 0.2s', textAlign:'left', marginBottom:2 }}>
            <Icon name={item.icon} size={16} /> {item.label}
          </button>
        ))}
      </aside>
      <main className="admin-main">{children}</main>
    </div>
  );
};

// ── Admin Dashboard ───────────────────────────────────────────
const AdminDashboard = () => {
  const stats = [
    { label:'Revenue', value:'$48,230', change:'+12.4%', up:true, icon:'trending_up' },
    { label:'Orders', value:'184', change:'+8.1%', up:true, icon:'package' },
    { label:'Products', value:MOCK_PRODUCTS.length, change:'+2', up:true, icon:'products' },
    { label:'Customers', value:MOCK_CUSTOMERS.length, change:'+5.3%', up:true, icon:'users' },
  ];
  return (
    <div>
      <h2 style={{ marginBottom:28 }}>Dashboard</h2>
      {/* Stats */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(180px,1fr))', gap:16, marginBottom:32 }}>
        {stats.map((s,i) => (
          <div key={i} className="stat-card">
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
              <span className="stat-label">{s.label}</span>
              <div style={{ width:36, height:36, borderRadius:'var(--radius-md)', background:'rgba(1,199,252,0.1)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--color-primary)' }}>
                <Icon name={s.icon} size={16} />
              </div>
            </div>
            <div className="stat-value">{s.value}</div>
            <div className={`stat-change ${s.up?'up':'down'}`}>
              {s.up ? <Icon name="arrow_up" size={12} /> : <Icon name="arrow_down" size={12} />} {s.change}
            </div>
          </div>
        ))}
      </div>

      {/* Recent Orders */}
      <h3 style={{ marginBottom:16 }}>Recent Orders</h3>
      <div className="table-wrap">
        <table>
          <thead><tr>
            <th>Order</th><th>Customer</th><th>Total</th><th>Status</th><th>Date</th>
          </tr></thead>
          <tbody>
            {MOCK_ORDERS.slice(0,5).map(o => (
              <tr key={o.id}>
                <td data-label="Order" style={{ fontFamily:'Fira Code', fontSize:13 }}>{o.id}</td>
                <td data-label="Customer">{o.customer}</td>
                <td data-label="Total" style={{ fontFamily:'Poppins', fontWeight:700, color:'var(--color-primary)' }}>${o.total.toLocaleString()}</td>
                <td data-label="Status">
                  <span className={`badge badge-${o.status==='completed'?'success':o.status==='cancelled'?'danger':'primary'}`}>{o.status}</span>
                </td>
                <td data-label="Date" style={{ fontSize:13, color:'var(--color-muted)' }}>{o.date}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ── Admin Products ────────────────────────────────────────────
const AdminProducts = () => {
  const { t } = useApp();
  const [products, setProducts] = useState(MOCK_PRODUCTS);
  const [modal, setModal] = useState(null);
  const [form, setForm] = useState({});

  const openEdit = (p) => { setForm(p ? {...p} : { name:'', category:'Audiometry', price:'', description:'', stock:'', active:true }); setModal(p ? 'edit' : 'add'); };

  const save = () => {
    if (modal === 'edit') setProducts(ps => ps.map(p => p.id === form.id ? form : p));
    else setProducts(ps => [...ps, { ...form, id: Date.now(), image: `https://picsum.photos/seed/${Date.now()}/480/360`, price: Number(form.price), stock: Number(form.stock) }]);
    setModal(null);
    addToast('Product saved', 'success');
  };

  const del = (id) => { setProducts(ps => ps.filter(p => p.id !== id)); addToast('Product deleted', 'error'); };

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:24, flexWrap:'wrap', gap:12 }}>
        <h2>{t.products_admin}</h2>
        <button onClick={() => openEdit(null)} className="btn btn-primary btn-sm">
          <Icon name="plus" size={14} /> {t.add_product}
        </button>
      </div>
      <div className="table-wrap">
        <table>
          <thead><tr><th>Image</th><th>Name</th><th>Category</th><th>Price</th><th>Stock</th><th>Status</th><th>Actions</th></tr></thead>
          <tbody>
            {products.map(p => (
              <tr key={p.id}>
                <td data-label="Image"><img src={p.image} alt={p.name} style={{ width:48, height:36, objectFit:'cover', borderRadius:'var(--radius-sm)' }} /></td>
                <td data-label="Name" style={{ fontWeight:600, fontSize:13 }}>{p.name}</td>
                <td data-label="Category"><span className="badge badge-primary">{p.category}</span></td>
                <td data-label="Price" style={{ fontFamily:'Poppins', fontWeight:700, color:'var(--color-primary)' }}>${p.price.toLocaleString()}</td>
                <td data-label="Stock" style={{ fontFamily:'Fira Code' }}>{p.stock}</td>
                <td data-label="Status"><span className={`badge badge-${p.active?'success':'danger'}`}>{p.active?'Active':'Inactive'}</span></td>
                <td data-label="Actions">
                  <div style={{ display:'flex', gap:6 }}>
                    <button onClick={() => openEdit(p)} className="btn btn-outline btn-sm"><Icon name="edit" size={12} /></button>
                    <button onClick={() => del(p.id)} className="btn btn-danger btn-sm"><Icon name="trash" size={12} /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {modal && (
        <div className="modal-overlay" onClick={e => e.target === e.currentTarget && setModal(null)}>
          <div className="modal">
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20 }}>
              <h3>{modal === 'edit' ? t.edit : t.add_product}</h3>
              <button onClick={() => setModal(null)} className="btn btn-ghost btn-sm"><Icon name="x" size={16} /></button>
            </div>
            <div style={{ display:'grid', gap:14 }}>
              <div className="form-group"><label className="form-label">{t.name}</label><input className="form-input" value={form.name||''} onChange={e=>setForm({...form,name:e.target.value})} /></div>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
                <div className="form-group"><label className="form-label">{t.price}</label><input className="form-input" type="number" value={form.price||''} onChange={e=>setForm({...form,price:e.target.value})} /></div>
                <div className="form-group"><label className="form-label">Stock</label><input className="form-input" type="number" value={form.stock||''} onChange={e=>setForm({...form,stock:e.target.value})} /></div>
              </div>
              <div className="form-group"><label className="form-label">{t.category}</label>
                <select className="form-select" value={form.category||'Audiometry'} onChange={e=>setForm({...form,category:e.target.value})}>
                  {CATEGORIES.slice(1).map(c => <option key={c}>{c}</option>)}
                </select>
              </div>
              <div className="form-group"><label className="form-label">{t.description}</label><textarea className="form-textarea" value={form.description||''} onChange={e=>setForm({...form,description:e.target.value})} /></div>
              <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                <input type="checkbox" id="active" checked={form.active||false} onChange={e=>setForm({...form,active:e.target.checked})} style={{ width:18, height:18, accentColor:'var(--color-primary)' }} />
                <label htmlFor="active" style={{ fontSize:14, fontWeight:500 }}>Active</label>
              </div>
            </div>
            <div style={{ display:'flex', gap:10, marginTop:24 }}>
              <button onClick={() => setModal(null)} className="btn btn-outline" style={{ flex:1 }}>{t.cancel}</button>
              <button onClick={save} className="btn btn-primary" style={{ flex:1 }}>{t.save}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ── Admin Orders ──────────────────────────────────────────────
const AdminOrders = () => {
  const { t } = useApp();
  const [orders, setOrders] = useState(MOCK_ORDERS);
  const [filter, setFilter] = useState('all');

  const filtered = filter === 'all' ? orders : orders.filter(o => o.status === filter);
  const changeStatus = (id, status) => {
    setOrders(os => os.map(o => o.id === id ? {...o, status} : o));
    addToast(`Status updated to ${status}`, 'success');
  };

  return (
    <div>
      <h2 style={{ marginBottom:20 }}>{t.orders}</h2>
      <div style={{ display:'flex', gap:8, marginBottom:20, flexWrap:'wrap' }}>
        {['all','pending','completed','cancelled'].map(f => (
          <button key={f} onClick={() => setFilter(f)} className={`tag${filter===f?' active':''}`}>{f}</button>
        ))}
      </div>
      <div className="table-wrap">
        <table>
          <thead><tr><th>Order</th><th>Customer</th><th>Items</th><th>Total</th><th>Status</th><th>Date</th><th>Action</th></tr></thead>
          <tbody>
            {filtered.map(o => (
              <tr key={o.id}>
                <td data-label="Order" style={{ fontFamily:'Fira Code', fontSize:13 }}>{o.id}</td>
                <td data-label="Customer">
                  <div style={{ fontWeight:600, fontSize:13 }}>{o.customer}</div>
                  <div style={{ fontSize:12, color:'var(--color-muted)' }}>{o.email}</div>
                </td>
                <td data-label="Items" style={{ fontFamily:'Fira Code' }}>{o.items}</td>
                <td data-label="Total" style={{ fontFamily:'Poppins', fontWeight:700, color:'var(--color-primary)' }}>${o.total.toLocaleString()}</td>
                <td data-label="Status">
                  <span className={`badge badge-${o.status==='completed'?'success':o.status==='cancelled'?'danger':'primary'}`}>{o.status}</span>
                </td>
                <td data-label="Date" style={{ fontSize:13, color:'var(--color-muted)' }}>{o.date}</td>
                <td data-label="Action">
                  <select value={o.status} onChange={e=>changeStatus(o.id,e.target.value)} style={{ background:'var(--color-surface)', border:'1px solid var(--color-border)', borderRadius:'var(--radius-sm)', padding:'4px 8px', fontSize:12, color:'var(--color-text)', cursor:'pointer' }}>
                    <option value="pending">Pending</option>
                    <option value="completed">Completed</option>
                    <option value="cancelled">Cancelled</option>
                  </select>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ── Admin Customers ───────────────────────────────────────────
const AdminCustomers = () => {
  const { t } = useApp();
  return (
    <div>
      <h2 style={{ marginBottom:20 }}>{t.customers}</h2>
      <div className="table-wrap">
        <table>
          <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Orders</th><th>Joined</th><th>Status</th></tr></thead>
          <tbody>
            {MOCK_CUSTOMERS.map(c => (
              <tr key={c.id}>
                <td data-label="Name" style={{ fontWeight:600 }}>{c.name}</td>
                <td data-label="Email" style={{ fontSize:13, color:'var(--color-muted)' }}>{c.email}</td>
                <td data-label="Role"><span className={`badge ${c.role==='admin'?'badge-accent':'badge-primary'}`}>{c.role}</span></td>
                <td data-label="Orders" style={{ fontFamily:'Fira Code' }}>{c.orders}</td>
                <td data-label="Joined" style={{ fontSize:13, color:'var(--color-muted)' }}>{c.joined}</td>
                <td data-label="Status"><span className={`badge badge-${c.active?'success':'danger'}`}>{c.active?'Active':'Inactive'}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ── Admin Upload ──────────────────────────────────────────────
const AdminUpload = () => {
  const { t } = useApp();
  const [dragging, setDragging] = useState(false);
  const [files, setFiles] = useState([]);
  const inputRef = useRef();

  const handleDrop = (e) => {
    e.preventDefault();
    setDragging(false);
    const dropped = [...e.dataTransfer.files].filter(f => f.type.startsWith('image/'));
    setFiles(prev => [...prev, ...dropped.map(f => ({ name:f.name, size:f.size, url:URL.createObjectURL(f) }))]);
    addToast(`${dropped.length} file(s) added`, 'success');
  };

  const handleInput = (e) => {
    const picked = [...e.target.files].filter(f => f.type.startsWith('image/'));
    setFiles(prev => [...prev, ...picked.map(f => ({ name:f.name, size:f.size, url:URL.createObjectURL(f) }))]);
    addToast(`${picked.length} file(s) added`, 'success');
  };

  return (
    <div>
      <h2 style={{ marginBottom:24 }}>{t.upload}</h2>
      <div className={`file-drop${dragging?' dragging':''}`}
        onDragOver={e=>{e.preventDefault();setDragging(true);}}
        onDragLeave={()=>setDragging(false)}
        onDrop={handleDrop}
        onClick={()=>inputRef.current?.click()}>
        <input ref={inputRef} type="file" multiple accept="image/*" style={{ display:'none' }} onChange={handleInput} />
        <Icon name="upload" size={36} cls="" />
        <p style={{ marginTop:12, fontWeight:600 }}>{t.drag_drop}</p>
        <p style={{ fontSize:13, color:'var(--color-muted)', marginTop:4 }}>PNG, JPG, WEBP up to 10MB</p>
        <button className="btn btn-primary btn-sm" style={{ marginTop:16, pointerEvents:'none' }}>Browse Files</button>
      </div>

      {files.length > 0 && (
        <div style={{ marginTop:28 }}>
          <h4 style={{ marginBottom:16 }}>Uploaded ({files.length})</h4>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(140px, 1fr))', gap:16 }}>
            {files.map((f,i) => (
              <div key={i} className="card" style={{ padding:8, textAlign:'center' }}>
                <img src={f.url} alt={f.name} style={{ width:'100%', aspectRatio:'4/3', objectFit:'cover', borderRadius:'var(--radius-sm)', marginBottom:8 }} />
                <div style={{ fontSize:11, color:'var(--color-muted)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{f.name}</div>
                <div style={{ fontSize:10, color:'var(--color-muted)' }}>{(f.size/1024).toFixed(1)}KB</div>
                <button onClick={() => setFiles(fs => fs.filter((_,j)=>j!==i))} className="btn btn-ghost btn-sm" style={{ marginTop:6, color:'var(--color-danger)', padding:'2px', minHeight:'unset' }}>
                  <Icon name="trash" size={12} />
                </button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

// ── Admin Settings ────────────────────────────────────────────
const AdminSettings = () => {
  const { dark, setDark, lang, setLang, t } = useApp();
  const [saved, setSaved] = useState(false);
  const save = () => { setSaved(true); addToast('Settings saved', 'success'); setTimeout(() => setSaved(false), 2000); };
  return (
    <div>
      <h2 style={{ marginBottom:24 }}>{t.settings}</h2>
      <div style={{ maxWidth:480, display:'flex', flexDirection:'column', gap:20 }}>
        <div className="card">
          <h4 style={{ marginBottom:16 }}>Appearance</h4>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
            <div>
              <div style={{ fontWeight:600, fontSize:14 }}>Dark Mode</div>
              <div style={{ fontSize:12, color:'var(--color-muted)', marginTop:2 }}>Toggle dark/light theme</div>
            </div>
            <button onClick={() => setDark(!dark)} style={{ width:52, height:28, borderRadius:99, background: dark ? 'var(--color-primary)' : 'var(--color-border)', border:'none', cursor:'pointer', transition:'all 0.3s', position:'relative' }}>
              <span style={{ position:'absolute', top:4, left: dark ? 'calc(100% - 22px)' : 4, width:20, height:20, borderRadius:'50%', background:'#fff', boxShadow:'0 1px 4px rgba(0,0,0,0.2)', transition:'left 0.3s' }} />
            </button>
          </div>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <div>
              <div style={{ fontWeight:600, fontSize:14 }}>Language</div>
              <div style={{ fontSize:12, color:'var(--color-muted)', marginTop:2 }}>Interface language</div>
            </div>
            <select value={lang} onChange={e => setLang(e.target.value)} style={{ background:'var(--color-surface)', border:'1px solid var(--color-border)', borderRadius:'var(--radius-md)', padding:'6px 12px', fontSize:13, color:'var(--color-text)' }}>
              <option value="en">English</option>
              <option value="es">Español</option>
              <option value="vi">Tiếng Việt</option>
            </select>
          </div>
        </div>

        <div className="card">
          <h4 style={{ marginBottom:16 }}>Store Config</h4>
          <div style={{ display:'grid', gap:14 }}>
            <div className="form-group"><label className="form-label">Store Name</label><input className="form-input" defaultValue="Audical Services" /></div>
            <div className="form-group"><label className="form-label">Support Email</label><input className="form-input" type="email" defaultValue="support@audical.com" /></div>
            <div className="form-group"><label className="form-label">Currency</label>
              <select className="form-select" defaultValue="USD"><option>USD</option><option>EUR</option><option>GBP</option></select>
            </div>
          </div>
        </div>

        <div className="card">
          <h4 style={{ marginBottom:16 }}>Payment Config</h4>
          <div style={{ display:'grid', gap:14 }}>
            <div className="form-group"><label className="form-label">Stripe Publishable Key</label><input className="form-input" type="password" defaultValue="pk_test_demo" /></div>
            <div className="form-group"><label className="form-label">Square App ID</label><input className="form-input" type="password" defaultValue="sq0idp_demo" /></div>
          </div>
        </div>

        <button onClick={save} className="btn btn-primary">
          {saved ? <><Icon name="check" size={16} /> Saved!</> : <>{t.save} Settings</>}
        </button>
      </div>
    </div>
  );
};

// ── Admin Page ────────────────────────────────────────────────
const AdminPage = () => {
  const { user, setPage } = useApp();
  const [tab, setTab] = useState('dashboard');
  if (!user || user.role !== 'admin') return (
    <main className="section"><div className="container" style={{ textAlign:'center', padding:60 }}>
      <Icon name="lock" size={48} /><h3 style={{ margin:'16px 0 8px' }}>Admin Access Required</h3>
      <p style={{ color:'var(--color-muted)', marginBottom:20 }}>Please log in with admin credentials.</p>
      <button onClick={() => setPage('login')} className="btn btn-primary">Login</button>
    </div></main>
  );
  const tabs = { dashboard: <AdminDashboard />, products: <AdminProducts />, orders: <AdminOrders />, customers: <AdminCustomers />, upload: <AdminUpload />, settings: <AdminSettings /> };
  return <AdminLayout activeTab={tab} setActiveTab={setTab}>{tabs[tab] || <AdminDashboard />}</AdminLayout>;
};

// ── App Root ──────────────────────────────────────────────────
const App = () => {
  const [page, setPage] = useState('home');
  const [cart, setCart] = useState([]);
  const [dark, setDark] = useState(false);
  const [lang, setLang] = useState('en');
  const [user, setUser] = useState(null);
  const [notifications, setNotifications] = useState([
    { id:1, msg:'New order ORD-0045 received', time:'2 min ago', read:false },
    { id:2, msg:'Low stock: OAE Screener (2 left)', time:'1 hr ago', read:false },
    { id:3, msg:'Payment confirmed for ORD-0043', time:'3 hrs ago', read:true },
  ]);

  const t = TRANSLATIONS[lang] || TRANSLATIONS.en;

  const addToCart = useCallback((product) => {
    setCart(prev => {
      const existing = prev.find(i => i.id === product.id);
      if (existing) {
        addToast(`${product.name} qty updated`, 'success');
        return prev.map(i => i.id === product.id ? {...i, qty: i.qty+1} : i);
      }
      addToast(`${product.name} added to cart`, 'success');
      return [...prev, { ...product, qty: 1 }];
    });
  }, []);

  const addNotification = useCallback((msg) => {
    setNotifications(prev => [{ id: Date.now(), msg, time:'just now', read:false }, ...prev]);
  }, []);

  // Dark mode class on HTML
  useEffect(() => {
    document.documentElement.classList.toggle('dark', dark);
  }, [dark]);

  const PAGES = { home: <HomePage />, products: <ProductsPage />, cart: <CartPage />, login: <LoginPage />, checkout: <CheckoutPage />, admin: <AdminPage /> };

  return (
    <AppContext.Provider value={{ page, setPage, cart, setCart, addToCart, dark, setDark, lang, setLang, user, setUser, t, notifications, addNotification }}>
      <div style={{ minHeight:'100vh', background:'var(--color-bg)', color:'var(--color-text)' }}>
        <Navbar />
        {PAGES[page] || <HomePage />}
        <ToastContainer />

        {/* Footer */}
        <footer style={{ borderTop:'1px solid var(--color-border)', padding:'32px 0', marginTop:'auto' }}>
          <div className="container" style={{ display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:16 }}>
            <div style={{ fontFamily:'Poppins', fontWeight:700, fontSize:16 }}>Audical<span style={{ color:'var(--color-primary)' }}>Services</span></div>
            <div style={{ fontSize:13, color:'var(--color-muted)' }}>© 2025 Audical Services. All rights reserved.</div>
            <div style={{ display:'flex', gap:12 }}>
              {['Privacy','Terms','Support'].map(l => (
                <a key={l} href="#" style={{ fontSize:13, color:'var(--color-muted)' }}>{l}</a>
              ))}
            </div>
          </div>
        </footer>
      </div>
    </AppContext.Provider>
  );
};

// Mount
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
