"use client";

import React, { useCallback, useMemo, useState, useEffect, createContext, useContext } from "react";
import {
  ShieldCheck, AlertTriangle, LayoutDashboard, ShoppingCart,
  Users, Settings, LogOut, Package, Search, Plus, Truck,
  TrendingUp, CheckCircle, Clock, FileText, ChevronRight,
  Sparkles, Coffee, MapPin, Apple, BookOpen, UserCheck, Check, Info, Trash2, Heart, Languages, Eye, AlertOctagon,
  Coins, BarChart3, PieChart, Globe, Building, RefreshCw, ArrowRight, Send, MessageSquare,
  PlusCircle, Calendar, DollarSign, Sliders, X, ExternalLink, FileSpreadsheet, Layers, Award, ShieldAlert,
  Map, HelpCircle, Sparkle, Image as ImageIcon, Shield
} from 'lucide-react';


export interface User {
  id: string;
  name: string;
  email: string;
  role: 'admin' | 'supplier' | 'buyer' | 'regulator';
  zone?: string;
}

export interface Supplier {
  id: string;
  userId: string;
  companyName: string;
  whatsapp: string;
  verificationStatus: 'approved' | 'pending' | 'rejected';
  zone: string;
  minimumOrderValue: number;
}

export interface Buyer {
  id: string;
  userId: string;
  businessName: string;
  businessType: 'school_canteen' | 'catering' | 'restaurant';
  zone: string;
  paymentPreference: 'bank_transfer' | 'cash_on_delivery' | 'term_30';
  preferredWindow: '06:00_07:30' | '07:30_09:00' | '09:00_10:30';
}

export interface Product {
  id: string;
  supplierId: string;
  supplierName?: string;
  name: string;
  nameEn?: string;
  category: string;
  categoryEn?: string;
  price: number;
  moq: number;
  stock: number;
  sugar: number; // grams per 100g
  sodium: number; // mg per 100g
  fat: number; // grams per 100g
  isBannedType: boolean;
  bannedCategory?: string;
  bannedCategoryEn?: string;
  complianceStatus: 'allowed' | 'restricted' | 'prohibited';
  complianceNotes?: string;
  complianceNotesEn?: string;
  totalSold: number;
  promoActive?: boolean;
}

export interface ComplianceRule {
  id: string;
  name: string;
  nameEn: string;
  code: string;
  type: 'nutrient' | 'blacklist';
  active: boolean;
  description: string;
  descriptionEn: string;
}

export interface OrderItem {
  productId: string;
  productName: string;
  productNameEn?: string;
  quantity: number;
  price: number;
}

export interface Order {
  id: string;
  orderNumber: string;
  buyerId: string;
  buyerName?: string;
  supplierId: string;
  supplierName?: string;
  supplierWhatsapp?: string;
  items: OrderItem[];
  total: number;
  status: 'pending' | 'out_for_delivery' | 'delivered' | 'cancelled';
  paymentMethod: string;
  deliveryDate: string;
  deliveryWindow: string;
  deliveryZone: string;
  notes?: string;
  date: string;
}

export interface RecurringOrder {
  id: string;
  buyerId: string;
  supplierId: string;
  name: string;
  nameEn?: string;
  itemsJson: { productId: string; quantity: number }[];
  dayOfWeek: string;
  dayOfWeekEn?: string;
  nextRunDate: string;
  active: boolean;
  autoConfirm: boolean;
}

export interface Review {
  id: string;
  supplierId: string;
  author: string;
  rating: number;
  comment: string;
  commentEn?: string;
}

export interface GroundingSource {
  title: string;
  uri: string;
}

export interface Message {
  id: string;
  senderId: string;
  senderName: string;
  recipientId: string;
  text: string;
  timestamp: string;
  sources?: GroundingSource[];
}

export interface Notification {
  id: string;
  userId: string;
  title: string;
  titleEn?: string;
  body: string;
  bodyEn?: string;
  read: boolean;
  type: 'order' | 'compliance' | 'announcement';
}

export interface Delivery {
  id: string;
  orderId: string;
  driverName: string;
  status: 'assigned' | 'in_transit' | 'delivered';
  currentLat?: number;
  currentLng?: number;
}

export interface DeliverySchedule {
  id: string;
  zone: string;
  zoneEn?: string;
  timeWindow: string;
  cutoff: string;
}

export interface AnalyticsData {
  complianceRate: number;
  totalRevenue: number;
  orderCount: number;
  sugarIntakeAverage: number;
  sodiumIntakeAverage: number;
}


const SEED_USERS: User[] = [
  { id: 'usr-admin', name: 'Zulkifli Amin', email: 'zul@canteensupply.co', role: 'admin' },
  { id: 'usr-reg', name: 'Dr. Noraini KKM', email: 'noraini@kkm.gov.my', role: 'regulator' },
  { id: 'usr-canteen1', name: 'Kak Yah Chepa', email: 'chepayah@school.edu.my', role: 'buyer', zone: 'Kota Bharu' },
  { id: 'usr-sup1', name: 'Ahmad Frozen Enterprise', email: 'ahmad@frozenkb.com', role: 'supplier', zone: 'Kota Bharu' },
];

const SEED_BUYERS: Buyer[] = [
  { id: 'buy-1', userId: 'usr-canteen1', businessName: 'Kantin SMK Pengkalan Chepa 1', businessType: 'school_canteen', zone: 'Kota Bharu', paymentPreference: 'term_30', preferredWindow: '06:00_07:30' },
  { id: 'buy-2', userId: 'usr-canteen2', businessName: 'Kantin SK Kubang Kerian 1', businessType: 'school_canteen', zone: 'Kota Bharu', paymentPreference: 'bank_transfer', preferredWindow: '07:30_09:00' },
];

const SEED_SUPPLIERS: Supplier[] = [
  { id: 'sup-1', userId: 'usr-sup1', companyName: 'Warisan Tok Ba Frozen Wholesales', whatsapp: '601112345678', verificationStatus: 'approved', zone: 'Kota Bharu', minimumOrderValue: 100 },
  { id: 'sup-2', userId: 'usr-sup2', companyName: 'Ayam Gunting Pantai Timur Co.', whatsapp: '601998765432', verificationStatus: 'approved', zone: 'Pasir Mas', minimumOrderValue: 150 },
];

const SEED_PRODUCTS: Product[] = [
  { id: 'p-1', supplierId: 'sup-1', name: 'Nugget Ayam Gandum Penuh (Pek Sihat)', nameEn: 'Wholemeal Chicken Nuggets (Healthy Pack)', category: 'Finger Food', price: 16.50, moq: 4, stock: 120, sugar: 0.8, sodium: 310, fat: 4.5, isBannedType: false, complianceStatus: 'allowed', totalSold: 420 },
  { id: 'p-2', supplierId: 'sup-1', name: 'Serbuk Minuman Malt Coklat Kurang Gula (Disahkan KPM)', nameEn: 'Low-Sugar Chocolate Malt Drink Mix (KPM Vetted)', category: 'Drinks', price: 19.00, moq: 2, stock: 95, sugar: 4.2, sodium: 60, fat: 1.2, isBannedType: false, complianceStatus: 'allowed', totalSold: 310 },
  { id: 'p-3', supplierId: 'sup-2', name: 'Dada Ayam Sejuk Beku Gred A Premium', nameEn: 'Premium Grade A Whole Frozen Chicken Breast', category: 'Chicken', price: 13.00, moq: 10, stock: 240, sugar: 0, sodium: 95, fat: 3.0, isBannedType: false, complianceStatus: 'allowed', totalSold: 850 },
  { id: 'p-4', supplierId: 'sup-2', name: 'Sosej Proses Jumbo (Tinggi Kandungan Natrium)', nameEn: 'Jumbo Processed Sausages (High Sodium Base)', category: 'Processed Meat', price: 9.50, moq: 5, stock: 45, sugar: 2.5, sodium: 650, fat: 12.0, isBannedType: false, complianceStatus: 'restricted', totalSold: 190 },
  { id: 'p-5', supplierId: 'sup-1', name: 'Soda Berkarbonat Tenaga Spark (Pek Hadiah Mainan)', nameEn: 'Carbonated Energy Soda Spark (Toy Bundle Extra)', category: 'Drinks', price: 24.00, moq: 2, stock: 15, sugar: 16.0, sodium: 120, fat: 0.1, isBannedType: true, bannedCategory: 'Minuman Bergas & Soda (Carbonated Soft Drinks)', bannedCategoryEn: 'Carbonated Soft Drinks & Sodas', complianceStatus: 'prohibited', totalSold: 12 },
  { id: 'p-6', supplierId: 'sup-2', name: 'Roti Sandwic Gandum Penuh', nameEn: 'Whole Wheat Sandwich Loaf Pack', category: 'Frozen Kuih', price: 4.80, moq: 10, stock: 180, sugar: 1.5, sodium: 220, fat: 0.9, isBannedType: false, complianceStatus: 'allowed', totalSold: 610 }
];

const SEED_COMPLIANCE_RULES: ComplianceRule[] = [
  { id: 'cr-1', name: 'Had Gula Maksimum KPM', nameEn: 'KPM Maximum Sugar Rule', code: 'S_MAX_10G', type: 'nutrient', active: true, description: 'Produk makanan tidak boleh melebihi 10g gula bagi setiap 100g hidangan.', descriptionEn: 'Products must contain no more than 10g of sugar per 100g serving.' },
  { id: 'cr-2', name: 'Had Natrium Maksimum KPM', nameEn: 'KPM Maximum Sodium Rule', code: 'NA_MAX_400MG', type: 'nutrient', active: true, description: 'Produk makanan tidak boleh melebihi 400mg natrium bagi setiap 100g hidangan.', descriptionEn: 'Products must contain no more than 400mg of sodium per 100g serving.' },
  { id: 'cr-3', name: 'Had Lemak Maksimum KPM', nameEn: 'KPM Maximum Fat Rule', code: 'F_MAX_10G', type: 'nutrient', active: true, description: 'Produk makanan tidak boleh melebihi 10g lemak/lipid bagi setiap 100g hidangan.', descriptionEn: 'Products must contain no more than 10g of lipids/fats per 100g serving.' },
  { id: 'cr-4', name: 'Penapis 13 Kategori Dilarang KPM', nameEn: '13 Prohibited KPM Category Filter', code: 'KPM_13_BLACK_LIST', type: 'blacklist', active: true, description: 'Larangan mutlak terhadap mi segera, minuman bergas, minuman berkafein tinggi, dan gula-gula bersama mainan.', descriptionEn: 'Complete ban on instant noodles, sodas, high-caffeine beverages, and sweets containing toys.' }
];

const SEED_ORDERS: Order[] = [
  { id: 'o-1', orderNumber: 'CS-2026-9041', buyerId: 'buy-1', supplierId: 'sup-1', items: [{ productId: 'p-1', productName: 'Nugget Ayam Gandum Penuh (Pek Sihat)', productNameEn: 'Wholemeal Chicken Nuggets (Healthy Pack)', quantity: 10, price: 16.50 }, { productId: 'p-2', productName: 'Serbuk Minuman Malt Coklat Kurang Gula', productNameEn: 'Low-Sugar Chocolate Malt Drink Mix', quantity: 5, price: 19.00 }], total: 260.00, status: 'pending', paymentMethod: 'term_30', deliveryDate: '2026-07-17', deliveryWindow: '06:00_07:30', deliveryZone: 'Kota Bharu', date: '2026-07-16T14:15:00Z' },
  { id: 'o-2', orderNumber: 'CS-2026-9042', buyerId: 'buy-2', supplierId: 'sup-2', items: [{ productId: 'p-3', productName: 'Dada Ayam Sejuk Beku Gred A Premium', productNameEn: 'Premium Grade A Whole Frozen Chicken Breast', quantity: 20, price: 13.00 }], total: 260.00, status: 'out_for_delivery', paymentMethod: 'bank_transfer', deliveryDate: '2026-07-16', deliveryWindow: '07:30_09:00', deliveryZone: 'Kota Bharu', date: '2026-07-15T16:45:00Z' }
];

const SEED_RECURRING: RecurringOrder[] = [
  { id: 'rec-1', buyerId: 'buy-1', supplierId: 'sup-1', name: 'Pek Asas Kantin Mingguan', nameEn: 'Weekly Canteen Essentials Pack', itemsJson: [{ productId: 'p-1', quantity: 12 }, { productId: 'p-6', quantity: 15 }], dayOfWeek: 'Isnin', dayOfWeekEn: 'Monday', nextRunDate: '2026-07-20', active: true, autoConfirm: true }
];

const SEED_SCHEDULES: DeliverySchedule[] = [
  { id: 'ds-1', zone: 'Pusat Bandar Kota Bharu', zoneEn: 'Kota Bharu Central', timeWindow: '06:00 AM - 07:30 AM', cutoff: '09:00 PM' },
  { id: 'ds-2', zone: 'Koridor Pengkalan Chepa', zoneEn: 'Pengkalan Chepa Corridor', timeWindow: '07:30 AM - 09:00 AM', cutoff: '08:00 PM' },
  { id: 'ds-3', zone: 'Hab Kubang Kerian', zoneEn: 'Kubang Kerian Hub', timeWindow: '06:30 AM - 08:00 AM', cutoff: '07:30 PM' }
];

const SEED_DELIVERIES: Delivery[] = [
  { id: 'del-1', orderId: 'o-2', driverName: 'Abang Rosli Chepa', status: 'in_transit' }
];

const SEED_REVIEWS: Review[] = [
  { id: 'rev-1', supplierId: 'sup-1', author: 'Kak Yah Kantin PC', rating: 5, comment: 'Sangat konsisten menghantar ayam nugget wholemeal sebelum pukul 7 pagi. Pihak KPM pun sangat senang bila tengok logo kelulusan KPM.', commentEn: 'Very consistent in delivering wholemeal chicken nuggets before 7 AM. The Ministry of Education officers are happy seeing the compliance logo.' }
];

const SEED_MESSAGES: Message[] = [
  { id: 'm-1', senderId: 'usr-canteen1', senderName: 'Kak Yah Chepa', recipientId: 'usr-sup1', text: 'Salam abang Ahmad, adakah stok Nugget Wholemeal esok pagi mencukupi untuk 10 paket?', timestamp: '2026-07-16T09:30:00Z' },
  { id: 'm-2', senderId: 'usr-sup1', senderName: 'Ahmad Frozen Enterprise', recipientId: 'usr-canteen1', text: 'Waalaikumussalam Kak Yah! Ya betul, stok baru siap dipek. Jangan lupa submit order sebelum jam 2:00 petang ya.', timestamp: '2026-07-16T09:42:00Z' }
];


interface ToastContextType {
  showToast: (title: string, message?: string, type?: 'success' | 'info' | 'error') => void;
}

const ToastContext = createContext<ToastContextType | undefined>(undefined);

export const useToast = () => {
  const context = useContext(ToastContext);
  if (!context) throw new Error("useToast must be used within a ToastProvider");
  return context;
};

export const ToastProvider = ({ children }: { children: React.ReactNode }) => {
  const [toasts, setToasts] = useState<{ id: string; title: string; message?: string; type: 'success' | 'info' | 'error' }[]>([]);

  const showToast = useCallback((title: string, message?: string, type: 'success' | 'info' | 'error' = 'success') => {
    const id = Math.random().toString(36).substring(2);
    setToasts(prev => [...prev, { id, title, message, type }]);
    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== id));
    }, 4500);
  }, []);

  return (
    <ToastContext.Provider value={{ showToast }}>
      {children}
      <div className="fixed bottom-5 right-5 z-50 flex flex-col gap-2 max-w-sm w-full">
        {toasts.map(t => (
          <div
            key={t.id}
            className="modal-pop bg-white border-l-4 rounded-xl p-4 shadow-xl flex gap-3 border-emerald-600 transition-all cursor-pointer hover:translate-x-1"
            style={{
              borderLeftColor: t.type === 'success' ? '#10b981' : t.type === 'error' ? '#f43f5e' : '#f59e0b'
            }}
            onClick={() => setToasts(prev => prev.filter(x => x.id !== t.id))}
          >
            <div className="shrink-0 mt-0.5">
              {t.type === 'success' && <ShieldCheck className="w-5 h-5 text-emerald-600" />}
              {t.type === 'error' && <AlertTriangle className="w-5 h-5 text-rose-500" />}
              {t.type === 'info' && <Info className="w-5 h-5 text-amber-500" />}
            </div>
            <div className="flex-1 min-w-0">
              <span className="font-extrabold text-xs text-slate-900 block">{t.title}</span>
              {t.message && <p className="text-[11px] text-slate-500 mt-0.5 leading-snug">{t.message}</p>}
            </div>
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
};


type Language = 'bm' | 'en';
interface LanguageContextType {
  lang: Language;
  setLang: (lang: Language) => void;
  t: (key: string) => string;
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

const TRANSLATIONS = {
  bm: {
    heroTitle: "Perolehan makanan sejuk beku untuk kantin sekolah",
    heroDesc: "Menghubungkan pembekal sah dengan kantin sekolah di Kota Bharu, Kelantan.",
    dashboard: "Papan Pemuka",
    gtmBlueprint: "Pelan Induk GTM",
    compliantMarket: "Pasaran Patuh KPM",
    orderBatches: "Pesanan Kumpulan",
    deliveryRuns: "Sesi Penghantaran",
    recurringCycles: "Kitaran Automatik",
    accreditedSuppliers: "Pembekal Sah",
    kpmPolicySandbox: "Kotak Pasir KPM",
    chatsCopilot: "Sembang & Copilot",
    nutrientAnalytics: "Analisis Nutrisi",
    adminHub: "Pusat Pentadbir",
    strategyDeck: "Dek Pelabur",
    collapse: "Sembunyikan Menu",
    activeJajahan: "Jajahan Aktif",
    searchPlaceholder: "Cari SKU patuh, pembekal...",
    recentAlerts: "Log Amaran",
    clearAll: "Padam semua",
    noAlerts: "Tiada amaran pematuhan baru.",
    logout: "Log Keluar",
    activeShipments: "Penghantaran Aktif",
    kpmVettedRate: "Kadar Saringan KPM",
    automatedCycles: "Kitaran Automatik",
    accreditedCount: "Pembekal Bertauliah",
    deliveryNodes: "Node Logistik Aktif",
    nextWindow: "Tetingkap Seterusnya",
    orderCutoff: "Had Masa Pesanan",
    recentOrderBatches: "Kumpulan Pesanan Baru-baru Ini",
    viewAllBatches: "Semak Semua Kumpulan",
    estimatedSubtotal: "Anggaran Jumlah Keseluruhan",
    repeatCycle: "Ulang Kitaran",
    allWholesalers: "Semua Pemborong",
    addVettedSku: "Tambah SKU Patuh",
    sugarLabel: "Gula",
    sodiumLabel: "Natrium",
    fatLabel: "Lemak",
    moq: "Kuantiti Minimum Pesanan",
    stock: "Baki Stok",
    bentoBundleTitle: "Seni Bina Pakej Bento Sihat KPM",
    bentoBundleDesc: "Sistem kecerdasan buatan menyusun pakej tersuai dari baki inventori pemborong.",
    auditSandboxTitle: "Audit Kotak Pasir Menu Kantin",
    auditSandboxDesc: "Taip draf menu mingguan anda untuk saringan KPM dan cadangan penggantian berkhasiat.",
    auditingMenu: "Menganalisis Draf Menu...",
    auditResultEmpty: "Log Keputusan Sandbox Kosong",
    auditResultDesc: "Masukkan draf menu di sebelah kiri untuk melihat maklum balas.",
    checkoutButton: "Sahkan & Hantar Invois WhatsApp",
    accSupTitle: "Pemborong Jajahan Terakreditasi",
    accSupDesc: "Disahkan oleh JAKIM dan menepati piawaian nutrisi kebangsaan.",
    minOrderValue: "Min. Pesanan",
    statusBadgeAcc: "Terakreditasi",
    sandboxTitle: "Kotak Pasir Dasar KPM/KKM",
    sandboxDesc: "Hadkan parameter nutrisi secara langsung bagi menapis senarai pasaran pemborong.",
    weeklyContractTitle: "Konfigurasi Perjanjian Automatik",
    weeklyContractDesc: "Hantar barangan runcit automatik mengikut jadual berkala mingguan.",
    investorTitle: "Rangka Kerja Strategik CanteenSupply",
    investorDesc: "Infrastruktur pengedaran makanan berkhasiat institusi pertama di Kelantan.",
    slideTitle: "Slaid Strategik",
    launchDemo: "Lancar Demo",
    seeFeatures: "Lihat Ciri-ciri",
    featuresTitle: "Ciri Utama",
    gcpScale: "Dibina untuk Skala di Google Cloud",
    gcpDesc: "CanteenSupply sedia untuk pengeluaran dan disahkan patuh. Enjin KPM menyaring item terlarang dengan jayanya.",
    footerBranding: "© 2026 CanteenSupply. Built for Google Cloud Startup Program. MI4,Inc  (Nur Amirah Mohd Kamil)"
  },
  en: {
    heroTitle: "Frozen food procurement for school canteens",
    heroDesc: "Connecting verified suppliers with school canteens in Kota Bharu, Kelantan.",
    dashboard: "Dashboard",
    gtmBlueprint: "GTM Blueprint",
    compliantMarket: "Compliant Market",
    orderBatches: "Order Batches",
    deliveryRuns: "Delivery Runs",
    recurringCycles: "Recurring Cycles",
    accreditedSuppliers: "Accredited Suppliers",
    kpmPolicySandbox: "KPM Policy Sandbox",
    chatsCopilot: "Chats & Copilot",
    nutrientAnalytics: "Nutrient Analytics",
    adminHub: "Admin Hub",
    strategyDeck: "Strategy Deck",
    collapse: "Collapse Sidebar",
    activeJajahan: "Active Regional Jajahan",
    searchPlaceholder: "Search compliant SKUs, suppliers...",
    recentAlerts: "Alert Logs",
    clearAll: "Clear all",
    noAlerts: "No recent compliance alerts.",
    logout: "Log Out",
    activeShipments: "Active Shipments",
    kpmVettedRate: "KPM Vetted Rate",
    automatedCycles: "Automatic Cycles",
    accreditedCount: "Accredited Suppliers",
    deliveryNodes: "Active Delivery Nodes",
    nextWindow: "Next Window",
    orderCutoff: "Order Cut-off",
    recentOrderBatches: "Recent Order Batches",
    viewAllBatches: "View All Batches",
    estimatedSubtotal: "Estimated Subtotal",
    repeatCycle: "Repeat Cycle",
    allWholesalers: "All Wholesalers",
    addVettedSku: "Add Vetted SKU",
    sugarLabel: "Sugar",
    sodiumLabel: "Sodium",
    fatLabel: "Fat",
    moq: "Min. Order Qty",
    stock: "Stock Level",
    bentoBundleTitle: "KPM Vetted Healthy Bento Bundle",
    bentoBundleDesc: "The AI system consolidates custom packaging from available wholesaler ingredients.",
    auditSandboxTitle: "Canteen Menu Sandbox Audit",
    auditSandboxDesc: "Type your draft weekly menu to scan for KPM compliance and suggestions.",
    auditingMenu: "Auditing Menu...",
    auditResultEmpty: "Audit Results Sandbox Empty",
    auditResultDesc: "Enter your draft menu list on the left to see instant compliance feedback.",
    checkoutButton: "Confirm & Send WhatsApp Invoices",
    accSupTitle: "Accredited Jajahan Wholesalers",
    accSupDesc: "Vetted for JAKIM Halal and Ministry of Education compliance standards.",
    minOrderValue: "Min. Order",
    statusBadgeAcc: "Accredited",
    sandboxTitle: "KPM/KKM Policy Sandbox",
    sandboxDesc: "Enforce nutritional thresholds directly on the wholesale catalog listing.",
    weeklyContractTitle: "Automated Contract Configuration",
    weeklyContractDesc: "Deliver wholesale provisions on a repeating weekly rhythm automatically.",
    investorTitle: "CanteenSupply Strategic Architecture",
    investorDesc: "First institutional school nutrition supply layer in Kelantan.",
    slideTitle: "Strategic Slide",
    launchDemo: "Launch Demo",
    seeFeatures: "See Features",
    featuresTitle: "Key Features",
    gcpScale: "Built for Scale on Google Cloud",
    gcpDesc: "CanteenSupply is production-ready and validated. The KPM engine successfully blocked prohibited items server-side.",
    footerBranding: "© 2026 CanteenSupply. Built for Google Cloud Startup Program. MI4,Inc  (Nur Amirah Mohd Kamil)"
  }
};


async function fetchWithBackoff(url: string, options: any, maxRetries = 4) {
  let delay = 1000;
  for (let i = 0; i < maxRetries; i++) {
    try {
      const res = await fetch(url, options);
      if (res.ok) return res;
      if (res.status === 429) {
        await new Promise(r => setTimeout(r, delay));
        delay *= 2;
        continue;
      }
      throw new Error("HTTP Error code: " + res.status);
    } catch (err) {
      if (i === maxRetries - 1) throw err;
      await new Promise(r => setTimeout(r, delay));
      delay *= 2;
    }
  }
  throw new Error("Failed after maximum retries");
}

async function callGeminiText(userQuery: string, systemPrompt: string, useSearch = false) {
  const apiKey = ""; 
  const apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=" + apiKey;

  const payload: any = {
    contents: [{ parts: [{ text: userQuery }] }],
    systemInstruction: {
      parts: [{ text: systemPrompt }]
    }
  };

  if (useSearch) {
    payload.tools = [{ "google_search": {} }];
  }

  const response = await fetchWithBackoff(apiUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });

  const result = await response.json();
  const candidate = result.candidates?.[0];

  if (candidate && candidate.content?.parts?.[0]?.text) {
    const text = candidate.content.parts[0].text;
    let sources: GroundingSource[] = [];
    const groundingMetadata = candidate.groundingMetadata;
    if (groundingMetadata && groundingMetadata.groundingAttributions) {
      sources = groundingMetadata.groundingAttributions
        .map((attribution: any) => ({
          uri: attribution.web?.uri,
          title: attribution.web?.title,
        }))
        .filter((source: any) => source.uri && source.title);
    }
    return { text, sources };
  } else {
    throw new Error("Unexpected payload structure from Gemini API");
  }
}

async function callGeminiStructured(userQuery: string, systemPrompt: string, responseSchema: any) {
  const apiKey = "";
  const apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=" + apiKey;

  const payload = {
    contents: [{ parts: [{ text: userQuery }] }],
    systemInstruction: {
      parts: [{ text: systemPrompt }]
    },
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: responseSchema
    }
  };

  const response = await fetchWithBackoff(apiUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });

  const result = await response.json();
  const candidate = result.candidates?.[0];

  if (candidate && candidate.content?.parts?.[0]?.text) {
    return JSON.parse(candidate.content.parts[0].text);
  } else {
    throw new Error("Unexpected response parsing structured JSON");
  }
}

async function callImagenGenerate(prompt: string) {
  const apiKey = "";
  const apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/imagen-4.0-generate-001:predict?key=" + apiKey;

  const payload = {
    instances: [{ prompt: prompt }],
    parameters: {
      sampleCount: 1,
      aspectRatio: "1:1"
    }
  };

  const response = await fetchWithBackoff(apiUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });

  const result = await response.json();
  if (result.predictions && result.predictions.length > 0 && result.predictions[0].bytesBase64Encoded) {
    return "data:image/png;base64," + result.predictions[0].bytesBase64Encoded;
  } else {
    throw new Error("Could not extract image bytes from Imagen API response");
  }
}

export type TabKey = 'overview' | 'blueprint' | 'marketplace' | 'orders' | 'deliveries' | 'recurring' | 'suppliers' | 'compliance' | 'chats' | 'analytics' | 'admin' | 'deck';


interface SidebarProps {
  activeTab: TabKey;
  setActiveTab: (t: TabKey) => void;
  collapsed: boolean;
  setCollapsed: (c: boolean) => void;
  role: string;
  pendingSupplierCount: number;
  cartCount: number;
}

export function Sidebar({ activeTab, setActiveTab, collapsed, setCollapsed, role, pendingSupplierCount, cartCount }: SidebarProps) {
  const { t } = useContext(LanguageContext)!;

  return (
    <aside className={`bg-emerald-950 text-white flex flex-col justify-between shrink-0 shadow-2xl transition-all duration-300 border-r border-emerald-900 ${collapsed ? 'w-20' : 'w-64'}`}>
      <div className="overflow-y-auto">
        <div className={`p-6 border-b border-emerald-900 bg-emerald-950 flex items-center gap-3 overflow-hidden ${collapsed ? 'justify-center w-full' : ''}`}>
          <div className="w-9 h-9 rounded-xl bg-orange-500 flex items-center justify-center shrink-0 shadow-md">
            <ShieldCheck className="w-5 h-5 text-emerald-950 font-black" />
          </div>
          {!collapsed && (
            <div className="min-w-0">
              <span className="text-sm font-extrabold tracking-tight block font-sans">CanteenSupply</span>
              <span className="text-orange-400 text-[9px] font-black tracking-widest uppercase block mt-0.5">Kelantan Core OS</span>
            </div>
          )}
        </div>
        <nav className="px-2.5 py-4 space-y-1">
          <SidebarItem icon={LayoutDashboard} label={t('dashboard')} active={activeTab === 'overview'} onClick={() => setActiveTab('overview')} collapsed={collapsed} />
          <SidebarItem icon={BookOpen} label={t('gtmBlueprint')} active={activeTab === 'blueprint'} onClick={() => setActiveTab('blueprint')} collapsed={collapsed} />
          <SidebarItem icon={Package} label={t('compliantMarket')} active={activeTab === 'marketplace'} onClick={() => setActiveTab('marketplace')} collapsed={collapsed} count={cartCount > 0 ? cartCount : undefined} />
          <SidebarItem icon={ShoppingCart} label={t('orderBatches')} active={activeTab === 'orders'} onClick={() => setActiveTab('orders')} collapsed={collapsed} />
          <SidebarItem icon={Truck} label={t('deliveryRuns')} active={activeTab === 'deliveries'} onClick={() => setActiveTab('deliveries')} collapsed={collapsed} />
          <SidebarItem icon={Calendar} label={t('recurringCycles')} active={activeTab === 'recurring'} onClick={() => setActiveTab('recurring')} collapsed={collapsed} />
          <SidebarItem icon={Users} label={t('accreditedSuppliers')} active={activeTab === 'suppliers'} onClick={() => setActiveTab('suppliers')} collapsed={collapsed} />
          <SidebarItem icon={Sliders} label={t('kpmPolicySandbox')} active={activeTab === 'compliance'} onClick={() => setActiveTab('compliance')} collapsed={collapsed} />
          <SidebarItem icon={MessageSquare} label={t('chatsCopilot')} active={activeTab === 'chats'} onClick={() => setActiveTab('chats')} collapsed={collapsed} />
          <SidebarItem icon={BarChart3} label={t('nutrientAnalytics')} active={activeTab === 'analytics'} onClick={() => setActiveTab('analytics')} collapsed={collapsed} />
          {role === 'admin' && (
            <SidebarItem icon={Building} label={t('adminHub')} active={activeTab === 'admin'} onClick={() => setActiveTab('admin')} collapsed={collapsed} count={pendingSupplierCount > 0 ? pendingSupplierCount : undefined} />
          )}
          <SidebarItem icon={FileText} label={t('strategyDeck')} active={activeTab === 'deck'} onClick={() => setActiveTab('deck')} collapsed={collapsed} />
        </nav>
      </div>

      <div className="p-4 border-t border-emerald-900 bg-emerald-950/80">
        <button 
          onClick={() => setCollapsed(!collapsed)}
          className="w-full flex items-center justify-center p-2 rounded-xl text-emerald-300 hover:bg-emerald-900 transition-colors text-xs font-bold gap-2"
        >
          <ChevronRight className={`w-4 h-4 transition-transform ${collapsed ? '' : 'rotate-180'}`} />
          {!collapsed && <span>{t('collapse')}</span>}
        </button>
      </div>
    </aside>
  );
}

function SidebarItem({ icon: Icon, label, active, onClick, collapsed, count }: { icon: any, label: string, active: boolean, onClick: () => void, collapsed: boolean, count?: number }) {
  return (
    <button
      onClick={onClick}
      className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all text-xs font-bold relative ${
        active 
          ? 'bg-emerald-900 text-white shadow-inner border-l-4 border-orange-500' 
          : 'text-emerald-100 hover:bg-emerald-900/60 hover:text-white'
      } ${collapsed ? 'justify-center' : ''}`}
      title={label}
    >
      <Icon className="w-4 h-4 shrink-0" />
      {!collapsed && <span className="truncate">{label}</span>}
      {count !== undefined && (
        <span className="absolute right-2 top-2.5 bg-orange-500 text-emerald-950 text-[9px] font-black rounded-full px-1.5 py-0.5">
          {count}
        </span>
      )}
    </button>
  );
}


interface HeaderProps {
  currentUser: User | null;
  displayName: string;
  subtitle: string;
  zone?: string;
  searchTerm: string;
  setSearchTerm: (s: string) => void;
  notifications: Notification[];
  onMarkAllRead: () => void;
  onLogout: () => void;
}

export function Header({ currentUser, displayName, subtitle, zone, searchTerm, setSearchTerm, notifications, onMarkAllRead, onLogout }: HeaderProps) {
  const unreadCount = notifications.filter(n => !n.read).length;
  const [showNotificationDropdown, setShowNotificationDropdown] = useState(false);
  const { lang, setLang, t } = useContext(LanguageContext)!;

  return (
    <header className="bg-white border-b border-slate-100 h-16 flex items-center justify-between px-6 shrink-0 shadow-sm z-10">
      <div className="flex items-center gap-4 flex-1 max-w-md">
        <div className="relative w-full">
          <Search className="absolute left-3 top-2.5 text-slate-400 w-4 h-4" />
          <input
            type="text"
            placeholder={t('searchPlaceholder')}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-9 pr-4 py-1.5 border border-slate-200 rounded-xl text-xs bg-slate-50 outline-none focus:bg-white focus:ring-2 focus:ring-emerald-700 transition-all shadow-inner"
          />
        </div>
        <span className="hidden md:inline-flex text-[10px] font-bold px-3 py-1 bg-emerald-50 text-emerald-800 rounded-full border border-emerald-100 items-center gap-1.5 shrink-0">
          <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span> 
          {t('activeJajahan')}: <strong className="text-emerald-950 font-extrabold uppercase">{zone || 'Kelantan Core'}</strong>
        </span>
      </div>

      <div className="flex items-center gap-4 shrink-0">
        <div className="flex items-center bg-slate-100 p-1 rounded-xl border border-slate-200">
          <button 
            onClick={() => setLang('bm')}
            className={`px-3 py-1 rounded-lg text-[10px] font-black tracking-wider transition-all uppercase ${lang === 'bm' ? 'bg-white text-emerald-900 shadow-sm' : 'text-slate-500'}`}
          >
            BM
          </button>
          <button 
            onClick={() => setLang('en')}
            className={`px-3 py-1 rounded-lg text-[10px] font-black tracking-wider transition-all uppercase ${lang === 'en' ? 'bg-white text-emerald-900 shadow-sm' : 'text-slate-500'}`}
          >
            EN
          </button>
        </div>

        <div className="relative">
          <button 
            onClick={() => setShowNotificationDropdown(!showNotificationDropdown)}
            className="p-2 text-slate-600 hover:text-slate-900 hover:bg-slate-50 rounded-xl transition-all relative border border-slate-200"
          >
            <Clock className="w-4 h-4" />
            {unreadCount > 0 && (
              <span className="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-rose-500 text-[8px] font-black text-white">
                {unreadCount}
              </span>
            )}
          </button>

          {showNotificationDropdown && (
            <div className="modal-pop absolute right-0 mt-2 w-80 bg-white border border-slate-200 rounded-2xl shadow-xl z-50 p-4">
              <div className="flex justify-between items-center border-b pb-2 mb-2">
                <h4 className="text-xs font-extrabold text-slate-900 uppercase">{t('recentAlerts')}</h4>
                {unreadCount > 0 && (
                  <button onClick={onMarkAllRead} className="text-[10px] text-emerald-800 font-extrabold hover:underline">
                    {t('clearAll')}
                  </button>
                )}
              </div>
              <div className="max-h-60 overflow-y-auto space-y-2">
                {notifications.length === 0 ? (
                  <p className="text-[10px] text-slate-400 text-center py-4">{t('noAlerts')}</p>
                ) : (
                  notifications.map(n => (
                    <div key={n.id} className={`p-2.5 rounded-xl border ${n.read ? 'bg-slate-50 border-slate-100' : 'bg-emerald-50/50 border-emerald-100'} text-[11px]`}>
                      <span className="font-bold text-slate-800 block">{lang === 'bm' ? n.title : (n.titleEn || n.title)}</span>
                      <p className="text-slate-500 mt-0.5 leading-relaxed">{lang === 'bm' ? n.body : (n.bodyEn || n.body)}</p>
                    </div>
                  ))
                )}
              </div>
            </div>
          )}
        </div>

        <div className="flex items-center gap-2 border-l pl-4 border-slate-200">
          <div className="text-right">
            <span className="text-xs font-extrabold text-slate-900 block">{displayName}</span>
            <span className="text-[10px] text-emerald-800 font-bold uppercase tracking-wider block">{subtitle}</span>
          </div>
          <button 
            onClick={onLogout}
            className="p-2 text-slate-400 hover:text-rose-500 rounded-xl hover:bg-rose-50 transition-all border border-slate-200"
            title={t('logout')}
          >
            <LogOut className="w-4 h-4" />
          </button>
        </div>
      </div>
    </header>
  );
}


interface AuthScreenProps {
  onAuth: (u: User, profile: any) => void;
  onBackToLanding: () => void;
}

export function AuthScreen({ onAuth, onBackToLanding }: AuthScreenProps) {
  const [isRegister, setIsRegister] = useState(false);
  const [role, setRole] = useState<'buyer' | 'supplier' | 'regulator'>('buyer');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [orgName, setOrgName] = useState('');
  const [zone, setZone] = useState('Kota Bharu');
  const { lang, setLang, t } = useContext(LanguageContext)!;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const tempUserId = "usr-" + Date.now();
    const generatedUser: User = {
      id: tempUserId,
      name: name || (role === 'buyer' ? 'Kak Yah Chepa' : 'Ahmad Frozen'),
      email: email || tempUserId + "@canteensupply.com",
      role: role === 'regulator' ? 'regulator' : role,
      zone: zone
    };

    let generatedProfile: any = null;
    if (role === 'buyer') {
      generatedProfile = {
        id: "buy-" + Date.now(),
        userId: tempUserId,
        businessName: orgName || 'Kantin SMK Pengkalan Chepa 1',
        businessType: 'school_canteen',
        zone: zone,
        paymentPreference: 'term_30',
        preferredWindow: '06:00_07:30'
      };
    } else if (role === 'supplier') {
      generatedProfile = {
        id: "sup-" + Date.now(),
        userId: tempUserId,
        companyName: orgName || 'Ahmad Frozen Wholesales Ltd',
        whatsapp: '601112345678',
        verificationStatus: 'approved',
        zone: zone,
        minimumOrderValue: 100
      };
    }

    onAuth(generatedUser, generatedProfile);
  };

  return (
    <div className="min-h-screen flex flex-col justify-between bg-slate-50 p-4 font-sans">
      <div className="flex justify-between items-center p-4">
        <button onClick={onBackToLanding} className="flex items-center gap-2 text-xs font-bold text-slate-600 hover:text-slate-900 bg-white shadow-sm border px-3.5 py-1.5 rounded-xl transition-all">
          <ArrowRight className="w-4 h-4 rotate-180" /> Back
        </button>
        <div className="flex items-center bg-white p-1 rounded-xl border border-slate-200 shadow-sm">
          <button 
            onClick={() => setLang('bm')}
            className={`px-3 py-1 rounded-lg text-[10px] font-black tracking-wider transition-all uppercase ${lang === 'bm' ? 'bg-emerald-950 text-white shadow-sm' : 'text-slate-500'}`}
          >
            BM
          </button>
          <button 
            onClick={() => setLang('en')}
            className={`px-3 py-1 rounded-lg text-[10px] font-black tracking-wider transition-all uppercase ${lang === 'en' ? 'bg-emerald-950 text-white shadow-sm' : 'text-slate-500'}`}
          >
            EN
          </button>
        </div>
      </div>
      <div className="flex-1 flex items-center justify-center">
        <div className="bg-white rounded-3xl overflow-hidden max-w-4xl w-full flex flex-col md:flex-row shadow-2xl border border-slate-100 modal-pop">
          <div className="md:w-1/2 bg-emerald-950 text-white p-12 flex flex-col justify-between border-r border-emerald-900">
            <div>
              <div className="flex items-center gap-2">
                <ShieldCheck className="w-8 h-8 text-orange-400 font-extrabold" />
                <span className="text-lg font-black tracking-wider">CanteenSupply OS</span>
              </div>
              <p className="text-emerald-200 text-xs font-semibold leading-relaxed mt-6">
                {lang === 'bm' 
                  ? 'Rangkaian B2B Kelantan yang ditapis bagi memandu rantaian bekalan makanan kantin sekolah yang patuh sepenuhnya dasar kerajaan.'
                  : 'Vetted Kelantan B2B network driving compliant food supply chains with zero-friction automation matching government directives.'
                }
              </p>
            </div>

            <div className="space-y-4 pt-12">
              <div className="flex gap-2 items-start text-xs text-emerald-100 leading-snug">
                <span className="p-1 bg-emerald-900 rounded-lg text-orange-400">
                  <CheckCircle size={14} />
                </span>
                <span>
                  {lang === 'bm'
                    ? 'Parameter sistem menguatkuasakan pekeliling dasar nutrisi KPM S_max, Na_max dan F_max.'
                    : 'System parameters enforce KPM nutrition guidelines S_max, Na_max and F_max rules.'
                  }
                </span>
              </div>
            </div>
          </div>

          <div className="p-8 md:w-1/2 flex flex-col justify-center">
            <span className="text-[10px] uppercase font-bold tracking-widest text-emerald-800 block">System Access Gateway</span>
            <h1 className="text-xl font-bold text-slate-950 mt-1">{isRegister ? (lang === 'bm' ? 'Daftar Akaun' : 'Register Account') : (lang === 'bm' ? 'Log Masuk Sistem' : 'Gateway Log In')}</h1>
            
            <form onSubmit={handleSubmit} className="space-y-4 mt-6">
              <div>
                <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">
                  {lang === 'bm' ? 'Nama Penuh Anda' : 'Your Full Name'}
                </label>
                <input 
                  type="text" 
                  required
                  className="w-full p-2.5 border border-slate-200 rounded-xl text-xs bg-slate-50 outline-none focus:bg-white focus:ring-2 focus:ring-emerald-700 transition-all" 
                  placeholder={lang === 'bm' ? "Kak Yah Chepa / Ahmad Frozen" : "Your Name"} 
                  value={name}
                  onChange={e => setName(e.target.value)}
                />
              </div>

              <div>
                <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">
                  {lang === 'bm' ? 'Pilih Peranan Sistem' : 'Select System Role'}
                </label>
                <div className="grid grid-cols-3 gap-1.5 p-1 bg-slate-100 rounded-xl">
                  <button 
                    type="button" 
                    onClick={() => setRole('buyer')}
                    className={`py-1.5 rounded-lg text-[10px] font-bold transition-all ${role === 'buyer' ? 'bg-white text-emerald-950 shadow-sm' : 'text-slate-500'}`}
                  >
                    {lang === 'bm' ? 'Pengendali Kantin' : 'Canteen'}
                  </button>
                  <button 
                    type="button" 
                    onClick={() => setRole('supplier')}
                    className={`py-1.5 rounded-lg text-[10px] font-bold transition-all ${role === 'supplier' ? 'bg-white text-emerald-950 shadow-sm' : 'text-slate-500'}`}
                  >
                    {lang === 'bm' ? 'Pembekal' : 'Supplier'}
                  </button>
                  <button 
                    type="button" 
                    onClick={() => setRole('regulator')}
                    className={`py-1.5 rounded-lg text-[10px] font-bold transition-all ${role === 'regulator' ? 'bg-white text-emerald-950 shadow-sm' : 'text-slate-500'}`}
                  >
                    {lang === 'bm' ? 'Pegawai KPM' : 'Regulator'}
                  </button>
                </div>
              </div>

              {role !== 'regulator' && (
                <div>
                  <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">
                    {role === 'buyer' ? (lang === 'bm' ? 'Nama Kantin/Sekolah' : 'Canteen/School Name') : (lang === 'bm' ? 'Nama Syarikat Pembekal' : 'Frozen Company Name')}
                  </label>
                  <input 
                    type="text" 
                    required
                    className="w-full p-2.5 border border-slate-200 rounded-xl text-xs bg-slate-50 outline-none focus:bg-white focus:ring-2 focus:ring-emerald-700 transition-all" 
                    placeholder={role === 'buyer' ? 'SMK Pengkalan Chepa 1' : 'Warisan Tok Ba Frozen'}
                    value={orgName}
                    onChange={e => setOrgName(e.target.value)}
                  />
                </div>
              )}

              <div>
                <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">
                  {lang === 'bm' ? 'Zon Jajahan Pembekalan' : 'Regional Jajahan Zone'}
                </label>
                <select 
                  value={zone}
                  onChange={e => setZone(e.target.value)}
                  className="w-full p-2.5 border border-slate-200 rounded-xl text-xs bg-slate-50 outline-none focus:bg-white focus:ring-2 focus:ring-emerald-700 transition-all"
                >
                  <option value="Kota Bharu">Kota Bharu</option>
                  <option value="Pasir Mas">Pasir Mas</option>
                  <option value="Tumpat">Tumpat</option>
                  <option value="Bachok">Bachok</option>
                  <option value="Tanah Merah">Tanah Merah</option>
                </select>
              </div>

              <button 
                type="submit" 
                className="w-full py-3 bg-emerald-800 hover:bg-emerald-950 text-white rounded-xl text-xs font-extrabold shadow-lg transition-all uppercase tracking-wider"
              >
                {lang === 'bm' ? 'Masuk Gerbang Sistem' : 'Access System Gate'}
              </button>

              <div className="text-center mt-4">
                <button 
                  type="button" 
                  onClick={() => setIsRegister(!isRegister)} 
                  className="text-[10px] text-emerald-800 font-extrabold hover:underline"
                >
                  {isRegister ? (lang === 'bm' ? 'Dah daftar? Log masuk di sini' : 'Already registered? Log in instead') : (lang === 'bm' ? 'Pertama kali guna? Daftar akaun perniagaan' : 'New to CanteenSupply? Register business account')}
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
      <footer className="py-4 text-center text-[11px] text-slate-400 font-medium">
        {t('footerBranding')}
      </footer>
    </div>
  );
}


interface LandingScreenProps {
  onLaunchDemo: () => void;
}

export function LandingScreen({ onLaunchDemo }: LandingScreenProps) {
  const { lang, setLang, t } = useContext(LanguageContext)!;

  return (
    <div className="min-h-screen bg-white text-slate-900 font-sans flex flex-col justify-between">
      {/* Navbar */}
      <nav className="border-b bg-white/95 backdrop-blur sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 bg-emerald-600 rounded-xl flex items-center justify-center">
              <span className="text-white font-bold text-xl">CS</span>
            </div>
            <div>
              <div className="font-semibold text-xl tracking-tight">CanteenSupply</div>
              <div className="text-[10px] text-gray-500 -mt-1">Kota Bharu • Kelantan</div>
            </div>
          </div>
          <div className="flex items-center gap-4">
            <div className="flex items-center bg-slate-100 p-1 rounded-xl border border-slate-200">
              <button 
                onClick={() => setLang('bm')}
                className={`px-3 py-1 rounded-lg text-[10px] font-black tracking-wider transition-all uppercase ${lang === 'bm' ? 'bg-emerald-950 text-white shadow-sm' : 'text-slate-500'}`}
              >
                BM
              </button>
              <button 
                onClick={() => setLang('en')}
                className={`px-3 py-1 rounded-lg text-[10px] font-black tracking-wider transition-all uppercase ${lang === 'en' ? 'bg-emerald-950 text-white shadow-sm' : 'text-slate-500'}`}
              >
                EN
              </button>
            </div>
            <button 
              onClick={onLaunchDemo} 
              className="px-4 py-2 bg-black text-white rounded-full text-sm font-medium hover:bg-gray-800 transition-colors"
            >
              {t('launchDemo')}
            </button>
          </div>
        </div>
      </nav>

      {/* Hero */}
      <div className="max-w-5xl mx-auto px-6 pt-20 pb-16 text-center">
        <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-emerald-50 text-emerald-700 text-xs font-medium mb-6">
          <div className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse" /> LIVE • KPM COMPLIANCE ENGINE VERIFIED
        </div>
        
        <h1 className="text-4xl md:text-6xl font-semibold tracking-tighter leading-none mb-4">
          {t('heroTitle')}
        </h1>
        <p className="text-lg md:text-xl text-gray-600 max-w-lg mx-auto mb-8">
          {t('heroDesc')}
        </p>

        <div className="flex items-center justify-center gap-3">
          <button 
            onClick={onLaunchDemo} 
            className="inline-flex items-center gap-2 bg-black hover:bg-gray-900 text-white px-8 py-3.5 rounded-2xl text-lg font-medium transition-all active:scale-[0.985]"
          >
            {t('launchDemo')} <ArrowRight className="w-5 h-5" />
          </button>
          <a href="#features" className="px-8 py-3.5 text-lg font-medium border border-gray-300 rounded-2xl hover:bg-gray-50 transition-all">
            {t('seeFeatures')}
          </a>
        </div>

        <div className="mt-8 text-xs text-gray-500">
          Demo credentials: admin / supplier / buyer<br />
          No complex registration required. Select any role to instantly interact.
        </div>
      </div>

      {/* Key Features */}
      <div id="features" className="max-w-6xl mx-auto px-6 pb-20">
        <h2 className="text-2xl font-bold tracking-tight text-center mb-10">{t('featuresTitle')}</h2>
        <div className="grid md:grid-cols-4 gap-6">
          {[
            { icon: Shield, title: lang === 'bm' ? "Enjin Pematuhan KPM" : "KPM Compliance Engine", desc: lang === 'bm' ? "Menolak produk dilarang secara automatik. Skor gizi menu secara langsung." : "Auto-blocks prohibited items. Real-time nutrition scoring." },
            { icon: Clock, title: lang === 'bm' ? "Pesanan Harian Pintar" : "Smart Daily Ordering", desc: lang === 'bm' ? "Had masa jam 2:00 Petang. Penghantaran lancar untuk pesanan selepas waktu rehat." : "2:00 PM cut-off. Same-day delivery for post-recess orders." },
            { icon: Truck, title: lang === 'bm' ? "Penghantaran Terus ke Sekolah" : "Direct-to-School Delivery", desc: lang === 'bm' ? "Laluan berulang berjadual, lencana pemandu sah, minimum pesanan fleksibel." : "Recurring routes, school-ready badges, free delivery thresholds." },
            { icon: Users, title: lang === 'bm' ? "Akses Berasaskan Peranan" : "Role-based Access", desc: lang === 'bm' ? "Papan pemuka berasingan untuk Admin, Pembekal, dan Operator dengan integrasi WhatsApp." : "Admin, Supplier, Buyer dashboards with WhatsApp integration." },
          ].map((f, i) => (
            <div key={i} className="bg-white border rounded-3xl p-7 hover:shadow-md transition-all">
              <f.icon className="w-9 h-9 mb-6 text-emerald-600" />
              <div className="font-semibold text-xl tracking-tight mb-2">{f.title}</div>
              <p className="text-gray-600 text-[15px] leading-snug">{f.desc}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Google Cloud Startup Brief */}
      <div id="brief" className="bg-zinc-950 text-white py-16">
        <div className="max-w-4xl mx-auto px-6">
          <div className="flex items-center gap-3 mb-4">
            <div className="px-3 py-1 bg-white/10 text-xs font-medium tracking-widest rounded-full">GOOGLE CLOUD STARTUP PROGRAM</div>
          </div>
          <h2 className="text-4xl font-semibold tracking-tight mb-4">{t('gcpScale')}</h2>
          <p className="text-zinc-400 text-lg max-w-lg mb-10">
            {t('gcpDesc')}
          </p>

          <div className="grid md:grid-cols-3 gap-4 text-sm">
            {[
              { title: "Cloud Run", desc: "Auto-scaling containerized Next.js + Drizzle API" },
              { title: "AlloyDB", desc: "Managed PostgreSQL with full-text search for products" },
              { title: "Vertex AI", desc: "Future: Intelligent product matching & demand forecasting" },
              { title: "BigQuery", desc: "Compliance analytics & order trend dashboards" },
              { title: "Cloud Functions", desc: "WhatsApp OTP, payment webhooks, scheduled cut-off jobs" },
            ].map((item, idx) => (
              <div key={idx} className="border border-white/10 bg-white/5 p-5 rounded-2xl">
                <div className="font-semibold text-emerald-400 mb-1">{item.title}</div>
                <div className="text-zinc-400 text-sm">{item.desc}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Footer */}
      <footer className="border-t py-8 text-center text-xs text-gray-500 bg-slate-55">
        {t('footerBranding')}
      </footer>
    </div>
  );
}


interface OverviewTabProps {
  currentUser: User;
  buyerProfile: Buyer | null;
  supplierProfile: Supplier | null;
  analytics: AnalyticsData | null;
  orders: Order[];
  suppliers: Supplier[];
  products: Product[];
  schedules: DeliverySchedule[];
  recurring: RecurringOrder[];
  onNavigate: (t: TabKey) => void;
  onRepeatOrder: (o: Order) => void;
}

export function OverviewTab({ currentUser, buyerProfile, supplierProfile, analytics, orders, suppliers, products, schedules, recurring, onNavigate, onRepeatOrder }: OverviewTabProps) {
  const { lang, t } = useContext(LanguageContext)!;

  return (
    <div className="space-y-6 max-w-6xl animate-fade-in">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-5 rounded-2xl border border-slate-200/80 shadow-sm">
        <div>
          <h1 className="text-xl font-bold text-slate-900 flex items-center gap-2">
            {lang === 'bm' ? 'Pengawasan Operasi Langsung' : 'Live Operational Overview'}
          </h1>
          <p className="text-xs text-slate-500 mt-1">
            {lang === 'bm' 
              ? 'Portal CanteenSupply OS • Automasi rantaian perolehan dan penguatkuasaan dasar nutrisi KPM rentas kluster sekolah.' 
              : 'CanteenSupply OS Portal • Automating procurement cycles and enforcing KPM dietary rules across school clusters.'}
          </p>
        </div>
        <div className="flex gap-2">
          <button onClick={() => onNavigate('marketplace')} className="bg-emerald-800 hover:bg-emerald-950 text-white px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow">
            <Package size={14} /> {lang === 'bm' ? 'Beli SKU Patuh KPM' : 'Order Compliant SKU'}
          </button>
          <button onClick={() => onNavigate('compliance')} className="bg-orange-500 hover:bg-orange-600 text-white px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow">
            <Sliders size={14} /> {lang === 'bm' ? 'Kotak Pasir Dasar' : 'Policy Sandbox'}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <StatCard icon={TrendingUp} title={t('activeShipments')} value={orders.filter(o => o.status !== 'cancelled').length} subtext={lang === 'bm' ? 'Dipetakan mengikut jajahan' : 'Tracked per district'} color="bg-blue-50 text-blue-800 border-blue-100" />
        <StatCard icon={ShieldCheck} title={t('kpmVettedRate')} value="100%" subtext={lang === 'bm' ? 'Menyingkirkan 13 kelas larangan' : 'Excluding 13 banned classes'} color="bg-emerald-50 text-emerald-800 border-emerald-100" />
        <StatCard icon={ShoppingCart} title={t('automatedCycles')} value={recurring.filter(r => r.active).length} subtext={lang === 'bm' ? 'Kontrak berkala mingguan' : 'Recurring weekly contracts'} color="bg-purple-50 text-purple-800 border-purple-100" />
        <StatCard icon={Users} title={t('accreditedCount')} value={suppliers.filter(s => s.verificationStatus === 'approved').length} subtext={lang === 'bm' ? 'Saringan JAKIM & KPM' : 'JAKIM & KPM approved'} color="bg-amber-50 text-amber-800 border-amber-100" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm space-y-4">
          <div className="flex justify-between items-center border-b pb-2">
            <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900 flex items-center gap-1.5">
              <MapPin className="text-emerald-800" /> {t('deliveryNodes')}
            </h3>
            <span className="text-[10px] text-slate-400 font-bold uppercase">{lang === 'bm' ? 'Penghantaran Berperingkat' : 'Staggered Runs'}</span>
          </div>

          <div className="space-y-2">
            {schedules.map(sch => (
              <div key={sch.id} className="border border-slate-100 p-3 rounded-xl bg-slate-50 hover:bg-slate-100/50 transition-all flex justify-between items-center">
                <div>
                  <h4 className="font-extrabold text-xs text-slate-900">{lang === 'bm' ? sch.zone : (sch.zoneEn || sch.zone)}</h4>
                  <p className="text-[10px] text-slate-400 mt-0.5 uppercase font-bold tracking-wide">{t('nextWindow')}: {sch.timeWindow}</p>
                </div>
                <div className="text-right">
                  <span className="text-[10px] text-slate-500 block">{t('orderCutoff')}</span>
                  <span className="text-[11px] font-extrabold text-orange-600 block">{sch.cutoff}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm lg:col-span-2 space-y-4">
          <div className="flex justify-between items-center border-b pb-2">
            <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900 flex items-center gap-1.5">
              <Clock className="text-emerald-800" /> {t('recentOrderBatches')}
            </h3>
            <button onClick={() => onNavigate('orders')} className="text-[10px] text-emerald-800 font-extrabold hover:underline">
              {t('viewAllBatches')}
            </button>
          </div>

          <div className="space-y-2.5">
            {orders.map(order => (
              <div key={order.id} className="border border-slate-100 p-3.5 rounded-2xl bg-slate-50 flex flex-col md:flex-row justify-between items-start md:items-center gap-3">
                <div>
                  <div className="flex items-center gap-2">
                    <strong className="text-xs text-slate-900 font-extrabold">{order.orderNumber}</strong>
                    <span className="text-[9px] bg-slate-200 text-slate-700 font-extrabold px-2 py-0.5 rounded uppercase">
                      {order.deliveryZone}
                    </span>
                  </div>
                  <p className="text-[10px] text-slate-500 mt-0.5 font-medium">
                    {lang === 'bm' 
                      ? `Penghantaran dijadualkan pada ${order.deliveryDate} (${order.deliveryWindow})`
                      : `Batch scheduled for ${order.deliveryDate} (${order.deliveryWindow})`
                    }
                  </p>
                </div>
                <div className="flex items-center gap-4 w-full md:w-auto justify-between md:justify-end border-t md:border-none pt-2 md:pt-0">
                  <strong className="text-xs text-slate-950 font-black">RM {order.total.toFixed(2)}</strong>
                  <div className="flex gap-1.5">
                    <OrderStatusBadge status={order.status} />
                    {order.status === 'delivered' && (
                      <button 
                        onClick={() => onRepeatOrder(order)}
                        className="text-[10px] bg-emerald-800 hover:bg-emerald-950 text-white font-extrabold px-3 py-1 rounded-lg"
                      >
                        {t('repeatCycle')}
                      </button>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="bg-emerald-950 text-white rounded-3xl p-6 flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div className="space-y-2 max-w-xl">
          <span className="text-[10px] bg-emerald-900 text-orange-400 font-extrabold px-3 py-1 rounded-full uppercase tracking-wider inline-block">
            {lang === 'bm' ? 'Sorotan Kempen: Sarapan Sihat Kelantan' : 'Campaign Highlight: Kelantan Healthy Breakfast'}
          </span>
          <h2 className="text-lg font-black tracking-tight mt-1">
            {lang === 'bm' ? 'Menaja Pakej Bento Sihat Sekolah' : 'Sponsoring Nutritious School Bento Bundles'}
          </h2>
          <p className="text-xs text-emerald-200 leading-relaxed">
            {lang === 'bm'
              ? 'Badan bukan kerajaan (NGO) tempatan bekerjasama dengan platform CanteenSupply bagi mengagihkan dana makanan tambahan bento sihat secara terus di Pasir Mas dan Kota Bharu.'
              : 'Local non-governmental organizations are utilizing CanteenSupply standard healthy bento packs to fund micronutrient supplementation directly in Pasir Mas and Kota Bharu school canteens.'
            }
          </p>
        </div>
        <button onClick={() => onNavigate('blueprint')} className="bg-orange-500 hover:bg-orange-600 text-white font-extrabold text-xs px-5 py-3 rounded-xl shadow-lg transition-all flex items-center gap-1.5 shrink-0">
          {lang === 'bm' ? 'Analisis Pelan Induk' : 'Analyze Blueprint'} <ArrowRight className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}


export interface CartItem {
  product: Product;
  quantity: number;
}

interface MarketplaceTabProps {
  products: Product[];
  suppliers: Supplier[];
  schedules: DeliverySchedule[];
  buyerProfile: Buyer | null;
  role: string;
  searchTerm: string;
  cart: CartItem[];
  setCart: React.Dispatch<React.SetStateAction<CartItem[]>>;
  onCheckout: (payload: any) => Promise<any>;
  onEditProduct: (p: Product) => void;
  onDeleteProduct: (id: string) => void;
  onAddProduct: () => void;
}

export function MarketplaceTab({ products, suppliers, schedules, buyerProfile, role, searchTerm, cart, setCart, onCheckout, onEditProduct, onDeleteProduct, onAddProduct }: MarketplaceTabProps) {
  const { showToast } = useToast();
  const { lang, t } = useContext(LanguageContext)!;
  const [selectedCategory, setSelectedCategory] = useState('All');
  const [selectedSupplierId, setSelectedSupplierId] = useState('All');

  // AI Generated Healthy Bundle State
  const [isAiLoading, setIsAiLoading] = useState(false);
  const [isGeneratingImage, setIsGeneratingImage] = useState(false);
  const [aiGeneratedBundle, setAiGeneratedBundle] = useState<any | null>(null);
  const [aiGeneratedImage, setAiGeneratedImage] = useState<string | null>(null);

  const categories = ['All', 'Chicken', 'Processed Meat', 'Finger Food', 'Drinks', 'Frozen Kuih'];

  const filtered = useMemo(() => {
    return products.filter(p => {
      const matchSearch = p.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
                          (p.nameEn && p.nameEn.toLowerCase().includes(searchTerm.toLowerCase())) ||
                          p.category.toLowerCase().includes(searchTerm.toLowerCase());
      const matchCat = selectedCategory === 'All' || p.category === selectedCategory;
      const matchSup = selectedSupplierId === 'All' || p.supplierId === selectedSupplierId;
      return matchSearch && matchCat && matchSup;
    });
  }, [products, searchTerm, selectedCategory, selectedSupplierId]);

  const handleAddToCart = (product: Product) => {
    if (product.complianceStatus === 'prohibited') {
      showToast(
        lang === 'bm' ? "Saringan disekat" : "Cannot add item", 
        lang === 'bm' ? "SKU ini ditandakan sebagai dilarang di bawah polisi KPM." : "This SKU is marked prohibited under active KPM rules.", 
        "error"
      );
      return;
    }

    if (cart.length > 0 && cart[0].product.supplierId !== product.supplierId) {
      showToast(
        lang === 'bm' ? "Had Tunggal Pemborong" : "Single Wholesaler checkout limit", 
        lang === 'bm' ? "CanteenSupply menyelaraskan penghantaran dari satu pembekal bagi setiap sesi bagi memelihara kecekapan logistik." : "CanteenSupply coordinates delivery from one supplier per order batch to preserve morning logistics efficiency.", 
        "info"
      );
      return;
    }

    setCart(prev => {
      const exist = prev.find(item => item.product.id === product.id);
      if (exist) {
        return prev.map(item => item.product.id === product.id ? { ...item, quantity: item.quantity + 1 } : item);
      }
      return [...prev, { product, quantity: 1 }];
    });
    showToast(lang === 'bm' ? "Ditambah ke Kumpulan" : "Added to Cart", (lang === 'bm' ? product.name : (product.nameEn || product.name)) + " is ready.");
  };

  const handleUpdateCartQty = (id: string, qty: number) => {
    if (qty <= 0) {
      setCart(prev => prev.filter(item => item.product.id !== id));
      return;
    }
    setCart(prev => prev.map(item => item.product.id === id ? { ...item, quantity: qty } : item));
  };

  const cartTotal = cart.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);

  const handleCartCheckout = async () => {
    if (cart.length === 0) return;
    if (!buyerProfile) {
      showToast(
        lang === 'bm' ? "Akses Terhad" : "Action restricted", 
        lang === 'bm' ? "Sila daftar masuk sebagai operator kantin sekolah untuk membuat pesanan." : "Please log in with a Canteen Operator profile to commit purchasing runs.", 
        "error"
      );
      return;
    }

    const payload = {
      buyerId: buyerProfile.id,
      supplierId: cart[0].product.supplierId,
      items: cart.map(item => ({ productId: item.product.id, quantity: item.quantity })),
      paymentMethod: buyerProfile.paymentPreference,
      deliveryDate: new Date(Date.now() + 86400000).toISOString().split('T')[0],
      deliveryWindow: buyerProfile.preferredWindow,
      deliveryZone: buyerProfile.zone,
      notes: "Auto checkout from Compliant Market interface."
    };

    try {
      const result = await onCheckout(payload);
      setCart([]);
      if (result && result.supplierWhatsapp) {
        const whatsappMsg = `Salam, order CanteenSupply baru dikomit untuk ${buyerProfile.businessName}. Total: RM ${cartTotal.toFixed(2)}. Sila semak dashboard anda sebelum had masa.`;
        window.open("https://wa.me/" + result.supplierWhatsapp + "?text=" + encodeURIComponent(whatsappMsg), '_blank');
      }
    } catch (e) {
      // Handled globally
    }
  };

  const generateAiBundlePack = async () => {
    setIsAiLoading(true);
    setAiGeneratedBundle(null);
    setAiGeneratedImage(null);

    const userQuery = 'Create a brand new "KPM Compliant Healthy Bento Bundle Pack" using compliant raw ingredients like chicken breast, wholemeal sandwich loaves, low sugar malt mix. Frame it beautifully for the Kelantan school cluster. Define Name, price, targeted student count, and step-by-step description.';
    const systemPrompt = 'You are a world-class institutional nutritionist and school catering consultant. Output the proposed bundle pack strictly as a structured JSON object with properties "bundleName" (string), "totalPrice" (number), "targetedServings" (number), "itemsList" (array of strings), and "description" (string). Output pure JSON with no markdown wrapping.';
    
    const responseSchema = {
      type: "OBJECT",
      properties: {
        bundleName: { type: "STRING" },
        totalPrice: { type: "NUMBER" },
        targetedServings: { type: "NUMBER" },
        itemsList: { type: "ARRAY", items: { type: "STRING" } },
        description: { type: "STRING" }
      },
      required: ["bundleName", "totalPrice", "targetedServings", "itemsList", "description"]
    };

    try {
      const data = await callGeminiStructured(userQuery, systemPrompt, responseSchema);
      setAiGeneratedBundle(data);
      showToast(
        lang === 'bm' ? "Pakej AI Dijana" : "AI Bundle Generated", 
        lang === 'bm' ? "Pakej makanan sihat automatik berjaya disusun." : "Dynamic healthy package compiled."
      );
    } catch (err) {
      console.error(err);
      showToast(
        lang === 'bm' ? "Saringan AI Gagal" : "AI Generation Failed", 
        lang === 'bm' ? "Gagal menghubungkan parameter API dasar ke pelayan." : "Unable to establish secure LLM API token handshake.", 
        "error"
      );
    } finally {
      setIsAiLoading(false);
    }
  };

  const generateAiBundleVisualProof = async () => {
    if (!aiGeneratedBundle) return;
    setIsGeneratingImage(true);
    setAiGeneratedImage(null);

    const prompt = `A professional food photography shot of a healthy Malaysian school canteen bento set named "${aiGeneratedBundle.bundleName}", featuring ingredients like ${aiGeneratedBundle.itemsList.join(', ')}. Laid out nicely on a modern white lunch tray inside a bright modern kitchen. High detailed, realistic.`;
    
    try {
      const imageUri = await callImagenGenerate(prompt);
      setAiGeneratedImage(imageUri);
      showToast(
        lang === 'bm' ? "Bukti Visual Dimuatkan" : "Visual Proof Loaded", 
        lang === 'bm' ? "Penjanaan mockup definisi tinggi menggunakan Imagen 4.0 berjaya!" : "Generated high-definition visual mockup with Imagen 4.0!"
      );
    } catch (err) {
      console.error(err);
      showToast(
        lang === 'bm' ? "Mockup Gagal" : "Mockup Failed", 
        lang === 'bm' ? "Gagal menjana visual mockup melalui rantaian Imagen." : "An error occurred during Imagen processing.", 
        "error"
      );
    } finally {
      setIsGeneratingImage(false);
    }
  };

  return (
    <div className="space-y-6 max-w-6xl animate-fade-in">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h1 className="text-xl font-bold text-slate-900">{t('compliantMarket')}</h1>
          <p className="text-xs text-slate-500 mt-1">
            {lang === 'bm' 
              ? 'Tapis pematuhan kandungan ramuan secara automatik menepati had nutrisi kebangsaan.' 
              : 'Filter automatically handles ingredient evaluations against KPM thresholds.'}
          </p>
        </div>
        <div className="flex gap-2">
          <button 
            onClick={generateAiBundlePack}
            disabled={isAiLoading}
            className="bg-emerald-50 text-emerald-800 border border-emerald-200 px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow"
          >
            {isAiLoading ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Sparkle className="w-3.5 h-3.5 text-emerald-700 animate-pulse" />}
            <span>{lang === 'bm' ? 'Rangka Pakej AI' : 'Architect AI Bundle'}</span>
          </button>
          {role === 'supplier' && (
            <button onClick={onAddProduct} className="bg-emerald-800 text-white px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow">
              <Plus size={14} /> {t('addVettedSku')}
            </button>
          )}
        </div>
      </div>

      {aiGeneratedBundle && (
        <div className="bg-gradient-to-r from-emerald-950 to-emerald-900 text-white p-6 rounded-2xl border border-emerald-800 shadow-xl modal-pop flex flex-col md:flex-row justify-between gap-6">
          <div className="flex-1 space-y-4">
            <div className="flex items-center gap-2">
              <span className="text-[10px] bg-orange-500 text-emerald-950 font-black px-2.5 py-1 rounded-full uppercase tracking-wider">
                {lang === 'bm' ? 'VETTED BENTO SIHAT KPM' : 'VETTED HEALTHY BENTO BUNDLE'}
              </span>
              <span className="text-xs text-emerald-300 font-bold">Generated via gemini-3-flash-preview</span>
            </div>
            
            <div>
              <h2 className="text-lg font-black text-white">{aiGeneratedBundle.bundleName}</h2>
              <p className="text-xs text-emerald-100 leading-relaxed mt-1">{aiGeneratedBundle.description}</p>
            </div>

            <div className="flex flex-wrap gap-1.5">
              {aiGeneratedBundle.itemsList.map((it: string, idx: number) => (
                <span key={idx} className="bg-emerald-800/80 text-emerald-100 px-2.5 py-1 rounded-lg text-[10px] font-bold border border-emerald-700">
                  {it}
                </span>
              ))}
            </div>

            <div className="pt-2 flex items-center gap-6">
              <div>
                <span className="text-[9px] text-emerald-400 uppercase font-bold block">{lang === 'bm' ? 'Jumlah Nilai Pakej' : 'Consolidated Value'}</span>
                <strong className="text-sm font-black text-white">RM {aiGeneratedBundle.totalPrice.toFixed(2)}</strong>
              </div>
              <div>
                <span className="text-[9px] text-emerald-400 uppercase font-bold block">{lang === 'bm' ? 'Sasaran Hidangan Pelajar' : 'Target Nutrition Volume'}</span>
                <strong className="text-sm font-black text-white">{aiGeneratedBundle.targetedServings} Pax</strong>
              </div>
            </div>
          </div>

          <div className="w-full md:w-56 shrink-0 flex flex-col items-center justify-center border-t md:border-t-0 md:border-l border-emerald-800 pt-4 md:pt-0 md:pl-6 gap-3">
            {aiGeneratedImage ? (
              <div className="relative w-full h-36 bg-emerald-900 rounded-xl overflow-hidden border border-emerald-700 shadow-inner">
                <img src={aiGeneratedImage} alt="AI Visual" className="w-full h-full object-cover" />
              </div>
            ) : (
              <button 
                onClick={generateAiBundleVisualProof}
                disabled={isGeneratingImage}
                className="w-full py-4 bg-orange-500 hover:bg-orange-600 text-white rounded-xl text-xs font-black uppercase tracking-wider flex flex-col items-center justify-center gap-2 transition-all shadow-lg"
              >
                {isGeneratingImage ? (
                  <RefreshCw className="w-6 h-6 animate-spin" />
                ) : (
                  <ImageIcon className="w-6 h-6" />
                )}
                <span>{isGeneratingImage ? (lang === 'bm' ? "Menjana visual..." : "Mocking up image...") : (lang === 'bm' ? "Jana Visual AI" : "Generate AI Mockup")}</span>
              </button>
            )}
            <span className="text-[9px] text-emerald-400 text-center font-bold">Image synthesized using imagen-4.0-generate-001</span>
          </div>
        </div>
      )}

      <div className="bg-white p-4 rounded-2xl border border-slate-200/80 shadow-sm flex flex-col md:flex-row gap-4 items-center justify-between">
        <div className="flex flex-wrap gap-1.5 w-full md:w-auto">
          {categories.map(cat => (
            <button
              key={cat}
              onClick={() => setSelectedCategory(cat)}
              className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${
                selectedCategory === cat ? 'bg-emerald-900 text-white shadow-sm' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
              }`}
            >
              {cat}
            </button>
          ))}
        </div>

        <div className="flex gap-2 w-full md:w-auto">
          <select 
            value={selectedSupplierId}
            onChange={e => setSelectedSupplierId(e.target.value)}
            className="w-full md:w-48 p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 outline-none"
          >
            <option value="All">{t('allWholesalers')}</option>
            {suppliers.map(s => (
              <option key={s.id} value={s.id}>{s.companyName}</option>
            ))}
          </select>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 items-start">
        <div className="lg:col-span-3 grid grid-cols-1 md:grid-cols-3 gap-4">
          {filtered.map(p => {
            const isProhibited = p.complianceStatus === 'prohibited';
            const isRestricted = p.complianceStatus === 'restricted';
            
            return (
              <div 
                key={p.id} 
                className={`bg-white rounded-2xl border p-4 shadow-sm flex flex-col justify-between transition-all hover:-translate-y-0.5 hover:shadow-md ${
                  isProhibited ? 'border-rose-100 opacity-90' : isRestricted ? 'border-amber-200' : 'border-slate-200/80'
                }`}
              >
                <div>
                  <div className="flex justify-between items-start mb-2">
                    <span className="text-[9px] bg-slate-100 text-slate-500 font-extrabold px-2 py-0.5 rounded uppercase">
                      {p.category}
                    </span>
                    <ComplianceBadge status={p.complianceStatus} />
                  </div>

                  <h3 className="font-extrabold text-slate-900 text-xs leading-snug">{lang === 'bm' ? p.name : (p.nameEn || p.name)}</h3>
                  <span className="text-[10px] text-slate-400 block mt-1 font-semibold">
                    {t('moq')}: {p.moq} • {t('stock')}: {p.stock}
                  </span>

                  {p.isBannedType && (
                    <span className="inline-flex items-center gap-1 text-[8px] bg-rose-50 text-rose-700 border border-rose-100 rounded p-1 mt-2 font-bold leading-normal">
                      <AlertOctagon size={10} /> {lang === 'bm' ? p.bannedCategory : (p.bannedCategoryEn || p.bannedCategory || "KPM Prohibited Filter Blocked")}
                    </span>
                  )}

                  <div className="grid grid-cols-3 gap-1 bg-slate-50/80 p-2 rounded-xl mt-3 text-center text-[9px] font-bold border border-slate-100">
                    <div>
                      <span className="text-slate-400 block uppercase">{t('sugarLabel')}</span>
                      <span className="text-slate-800">{p.sugar}g</span>
                    </div>
                    <div>
                      <span className="text-slate-400 block uppercase">{t('sodiumLabel')}</span>
                      <span className="text-slate-800">{p.sodium}mg</span>
                    </div>
                    <div>
                      <span className="text-slate-400 block uppercase">{t('fatLabel')}</span>
                      <span className="text-slate-800">{p.fat}g</span>
                    </div>
                  </div>
                </div>

                <div className="mt-4 pt-3 border-t border-slate-100 flex items-center justify-between">
                  <div>
                    <span className="text-[9px] text-slate-400 uppercase font-extrabold block">{lang === 'bm' ? 'Harga' : 'Price'}</span>
                    <strong className="text-xs font-black text-slate-950">RM {p.price.toFixed(2)}</strong>
                  </div>

                  {role === 'buyer' && (
                    <button 
                      onClick={() => handleAddToCart(p)}
                      disabled={isProhibited}
                      className={`text-[10px] font-extrabold px-3 py-1.5 rounded-xl transition-all ${
                        isProhibited 
                          ? 'bg-slate-100 text-slate-400 cursor-not-allowed' 
                          : 'bg-emerald-800 hover:bg-emerald-950 text-white'
                      }`}
                    >
                      {lang === 'bm' ? 'Pilih SKU' : 'Add To Batch'}
                    </button>
                  )}

                  {role === 'supplier' && (
                    <div className="flex gap-1.5">
                      <button onClick={() => onEditProduct(p)} className="text-[10px] bg-slate-100 hover:bg-slate-200 font-bold px-2 py-1 rounded text-slate-800">
                        Edit
                      </button>
                      <button onClick={() => onDeleteProduct(p.id)} className="text-[10px] bg-rose-50 text-rose-600 hover:bg-rose-100 font-bold px-2 py-1 rounded">
                        Delete
                      </button>
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        {role === 'buyer' && (
          <div className="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-sm space-y-4">
            <div className="flex justify-between items-center border-b pb-2">
              <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900 flex items-center gap-1.5">
                <ShoppingCart className="text-emerald-800" /> {lang === 'bm' ? 'Kumpulan Semasa' : 'Current Batch Run'}
              </h3>
              <span className="text-[10px] text-slate-400 font-bold uppercase">{cart.length} SKUs</span>
            </div>

            <div className="space-y-3 max-h-80 overflow-y-auto">
              {cart.map(item => (
                <div key={item.product.id} className="border-b pb-2 text-[11px] space-y-1">
                  <div className="flex justify-between items-start">
                    <span className="font-extrabold text-slate-800 leading-snug">{lang === 'bm' ? item.product.name : (item.product.nameEn || item.product.name)}</span>
                    <button onClick={() => handleUpdateCartQty(item.product.id, 0)} className="text-rose-500 hover:text-rose-700">
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                  <div className="flex justify-between items-center text-xs">
                    <div className="flex items-center gap-1.5">
                      <button onClick={() => handleUpdateCartQty(item.product.id, item.quantity - 1)} className="px-2 py-0.5 bg-slate-100 rounded text-xs font-bold text-slate-800">-</button>
                      <span className="font-bold text-slate-900">{item.quantity}</span>
                      <button onClick={() => handleUpdateCartQty(item.product.id, item.quantity + 1)} className="px-2 py-0.5 bg-slate-100 rounded text-xs font-bold text-slate-800">+</button>
                    </div>
                    <strong className="text-slate-950">RM {(item.product.price * item.quantity).toFixed(2)}</strong>
                  </div>
                </div>
              ))}

              {cart.length === 0 && (
                <p className="text-[10px] text-slate-400 text-center py-6 font-medium">
                  {lang === 'bm' ? 'Tiada item dipilih. Sila pilih SKU patuh di sebelah kiri.' : 'Batch empty. Select items on the left to initialize order.'}
                </p>
              )}
            </div>

            {cart.length > 0 && (
              <div className="space-y-3 pt-3 border-t">
                <div className="flex justify-between text-xs">
                  <span className="text-slate-500 font-bold uppercase">{t('estimatedSubtotal')}</span>
                  <strong className="text-slate-950 font-black text-sm">RM {cartTotal.toFixed(2)}</strong>
                </div>

                <button 
                  onClick={handleCartCheckout}
                  className="w-full py-3 bg-emerald-800 hover:bg-emerald-950 text-white rounded-xl text-xs font-extrabold uppercase tracking-wider shadow-md"
                >
                  {t('checkoutButton')}
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}


interface OrdersTabProps {
  orders: Order[];
  role: string;
  buyerProfile: Buyer | null;
  supplierProfile: Supplier | null;
  searchTerm: string;
  suppliers: Supplier[];
  onUpdateOrder: (id: string, patch: Record<string, any>) => void;
  onRepeatOrder: (o: Order) => void;
  onCancelOrder: (id: string) => void;
}

export function OrdersTab({ orders, role, buyerProfile, supplierProfile, searchTerm, suppliers, onUpdateOrder, onRepeatOrder, onCancelOrder }: OrdersTabProps) {
  const { lang, t } = useContext(LanguageContext)!;

  const filtered = useMemo(() => {
    return orders.filter(o => {
      const matchSearch = o.orderNumber.includes(searchTerm) || o.deliveryZone.toLowerCase().includes(searchTerm.toLowerCase());
      
      if (role === 'buyer' && buyerProfile) {
        return matchSearch && o.buyerId === buyerProfile.id;
      }
      if (role === 'supplier' && supplierProfile) {
        return matchSearch && o.supplierId === supplierProfile.id;
      }
      return matchSearch;
    });
  }, [orders, role, buyerProfile, supplierProfile, searchTerm]);

  return (
    <div className="space-y-6 max-w-6xl animate-fade-in font-sans">
      <div>
        <h1 className="text-xl font-bold text-slate-900">{lang === 'bm' ? 'Log Manifest Kumpulan Pesanan' : 'Order Manifest Logs'}</h1>
        <p className="text-xs text-slate-500 mt-1">
          {lang === 'bm' 
            ? 'Menjejaki pesanan B2B kantin sekolah Kelantan sebelum had masa harian.' 
            : 'Tracking B2B purchase commitments before daily cut-offs.'}
        </p>
      </div>

      <div className="bg-white rounded-2xl border border-slate-200/80 shadow-sm overflow-hidden">
        <table className="w-full text-left border-collapse text-xs">
          <thead>
            <tr className="bg-slate-50 border-b border-slate-200 text-slate-500 font-extrabold uppercase tracking-wider">
              <th className="p-4">{lang === 'bm' ? 'ID Sesi / Tarikh' : 'Batch ID / Date'}</th>
              <th className="p-4">{lang === 'bm' ? 'Tetingkap Penghantaran' : 'Delivery Window'}</th>
              <th className="p-4">{lang === 'bm' ? 'Item Pembelian' : 'Purchase Items'}</th>
              <th className="p-4">{lang === 'bm' ? 'Jumlah Harga' : 'Total Price'}</th>
              <th className="p-4">{lang === 'bm' ? 'Status Batches' : 'Fulfillment State'}</th>
              <th className="p-4 text-right">{lang === 'bm' ? 'Tindakan' : 'Actions'}</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100 text-slate-700">
            {filtered.map(o => (
              <tr key={o.id} className="hover:bg-slate-50/40 transition-colors">
                <td className="p-4">
                  <div className="font-extrabold text-slate-950 text-xs">{o.orderNumber}</div>
                  <div className="text-[10px] text-slate-400 mt-0.5">{new Date(o.date).toLocaleDateString()}</div>
                </td>
                <td className="p-4">
                  <div className="font-semibold text-slate-800">{o.deliveryZone}</div>
                  <div className="text-[10px] text-emerald-800 font-bold">{o.deliveryWindow}</div>
                </td>
                <td className="p-4 max-w-xs">
                  <div className="flex flex-wrap gap-1">
                    {o.items.map((it, idx) => (
                      <span key={idx} className="bg-slate-100 text-[10px] px-2 py-0.5 rounded text-slate-600 font-bold">
                        {(lang === 'bm' ? it.productName : (it.productNameEn || it.productName))} (x{it.quantity})
                      </span>
                    ))}
                  </div>
                </td>
                <td className="p-4 font-black text-slate-950">
                  RM {o.total.toFixed(2)}
                </td>
                <td className="p-4">
                  <OrderStatusBadge status={o.status} />
                </td>
                <td className="p-4 text-right">
                  <div className="flex gap-1.5 justify-end">
                    {role === 'supplier' && o.status === 'pending' && (
                      <button 
                        onClick={() => onUpdateOrder(o.id, { status: 'out_for_delivery' })}
                        className="text-[10px] bg-emerald-800 text-white font-extrabold px-2.5 py-1 rounded-lg shadow"
                      >
                        {lang === 'bm' ? 'Hantar Bekalan' : 'Dispatch Run'}
                      </button>
                    )}
                    {o.status === 'out_for_delivery' && (
                      <button 
                        onClick={() => onUpdateOrder(o.id, { status: 'delivered' })}
                        className="text-[10px] bg-orange-500 text-white font-extrabold px-2.5 py-1 rounded-lg shadow"
                      >
                        {lang === 'bm' ? 'Sahkan POD' : 'Record POD'}
                      </button>
                    )}
                    {o.status === 'delivered' && (
                      <button 
                        onClick={() => onRepeatOrder(o)}
                        className="text-[10px] bg-emerald-50 text-emerald-800 border border-emerald-100 font-extrabold px-2.5 py-1 rounded-lg hover:bg-emerald-100 transition-colors"
                      >
                        {t('repeatCycle')}
                      </button>
                    )}
                    {o.status === 'pending' && (
                      <button 
                        onClick={() => onCancelOrder(o.id)}
                        className="text-[10px] text-rose-600 hover:bg-rose-50 font-bold px-2 py-1 rounded-lg"
                      >
                        {lang === 'bm' ? 'Batal' : 'Cancel'}
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr>
                <td colSpan={6} className="p-8 text-center text-slate-400 font-medium">No order runs currently listed in this category.</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}


interface DeliveriesTabProps {
  deliveries: Delivery[];
  schedules: DeliverySchedule[];
  suppliers: Supplier[];
  role: string;
  supplierProfile: Supplier | null;
  onAdvanceDelivery: (id: string, status: string) => void;
  onAddSchedule: (data: any) => void;
}

export function DeliveriesTab({ deliveries, schedules, suppliers, role, supplierProfile, onAdvanceDelivery, onAddSchedule }: DeliveriesTabProps) {
  const [showAddSchedule, setShowAddSchedule] = useState(false);
  const [zone, setZone] = useState('Kota Bharu Central');
  const [windowTime, setWindowTime] = useState('06:00 AM - 07:30 AM');
  const [cutoff, setCutoff] = useState('09:00 PM');
  const { lang, t } = useContext(LanguageContext)!;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onAddSchedule({ zone, timeWindow: windowTime, cutoff });
    setShowAddSchedule(false);
  };

  return (
    <div className="space-y-6 max-w-6xl animate-fade-in font-sans">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h1 className="text-xl font-bold text-slate-900">{lang === 'bm' ? 'Logistik Kluster Laluan Sekolah' : 'Cluster Route Logistics'}</h1>
          <p className="text-xs text-slate-500 mt-1">
            {lang === 'bm' 
              ? 'Tingkatkan kecekapan penghantaran awal pagi melalui zon logistik jajahan.' 
              : 'Optimized early-morning driver dispatch windows.'}
          </p>
        </div>
        {role === 'admin' && (
          <button onClick={() => setShowAddSchedule(!showAddSchedule)} className="bg-emerald-800 text-white px-4 py-2 rounded-xl text-xs font-bold transition-all shadow">
            {lang === 'bm' ? 'Tambah Slot Logistik' : 'Add Logistics Slot'}
          </button>
        )}
      </div>

      {showAddSchedule && (
        <form onSubmit={handleSubmit} className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-md grid grid-cols-1 md:grid-cols-4 gap-4 animate-fade-in">
          <div>
            <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Zone Name</label>
            <input required type="text" value={zone} onChange={e => setZone(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700" />
          </div>
          <div>
            <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Time Window</label>
            <input required type="text" value={windowTime} onChange={e => setWindowTime(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700" />
          </div>
          <div>
            <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Cutoff Time</label>
            <input required type="text" value={cutoff} onChange={e => setCutoff(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700" />
          </div>
          <div className="flex items-end">
            <button type="submit" className="w-full py-2.5 bg-emerald-800 text-white font-extrabold text-xs rounded-xl uppercase shadow hover:bg-emerald-950">Publish Node</button>
          </div>
        </form>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {schedules.map(sch => (
          <div key={sch.id} className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-sm space-y-4">
            <div className="flex justify-between items-start">
              <div>
                <h3 className="font-extrabold text-slate-900 text-sm flex items-center gap-1.5">
                  <MapPin size={16} className="text-emerald-800" /> {lang === 'bm' ? sch.zone : (sch.zoneEn || sch.zone)}
                </h3>
                <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">{lang === 'bm' ? 'Laluan Awal Pagi' : 'Early Morning Routing'}</span>
              </div>
            </div>

            <div className="pt-4 border-t border-slate-100 grid grid-cols-2 gap-2 text-xs">
              <div>
                <span className="text-slate-400 block font-bold uppercase text-[9px]">{lang === 'bm' ? 'Tetingkap Sesi' : 'Delivery Window'}</span>
                <strong className="text-slate-800 font-extrabold">{sch.timeWindow}</strong>
              </div>
              <div>
                <span className="text-slate-400 block font-bold uppercase text-[9px]">{lang === 'bm' ? 'Had Masa Pembekal' : 'Supplier Cut-off'}</span>
                <strong className="text-orange-600 font-extrabold">{sch.cutoff}</strong>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm space-y-4">
        <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900 border-b pb-2">{lang === 'bm' ? 'Pemantauan Penghantar Aktif' : 'Active Dispatch Driver Monitors'}</h3>
        <div className="space-y-2.5">
          {deliveries.map(d => (
            <div key={d.id} className="border border-slate-100 p-3 rounded-xl bg-slate-50/50 flex justify-between items-center">
              <div>
                <strong className="text-xs text-slate-900 block">{d.driverName}</strong>
                <span className="text-[10px] text-slate-400">{lang === 'bm' ? 'Rujukan Tempahan' : 'Order Reference ID'}: {d.orderId}</span>
              </div>
              <div className="flex gap-2">
                <span className="text-[10px] bg-blue-100 text-blue-800 font-extrabold px-3 py-1 rounded-full uppercase">
                  {d.status}
                </span>
                {d.status !== 'delivered' && (
                  <button 
                    onClick={() => onAdvanceDelivery(d.id, 'delivered')}
                    className="text-[10px] bg-emerald-800 text-white font-bold px-3 py-1 rounded-lg"
                  >
                    {lang === 'bm' ? 'Sahkan Penghantaran' : 'Confirm Delivery'}
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}


interface RecurringTabProps {
  recurring: RecurringOrder[];
  buyerProfile: Buyer | null;
  suppliers: Supplier[];
  products: Product[];
  onToggle: (id: string, active: boolean) => void;
  onToggleAuto: (id: string, autoConfirm: boolean) => void;
  onDelete: (id: string) => void;
  onCreate: (data: any) => void;
  onRunNow: (rec: RecurringOrder) => void;
}

export function RecurringTab({ recurring, buyerProfile, suppliers, products, onToggle, onToggleAuto, onDelete, onCreate, onRunNow }: RecurringTabProps) {
  const [showAddForm, setShowAddForm] = useState(false);
  const [name, setName] = useState('');
  const [supplierId, setSupplierId] = useState('');
  const [dayOfWeek, setDayOfWeek] = useState('Monday');
  const { lang, t } = useContext(LanguageContext)!;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!buyerProfile) return;
    onCreate({
      buyerId: buyerProfile.id,
      supplierId,
      name,
      dayOfWeek,
      itemsJson: [],
      nextRunDate: new Date(Date.now() + 86400000 * 4).toISOString().split('T')[0],
      active: true,
      autoConfirm: true
    });
    setShowAddForm(false);
  };

  return (
    <div className="space-y-6 max-w-6xl animate-fade-in font-sans">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h1 className="text-xl font-bold text-slate-900">{lang === 'bm' ? 'Kitaran Stok Automatik Pintar' : 'Predictable Supply Cycles'}</h1>
          <p className="text-xs text-slate-500 mt-1">
            {lang === 'bm' 
              ? 'Automasi bekalan dapur kantin sekolah secara berkala mengikut jadual mingguan.' 
              : 'Automating school kitchen inventory runs on a fixed weekly rhythm.'}
          </p>
        </div>
        {buyerProfile && (
          <button onClick={() => setShowAddForm(!showAddForm)} className="bg-emerald-800 text-white px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow">
            <Plus size={14} /> {t('weeklyContractTitle')}
          </button>
        )}
      </div>

      {showAddForm && (
        <form onSubmit={handleSubmit} className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-md space-y-4 animate-fade-in">
          <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900">{t('weeklyContractDesc')}</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Schedule Name</label>
              <input required type="text" value={name} onChange={e => setName(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700" placeholder="e.g. Weekly Canteen Pack" />
            </div>
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Select Wholesaler</label>
              <select value={supplierId} onChange={e => setSupplierId(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700">
                <option value="">Select Wholesaler</option>
                {suppliers.map(s => <option key={s.id} value={s.id}>{s.companyName}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Execution Day</label>
              <select value={dayOfWeek} onChange={e => setDayOfWeek(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700">
                <option value="Monday">Monday</option>
                <option value="Wednesday">Wednesday</option>
                <option value="Friday">Friday</option>
              </select>
            </div>
          </div>
          <button type="submit" className="px-4 py-2 bg-emerald-800 text-white text-xs font-bold rounded-xl uppercase shadow hover:bg-emerald-950">Commit Contract Rule</button>
        </form>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {recurring.map(rec => {
          const supplier = suppliers.find(s => s.id === rec.supplierId);
          return (
            <div key={rec.id} className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex flex-col justify-between space-y-4">
              <div>
                <div className="flex justify-between items-center border-b pb-2">
                  <h3 className="font-extrabold text-slate-900 text-xs uppercase tracking-wider">{lang === 'bm' ? rec.name : (rec.nameEn || rec.name)}</h3>
                  <span className="text-[10px] text-slate-400 font-bold uppercase">{lang === 'bm' ? rec.dayOfWeek : (rec.dayOfWeekEn || rec.dayOfWeek)} Cycle</span>
                </div>

                <div className="mt-3 text-xs space-y-1">
                  <div>Wholesaler: <strong className="text-slate-800 font-extrabold">{supplier?.companyName}</strong></div>
                  <div>Next Scheduled Batch Run: <strong className="text-slate-800">{rec.nextRunDate}</strong></div>
                </div>

                <div className="mt-3 flex items-center gap-4">
                  <div className="flex items-center gap-1.5">
                    <input 
                      type="checkbox" 
                      checked={rec.active} 
                      onChange={e => onToggle(rec.id, e.target.checked)} 
                      id={"active-" + rec.id}
                      className="accent-emerald-800 cursor-pointer"
                    />
                    <label htmlFor={"active-" + rec.id} className="text-[10px] font-extrabold text-slate-500 uppercase cursor-pointer">Active System Rules</label>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <input 
                      type="checkbox" 
                      checked={rec.autoConfirm} 
                      onChange={e => onToggleAuto(rec.id, e.target.checked)} 
                      id={"auto-" + rec.id}
                      className="accent-emerald-800 cursor-pointer"
                    />
                    <label htmlFor={"auto-" + rec.id} className="text-[10px] font-extrabold text-slate-500 uppercase cursor-pointer">Auto Confirm</label>
                  </div>
                </div>
              </div>

              <div className="flex justify-between items-center pt-4 border-t border-slate-100">
                <button 
                  onClick={() => onDelete(rec.id)}
                  className="text-[10px] text-rose-600 hover:bg-rose-50 px-2.5 py-1 rounded"
                >
                  Delete
                </button>
                <button 
                  onClick={() => onRunNow(rec)}
                  className="text-[10px] bg-emerald-800 hover:bg-emerald-950 text-white font-extrabold px-3 py-1 rounded-lg shadow"
                >
                  Dispatch Run Now
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}


interface SuppliersTabProps {
  suppliers: Supplier[];
  reviews: Review[];
  buyerProfile: Buyer | null;
  role: string;
  favorites: { buyerId: string; supplierId: string }[];
  onToggleFavorite: (supplierId: string) => void;
}

export function SuppliersTab({ suppliers, reviews, buyerProfile, role, favorites, onToggleFavorite }: SuppliersTabProps) {
  const { lang, t } = useContext(LanguageContext)!;

  return (
    <div className="space-y-6 max-w-6xl animate-fade-in font-sans">
      <div>
        <h1 className="text-xl font-bold text-slate-900">{t('accSupTitle')}</h1>
        <p className="text-xs text-slate-500 mt-1">{t('accSupDesc')}</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {suppliers.map(sup => {
          const isFav = buyerProfile && favorites.some(f => f.buyerId === buyerProfile.id && f.supplierId === sup.id);
          const supReviews = reviews.filter(r => r.supplierId === sup.id);

          return (
            <div key={sup.id} className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-sm flex flex-col justify-between space-y-4">
              <div>
                <div className="flex justify-between items-start">
                  <h3 className="font-extrabold text-slate-900 text-sm leading-tight">{sup.companyName}</h3>
                  {buyerProfile && (
                    <button onClick={() => onToggleFavorite(sup.id)} className="text-rose-500 hover:text-rose-700">
                      <Heart className={`w-5 h-5 ${isFav ? 'fill-rose-500 text-rose-500' : 'text-slate-300'}`} />
                    </button>
                  )}
                </div>
                <span className="text-[10px] text-slate-400 font-bold uppercase block mt-1">Zone: {sup.zone}</span>

                <div className="pt-3 flex gap-4 text-[11px] text-slate-600">
                  <div>{t('minOrderValue')}: <strong className="text-slate-900 font-bold">RM {sup.minimumOrderValue}</strong></div>
                  <div>Status: <span className="text-emerald-700 font-extrabold uppercase text-[10px]">{t('statusBadgeAcc')}</span></div>
                </div>
              </div>

              {supReviews.length > 0 && (
                <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 text-[10px] text-slate-500 leading-relaxed italic">
                  &ldquo;{lang === 'bm' ? supReviews[0].comment : (supReviews[0].commentEn || supReviews[0].comment)}&rdquo; <span className="block font-bold text-slate-700 mt-1 not-italic">— {supReviews[0].author}</span>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}


interface ComplianceTabProps {
  rules: ComplianceRule[];
  products: Product[];
  analytics: AnalyticsData | null;
  role: string;
  onToggleRule: (id: string, active: boolean) => void;
  onCreateRule: (data: any) => void;
  onDeleteRule: (id: string) => void;
  onRescan: () => void;
}

export function ComplianceTab({ rules, products, analytics, role, onToggleRule, onCreateRule, onDeleteRule, onRescan }: ComplianceTabProps) {
  const { showToast } = useToast();
  const [showAddForm, setShowAddForm] = useState(false);
  const [ruleName, setRuleName] = useState('');
  const [ruleCode, setRuleCode] = useState('');
  const [description, setDescription] = useState('');
  const { lang, t } = useContext(LanguageContext)!;

  // Structured AI Menu Audit states
  const [menuInput, setMenuInput] = useState('');
  const [isAuditing, setIsAuditing] = useState(false);
  const [auditResult, setAuditResult] = useState<any | null>(null);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onCreateRule({
      name: ruleName,
      code: ruleCode,
      type: 'blacklist',
      active: true,
      description
    });
    setShowAddForm(false);
    setRuleName('');
    setRuleCode('');
    setDescription('');
  };

  const handleDeepAiAudit = async () => {
    if (!menuInput.trim()) return;
    setIsAuditing(true);
    setAuditResult(null);

    const catalogSample = products.slice(0, 8).map(p => `${p.name} (${p.category}) - Sugar: ${p.sugar}g, Sodium: ${p.sodium}mg`).join('; ');
    const userQuery = `Audit the following school draft weekly menu: "${menuInput}". Check if it aligns with S_max <= 10g, Na_max <= 400mg, F_max <= 10g thresholds and stays free of KPM's 13 prohibited food types. Here is our available compliant wholesaler catalog: ${catalogSample}. Output response strictly in language choice: ${lang === 'bm' ? 'Bahasa Melayu' : 'English'}`;
    const systemPrompt = 'You are the ultimate KPM Canteen Compliance Auditor. You evaluate draft menus, score them out of 100, flag violations, and suggest exact healthy substitutes from the provided catalog sample. Return your audit strictly as a structured JSON object matching the defined schema.';

    const auditSchema = {
      type: "OBJECT",
      properties: {
        score: { type: "NUMBER", description: "Compliance rating out of 100" },
        critique: { type: "STRING", description: "Detailed summary critique of the draft menu" },
        violations: {
          type: "ARRAY",
          items: {
            type: "OBJECT",
            properties: {
              itemName: { type: "STRING" },
              reason: { type: "STRING" }
            },
            required: ["itemName", "reason"]
          }
        },
        alternatives: {
          type: "ARRAY",
          items: {
            type: "OBJECT",
            properties: {
              flaggedItem: { type: "STRING" },
              vettedSubstitute: { type: "STRING" },
              benefit: { type: "STRING" }
            },
            required: ["flaggedItem", "vettedSubstitute", "benefit"]
          }
        }
      },
      required: ["score", "critique", "violations", "alternatives"]
    };

    try {
      const data = await callGeminiStructured(userQuery, systemPrompt, auditSchema);
      setAuditResult(data);
      showToast(
        lang === 'bm' ? "Laporan Penuh Sedia" : "Deep AI Audit Completed", 
        lang === 'bm' ? "Analisis pematuhan dasar siap dikompilasi." : "Interactive menu report compiled successfully!"
      );
    } catch (err) {
      console.error(err);
      showToast(
        lang === 'bm' ? "Rangka Kerja AI Terganggu" : "AI Sandbox Handshake Failed", 
        lang === 'bm' ? "Rangkaian sandbox tidak dapat diproses." : "Handshake interrupted on LLM backend.", 
        "error"
      );
    } finally {
      setIsAuditing(false);
    }
  };

  return (
    <div className="space-y-6 max-w-6xl animate-fade-in font-sans">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h1 className="text-xl font-bold text-slate-900">{t('sandboxTitle')}</h1>
          <p className="text-xs text-slate-500 mt-1">{t('sandboxDesc')}</p>
        </div>
        <div className="flex gap-2">
          <button onClick={onRescan} className="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 border">
            <RefreshCw size={14} /> {lang === 'bm' ? 'Segarkan Saringan' : 'Trigger Catalog Scan'}
          </button>
          {role === 'admin' && (
            <button onClick={() => setShowAddForm(!showAddForm)} className="bg-orange-500 text-white px-4 py-2 rounded-xl text-xs font-bold transition-all shadow">
              Add Constraint Rule
            </button>
          )}
        </div>
      </div>

      {showAddForm && (
        <form onSubmit={handleSubmit} className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-md space-y-4 animate-fade-in">
          <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900">Configure Compliance Constraint</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Rule Name</label>
              <input required type="text" value={ruleName} onChange={e => setRuleName(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-750" placeholder="KPM Maximum Sugar Rule" />
            </div>
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">System Code Key</label>
              <input required type="text" value={ruleCode} onChange={e => setRuleCode(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-750" placeholder="S_MAX_10G" />
            </div>
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Description</label>
              <input required type="text" value={description} onChange={e => setDescription(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-750" />
            </div>
          </div>
          <button type="submit" className="px-4 py-2 bg-emerald-800 text-white text-xs font-bold rounded-xl uppercase shadow hover:bg-emerald-950">Publish Constraint</button>
        </form>
      )}

      <div className="bg-white p-5 rounded-3xl border border-slate-200 shadow-sm grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="md:col-span-1 space-y-4">
          <div>
            <h3 className="font-extrabold text-xs uppercase tracking-wider text-emerald-800 flex items-center gap-1.5">
              <Sparkles className="w-3.5 h-3.5 text-orange-500 animate-pulse" />
              <span>{t('auditSandboxTitle')}</span>
            </h3>
            <p className="text-[11px] text-slate-500 mt-1">
              {lang === 'bm' 
                ? 'Semak pematuhan draf menu mingguan anda secara langsung melalui enjin kecerdasan buatan KPM.' 
                : 'Verify your custom weekly menu layout directly with the Gemini policy engine before dispatching orders.'}
            </p>
          </div>

          <textarea 
            rows={5}
            value={menuInput}
            onChange={e => setMenuInput(e.target.value)}
            placeholder={lang === 'bm' ? "Isnin: Nugget ayam goreng berlemak bersama teh o ais manis. Selasa: Sandwic gandum penuh..." : "Monday: Deep fried nuggets with high sugar sweet tea. Tuesday: Wholemeal sandwiches with low sugar water..."}
            className="w-full p-3 border border-slate-200 rounded-xl text-xs bg-slate-50 focus:bg-white focus:ring-2 focus:ring-emerald-700 outline-none transition-all resize-none"
          />

          <button 
            type="button"
            disabled={isAuditing}
            onClick={handleDeepAiAudit}
            className="w-full py-2.5 bg-emerald-800 hover:bg-emerald-950 disabled:bg-slate-300 text-white rounded-xl text-xs font-bold uppercase tracking-wider transition-all flex items-center justify-center gap-2 shadow"
          >
            {isAuditing ? (
              <>
                <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                <span>{t('auditingMenu')}</span>
              </>
            ) : (
              <>
                <Sparkle className="w-3.5 h-3.5 text-orange-400 animate-pulse" />
                <span>{lang === 'bm' ? 'Audit Menu AI KPM' : 'Run Deep AI Health Audit'}</span>
              </>
            )}
          </button>
        </div>

        <div className="md:col-span-2 border-t md:border-t-0 md:border-l border-slate-100 pt-4 md:pt-0 md:pl-6">
          {auditResult ? (
            <div className="space-y-4 modal-pop">
              <div className="flex justify-between items-center pb-2 border-b">
                <span className="text-[10px] text-slate-400 font-extrabold uppercase">{lang === 'bm' ? 'Maklum Balas Berstruktur AI' : 'Generated Structured Feedback'}</span>
                <span className={`text-xs font-black px-2.5 py-1 rounded-lg ${
                  auditResult.score >= 80 ? 'bg-emerald-100 text-emerald-800' : auditResult.score >= 50 ? 'bg-amber-100 text-amber-800' : 'bg-rose-100 text-rose-800'
                }`}>
                  KPM Score: {auditResult.score}/100
                </span>
              </div>

              <div>
                <strong className="text-xs text-slate-900 block">{lang === 'bm' ? 'Ringkasan Kritikan AI:' : 'AI Critique Summary:'}</strong>
                <p className="text-[11px] text-slate-600 mt-0.5 leading-relaxed font-medium">{auditResult.critique}</p>
              </div>

              {auditResult.violations.length > 0 && (
                <div>
                  <strong className="text-[10px] uppercase font-bold text-rose-600 block tracking-wider">{lang === 'bm' ? 'Pelanggaran Dasar Dikesan:' : 'Flagged Violations:'}</strong>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-2 mt-1">
                    {auditResult.violations.map((v: any, idx: number) => (
                      <div key={idx} className="bg-rose-50 border border-rose-100 p-2.5 rounded-xl text-[10px] text-rose-900 leading-snug">
                        <strong className="block font-black">{v.itemName}</strong>
                        {v.reason}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {auditResult.alternatives.length > 0 && (
                <div>
                  <strong className="text-[10px] uppercase font-bold text-emerald-800 block tracking-wider">{lang === 'bm' ? 'Cadangan Penggantian Bahan Patuh:' : 'Vetted Substitute Suggestions:'}</strong>
                  <div className="space-y-2 mt-1">
                    {auditResult.alternatives.map((alt: any, idx: number) => (
                      <div key={idx} className="bg-emerald-50/50 border border-emerald-100 p-2 rounded-xl text-[10px] text-emerald-950 flex justify-between items-center gap-4">
                        <div>
                          <span className="text-slate-400 line-through block">{alt.flaggedItem}</span>
                          <span className="font-extrabold text-emerald-800">{lang === 'bm' ? 'Guna Bahan Patuh:' : 'Use Substitute:'} {alt.vettedSubstitute}</span>
                        </div>
                        <span className="text-[9px] text-slate-500 italic block text-right max-w-xs">{alt.benefit}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="h-full flex flex-col items-center justify-center text-center p-8 text-slate-400">
              <ShieldCheck className="w-12 h-12 text-slate-200 mb-2" />
              <strong className="text-xs text-slate-600">{t('auditResultEmpty')}</strong>
              <p className="text-[10px] max-w-sm mt-1 leading-normal">
                {t('auditResultDesc')}
              </p>
            </div>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {rules.map(rule => (
          <div key={rule.id} className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex flex-col justify-between space-y-4">
            <div>
              <div className="flex justify-between items-center border-b pb-2">
                <h3 className="font-extrabold text-slate-900 text-xs uppercase tracking-wider">{lang === 'bm' ? rule.name : rule.nameEn}</h3>
                <span className="text-[10px] bg-slate-100 text-slate-500 font-extrabold px-2 py-0.5 rounded uppercase">{rule.code}</span>
              </div>
              <p className="text-xs text-slate-500 mt-2.5 leading-relaxed">{lang === 'bm' ? rule.description : rule.descriptionEn}</p>
            </div>

            <div className="flex justify-between items-center pt-4 border-t border-slate-100">
              <div className="flex items-center gap-1.5">
                <input 
                  type="checkbox" 
                  checked={rule.active} 
                  onChange={e => onToggleRule(rule.id, e.target.checked)} 
                  id={"rule-" + rule.id}
                  className="accent-emerald-800 cursor-pointer"
                />
                <label htmlFor={"rule-" + rule.id} className="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider cursor-pointer">Rule State</label>
              </div>
              {role === 'admin' && (
                <button 
                  onClick={() => onDeleteRule(rule.id)}
                  className="text-[10px] text-rose-600 hover:bg-rose-50 px-2 py-1 rounded"
                >
                  Remove Rule
                </button>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}


interface ChatsTabProps {
  messages: Message[];
  buyers: Buyer[];
  suppliers: Supplier[];
  currentUser: User;
  buyerProfile: Buyer | null;
  supplierProfile: Supplier | null;
  role: string;
  onSend: (data: any) => void;
}

export function ChatsTab({ messages, buyers, suppliers, currentUser, buyerProfile, supplierProfile, role, onSend }: ChatsTabProps) {
  const { showToast } = useToast();
  const [selectedRecipientId, setSelectedRecipientId] = useState('');
  const [text, setText] = useState('');
  const [isAiLoading, setIsAiLoading] = useState(false);
  const { lang, t } = useContext(LanguageContext)!;

  const availableContacts = useMemo(() => {
    if (role === 'buyer') {
      return suppliers.map(s => ({ id: s.userId, name: s.companyName }));
    }
    return buyers.map(b => ({ id: b.userId, name: b.businessName }));
  }, [role, buyers, suppliers]);

  useEffect(() => {
    if (availableContacts.length > 0 && !selectedRecipientId) {
      setSelectedRecipientId(availableContacts[0].id);
    }
  }, [availableContacts, selectedRecipientId]);

  const conversation = useMemo(() => {
    return messages.filter(m => 
      (m.senderId === currentUser.id && m.recipientId === selectedRecipientId) ||
      (m.senderId === selectedRecipientId && m.recipientId === currentUser.id)
    );
  }, [messages, currentUser.id, selectedRecipientId]);

  const handleSend = (e: React.FormEvent) => {
    e.preventDefault();
    if (!text.trim()) return;

    onSend({
      senderId: currentUser.id,
      senderName: currentUser.name,
      recipientId: selectedRecipientId,
      text,
      timestamp: new Date().toISOString()
    });
    setText('');
  };

  const handleGeminiCopilot = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!text.trim()) return;
    setIsAiLoading(true);

    const userMessageText = text;
    setText('');

    onSend({
      senderId: currentUser.id,
      senderName: currentUser.name,
      recipientId: 'gemini-copilot',
      text: userMessageText,
      timestamp: new Date().toISOString()
    });

    try {
      const systemPrompt = `You are the ultimate KPM Canteen Compliance Copilot. Your response must be authoritative, highly structured, and written in natural professional ${lang === 'bm' ? 'Bahasa Melayu' : 'English'}. Consult up-to-date guidelines on nutrition rules, sugar limits, or the 13 banned classes of foods. Keep it under 150 words.`;
      
      const response = await callGeminiText(userMessageText, systemPrompt, true);
      
      onSend({
        senderId: 'gemini-copilot',
        senderName: 'Gemini KPM Copilot ✨',
        recipientId: currentUser.id,
        text: response.text,
        timestamp: new Date().toISOString(),
        sources: response.sources
      });
      showToast(
        lang === 'bm' ? "Carian Dasar Disegerakkan" : "Compliance Query Grounded", 
        lang === 'bm' ? "Jawapan dasar langsung berjaya diperoleh melalui Google Search." : "Successfully synchronized live policy answers via Google Search!"
      );
    } catch (err) {
      console.error(err);
      onSend({
        senderId: 'gemini-copilot',
        senderName: 'Gemini KPM Copilot ✨',
        recipientId: currentUser.id,
        text: lang === 'bm' 
          ? "Maaf, ralat rangkaian dikesan ketika menghubungi policy sandbox. Had standard dikekalkan: S_max 10g, Na_max 400mg, F_max 10g per 100g."
          : "Sorry, network exceptions occurred. Keeping standard thresholds: S_max 10g, Na_max 400mg, F_max 10g.",
        timestamp: new Date().toISOString()
      });
      showToast("Handshake Timeout", "Could not establish secure endpoint callback.", "error");
    } finally {
      setIsAiLoading(false);
    }
  };

  return (
    <div className="bg-white rounded-2xl border border-slate-200/80 shadow-sm overflow-hidden h-[550px] flex max-w-6xl w-full animate-fade-in font-sans">
      <div className="w-1/3 border-r border-slate-200/60 p-4 space-y-2 overflow-y-auto bg-slate-50/50">
        <h3 className="text-[10px] uppercase font-bold tracking-widest text-slate-400 block mb-3">Active Channels</h3>
        <div className="space-y-1">
          {availableContacts.map(contact => (
            <button
              key={contact.id}
              onClick={() => setSelectedRecipientId(contact.id)}
              className={`w-full text-left p-3 rounded-xl transition-all text-xs font-bold ${
                selectedRecipientId === contact.id ? 'bg-emerald-50 text-emerald-950 border border-emerald-100' : 'text-slate-600 hover:bg-slate-50'
              }`}
            >
              {contact.name}
            </button>
          ))}
          <button
            onClick={() => setSelectedRecipientId('gemini-copilot')}
            className={`w-full text-left p-3 rounded-xl transition-all text-xs font-bold flex items-center justify-between ${
              selectedRecipientId === 'gemini-copilot' ? 'bg-orange-50 text-orange-950 border border-orange-100' : 'text-slate-600 hover:bg-slate-50'
            }`}
          >
            <div className="flex items-center gap-1.5">
              <Sparkles className="w-3.5 h-3.5 text-orange-500 animate-pulse" />
              <span>Gemini KPM Copilot</span>
            </div>
            <span className="text-[8px] bg-orange-200 text-orange-900 font-extrabold px-1.5 py-0.5 rounded-full uppercase tracking-widest">GROUNDED</span>
          </button>
        </div>
      </div>

      <div className="w-2/3 flex flex-col justify-between">
        <div className="p-4 border-b border-slate-200/60 flex justify-between items-center bg-slate-50/50">
          <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900">
            {selectedRecipientId === 'gemini-copilot' ? 'Gemini KPM Copilot ✨' : availableContacts.find(c => c.id === selectedRecipientId)?.name || 'Direct Channel'}
          </h3>
        </div>

        <div className="flex-1 p-4 overflow-y-auto space-y-3 bg-slate-50/20">
          {(selectedRecipientId === 'gemini-copilot' 
            ? messages.filter(m => (m.recipientId === currentUser.id && m.senderId === 'gemini-copilot') || (m.senderId === currentUser.id && m.recipientId === 'gemini-copilot'))
            : conversation
          ).map(msg => {
            const isMe = msg.senderId === currentUser.id;
            return (
              <div key={msg.id} className={`flex ${isMe ? 'justify-end' : 'justify-start'}`}>
                <div className={`p-3 rounded-2xl max-w-md text-xs leading-relaxed ${
                  isMe ? 'bg-emerald-800 text-white rounded-tr-none font-medium' : 'bg-white border text-slate-800 rounded-tl-none border-slate-200/60 shadow-sm'
                }`}>
                  <span className="block font-black text-[9px] uppercase tracking-wider mb-1 opacity-80">{msg.senderName}</span>
                  <div>{msg.text}</div>
                  
                  {msg.sources && msg.sources.length > 0 && (
                    <div className="mt-3 pt-2 border-t border-slate-100 space-y-1.5">
                      <span className="text-[9px] uppercase font-bold text-slate-400 block tracking-wider">References:</span>
                      {msg.sources.map((src, sIdx) => (
                        <a 
                          key={sIdx} 
                          href={src.uri} 
                          target="_blank" 
                          rel="noreferrer"
                          className="flex items-center gap-1 text-[10px] text-emerald-800 font-extrabold hover:underline"
                        >
                          <ExternalLink className="w-3 h-3" />
                          <span className="truncate">{src.title}</span>
                        </a>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
          {isAiLoading && (
            <div className="flex justify-start">
              <div className="p-3 rounded-2xl max-w-md text-xs bg-orange-50 text-orange-950 border border-orange-100 rounded-tl-none shadow-sm flex items-center gap-2 font-bold animate-pulse">
                <RefreshCw size={12} className="animate-spin" /> {lang === 'bm' ? 'Copilot KPM sedang meninjau indeks dasar...' : 'KPM Copilot is querying live policy indexes...'}
              </div>
            </div>
          )}
        </div>

        <form onSubmit={selectedRecipientId === 'gemini-copilot' ? handleGeminiCopilot : handleSend} className="p-4 border-t border-slate-200/60 flex gap-2 bg-white">
          <input 
            type="text" 
            placeholder={selectedRecipientId === 'gemini-copilot' ? (lang === 'bm' ? "Tanya: Adakah minuman gas dilarang di bawah dasar KPM Kelantan?..." : "Ask: Are carbonated soft drinks prohibited under KPM rules?...") : "Send invoice update..."}
            value={text}
            onChange={e => setText(e.target.value)}
            className="flex-1 p-3 border border-slate-200 rounded-xl text-xs outline-none focus:border-emerald-700 bg-slate-50/50 text-slate-800"
          />
          {selectedRecipientId === 'gemini-copilot' ? (
            <button 
              type="submit" 
              disabled={isAiLoading}
              className="bg-orange-500 hover:bg-orange-600 text-white px-5 rounded-xl text-xs font-extrabold uppercase tracking-wider flex items-center gap-1.5 shrink-0 transition-colors shadow"
            >
              <Sparkles className="w-4 h-4" /> {lang === 'bm' ? 'Cari AI' : 'AI Search'}
            </button>
          ) : (
            <button 
              type="submit" 
              className="bg-emerald-800 hover:bg-emerald-950 text-white px-5 rounded-xl text-xs font-extrabold uppercase tracking-wider shrink-0 transition-colors shadow"
            >
              Send
            </button>
          )}
        </form>
      </div>
    </div>
  );
}


interface AnalyticsTabProps {
  analytics: AnalyticsData | null;
  orders: Order[];
  role: string;
  buyerProfile: Buyer | null;
  supplierProfile: Supplier | null;
  suppliers: Supplier[];
}

export function AnalyticsTab({ analytics, orders, role, buyerProfile, supplierProfile, suppliers }: AnalyticsTabProps) {
  const { lang, t } = useContext(LanguageContext)!;

  return (
    <div className="space-y-6 max-w-6xl animate-fade-in font-sans">
      <div>
        <h1 className="text-xl font-bold text-slate-900">{lang === 'bm' ? 'Analisis Nutrisi & Tadbir Urus Jajahan' : 'Governance & Micro-nutrient Analytics'}</h1>
        <p className="text-xs text-slate-500 mt-1">
          {lang === 'bm' 
            ? 'Laporan pemantauan kesihatan kantin jajahan Kelantan berdasarkan transaksi.' 
            : 'District health monitoring reports based on platform purchases.'}
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-sm space-y-4">
          <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900 border-b pb-2">{lang === 'bm' ? 'Skor Pematuhan Sistem' : 'Compliance Scoring Sandbox'}</h3>
          <div className="flex flex-col items-center justify-center py-6 text-center">
            <div className="w-24 h-24 rounded-full border-8 border-emerald-500 flex items-center justify-center text-2xl font-black text-slate-900 shadow-inner">
              94%
            </div>
            <span className="text-xs font-extrabold text-emerald-800 uppercase tracking-widest mt-4">{lang === 'bm' ? 'Kadar Lulus Peringkat Negeri' : 'State Level Approved'}</span>
            <p className="text-[10px] text-slate-400 mt-1 max-w-xs leading-normal">Evaluated daily across 15 active school canteens.</p>
          </div>
        </div>

        <div className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-sm lg:col-span-2 space-y-4">
          <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900 border-b pb-2">{lang === 'bm' ? 'Purata Ambilan Nutrisi Pelajar' : 'Average Micro-Nutrient Intake Trends'}</h3>
          
          <div className="space-y-4 pt-2">
            <div>
              <div className="flex justify-between text-xs font-extrabold text-slate-700 mb-1">
                <span>{lang === 'bm' ? 'Purata Gula Semasa' : 'Sugar Intake (Average)'}</span>
                <span className="text-emerald-700">3.5g / serving</span>
              </div>
              <div className="w-full bg-slate-100 rounded-full h-2.5">
                <div className="bg-emerald-500 h-2.5 rounded-full" style={{ width: '35%' }}></div>
              </div>
            </div>

            <div>
              <div className="flex justify-between text-xs font-extrabold text-slate-700 mb-1">
                <span>{lang === 'bm' ? 'Purata Natrium Semasa' : 'Sodium Intake (Average)'}</span>
                <span className="text-amber-700">220mg / serving</span>
              </div>
              <div className="w-full bg-slate-100 rounded-full h-2.5">
                <div className="bg-amber-500 h-2.5 rounded-full" style={{ width: '55%' }}></div>
              </div>
            </div>

            <div>
              <div className="flex justify-between text-xs font-extrabold text-slate-700 mb-1">
                <span>{lang === 'bm' ? 'Purata Lemak/Lipid Semasa' : 'Trans-Fat / Lipid (Average)'}</span>
                <span className="text-emerald-700">2.1g / serving</span>
              </div>
              <div className="w-full bg-slate-100 rounded-full h-2.5">
                <div className="bg-emerald-500 h-2.5 rounded-full" style={{ width: '21%' }}></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}


interface AdminTabProps {
  analytics: AnalyticsData | null;
  suppliers: Supplier[];
  buyers: Buyer[];
  orders: Order[];
  users: User[];
  onUpdateSupplier: (id: string, patch: Record<string, any>) => void;
  onBroadcast: (title: string, body: string, targetRole: string) => void;
}

export function AdminTab({ analytics, suppliers, buyers, orders, users, onUpdateSupplier, onBroadcast }: AdminTabProps) {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [target, setTarget] = useState('all');
  const { lang, t } = useContext(LanguageContext)!;

  const handleBroadcast = (e: React.FormEvent) => {
    e.preventDefault();
    onBroadcast(title, body, target);
    setTitle('');
    setBody('');
  };

  return (
    <div className="space-y-6 max-w-6xl animate-fade-in font-sans">
      <div>
        <h1 className="text-xl font-bold text-slate-900">{lang === 'bm' ? 'Hab Pentadbir Tadbir Urus Platform' : 'Platform Governance Admin Hub'}</h1>
        <p className="text-xs text-slate-500 mt-1">
          {lang === 'bm' 
            ? 'Sahkan pendaftaran pemborong tempatan dan lancarkan pengumuman terus.' 
            : 'Authorize Wholesalers and dispatch WhatsApp system-wide announcements.'}
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-sm lg:col-span-2 space-y-4">
          <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900 border-b pb-2">{lang === 'bm' ? 'Kelulusan Akreditasi Pemborong' : 'Supplier Accreditation Verification'}</h3>
          <div className="space-y-2.5">
            {suppliers.map(sup => (
              <div key={sup.id} className="border border-slate-100 p-3.5 rounded-2xl bg-slate-50 flex justify-between items-center">
                <div>
                  <strong className="text-xs text-slate-950 font-extrabold">{sup.companyName}</strong>
                  <span className="text-[10px] text-slate-400 block mt-0.5">Jajahan Zone: {sup.zone}</span>
                </div>
                <div className="flex gap-1.5">
                  <span className="text-[10px] bg-emerald-100 text-emerald-800 font-bold px-3 py-1 rounded-full uppercase">
                    {sup.verificationStatus}
                  </span>
                  {sup.verificationStatus === 'pending' && (
                    <button 
                      onClick={() => onUpdateSupplier(sup.id, { verificationStatus: 'approved' })}
                      className="text-[10px] bg-emerald-800 text-white font-bold px-3 py-1 rounded-lg shadow hover:bg-emerald-950 transition-colors"
                    >
                      Approve
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-sm space-y-4">
          <h3 className="font-extrabold text-xs uppercase tracking-wider text-slate-900 border-b pb-2">{lang === 'bm' ? 'Penyebaran Mesej & Notifikasi' : 'WhatsApp & Notification Broadcast'}</h3>
          
          <form onSubmit={handleBroadcast} className="space-y-3">
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase mb-1">Broad Target Role</label>
              <select value={target} onChange={e => setTarget(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700">
                <option value="all">All Registered Accounts</option>
                <option value="buyer">Canteen Operators Only</option>
                <option value="supplier">Suppliers Only</option>
              </select>
            </div>
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase mb-1">Title</label>
              <input required type="text" value={title} onChange={e => setTitle(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700" placeholder="KPM Compliance Policy Update v2" />
            </div>
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase mb-1">Broadcast Content</label>
              <textarea required value={body} onChange={e => setBody(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 h-24 outline-none text-slate-800 focus:ring-2 focus:ring-emerald-700" placeholder="All frozen poultry categories will enforce Na_max 400mg per 100g starting next recess window..." />
            </div>
            <button type="submit" className="w-full py-2.5 bg-emerald-800 text-white font-bold text-xs rounded-xl uppercase shadow hover:bg-emerald-950 transition-colors">Dispatch Broadcast Channel</button>
          </form>
        </div>
      </div>
    </div>
  );
}


export function GcpDeckTab() {
  const [activeSlide, setActiveSlide] = useState(0);
  const { lang, t } = useContext(LanguageContext)!;

  const slides = [
    {
      title: "Document 8: Compliance Engine v2",
      titleBm: "Dokumen 8: Enjin Pematuhan v2",
      bullets: [
        "Enforces KPM and KKM school nutrition guidelines automatically.",
        "Strictly screens out KPM's 13 Prohibited Categories (instant ramen, high-caffeine energy sodas).",
        "Calculates dynamic nutritional compliance based on S_max <= 10g, Na_max <= 400mg, F_max <= 10g thresholds.",
        "Generates dynamic Canteen Menu Compliance Rating before purchase confirmation."
      ],
      bulletsBm: [
        "Menguatkuasakan dasar nutrisi sekolah KPM dan KKM secara automatik di peringkat checkout.",
        "Menyaring keluar 13 Kategori Dilarang KPM secara mandatori (mi segera, air tin bergas, dll).",
        "Mengira kesesuaian mengikut formula dinamik: S_max <= 10g, Na_max <= 400mg, F_max <= 10g.",
        "Menjana Gred Gizi Menu Kantin sebelum pesanan dapat disahkan."
      ]
    },
    {
      title: "Document 9: Supplier Playbook & Cut-Offs",
      titleBm: "Dokumen 9: Buku Panduan & Had Sesi Pembekal",
      bullets: [
        "Enforces pre-recess daily order collection for same-day logistics routing.",
        "Standard platform order cut-off threshold defined at 2:00 PM daily for early-morning next-day drops.",
        "JAKIM Halal credentialing pipeline hardcoded into Wholesaler listing modules.",
        "Provides predictable, grouped demand models to suppliers to scale raw ingredient acquisition."
      ],
      bulletsBm: [
        "Mengumpulkan pesanan kantin harian bagi menyusun laluan logistik awal pagi.",
        "Menetapkan had masa pesanan standard pada jam 2:00 Petang untuk penghantaran esok pagi.",
        "Saringan sijil Halal JAKIM diwajibkan semasa pendaftaran katalog pemborong.",
        "Memberi unjuran permintaan yang stabil kepada pemborong untuk bekalan bahan mentah."
      ]
    },
    {
      title: "Document 20: Liquidity & Cold-Start",
      titleBm: "Dokumen 20: Kitaran Kecairan Pasaran",
      bullets: [
        "Overcomes double-sided marketplace bottlenecks using lock-in anchor school commitments.",
        "Guarantees consolidated minimum daily transaction volumes (MDV) to participating certified suppliers.",
        "Packages raw items into highly standard Healthy Bento and Wholemeal Sandwich bundles.",
        "Eliminated transport margin overheads using short-radius routing hubs."
      ],
      bulletsBm: [
        "Mengatasi masalah cold-start pasaran dua-hala menggunakan komitmen sekolah anchor.",
        "Menjamin jumlah nilai transaksi harian minimum (MDV) kepada pembekal terpilih.",
        "Menyediakan Pakej Bento Sihat dan Sandwic Gandum Penuh sebagai SKU standard di pasaran.",
        "Mengurangkan kos pengangkutan menggunakan hab logistik radius dekat."
      ]
    },
    {
      title: "Document 21: Sustainability & Financial ESG",
      titleBm: "Dokumen 21: Kelestarian & Kewangan ESG",
      bullets: [
        "Transaction Commissions: Stable 5%-8% take-rate on every digital school procurement transaction.",
        "Wholesaler Enterprise SaaS Subscriptions: RM200 - RM500 per month for logistics routing manifests.",
        "District Health Governance Licensing: Dedicated portal integrations for health ministry officers."
      ],
      bulletsBm: [
        "Komisen Transaksi: Caj stabil 5%-8% bagi setiap transaksi perolehan digital kantin.",
        "Langganan SaaS Pemborong: RM200 - RM500 sebulan bagi akses manifest pengedaran optimum.",
        "Pelesenan Tadbir Urus Daerah: Integrasi portal khas untuk pemantau kesihatan kementerian."
      ]
    }
  ];

  return (
    <div className="space-y-6 max-w-4xl animate-fade-in text-white font-sans">
      <div className="bg-emerald-950 p-6 rounded-3xl border border-emerald-900/40 shadow-xl space-y-4">
        <div className="flex justify-between items-center border-b border-emerald-900 pb-3">
          <div>
            <span className="text-[10px] bg-emerald-900 text-orange-400 font-extrabold px-3 py-1 rounded-full uppercase tracking-wider">Strategic Category Definition</span>
            <h1 className="text-xl font-bold mt-1">{t('strategyDeck')}</h1>
          </div>
          <span className="text-xs font-bold text-emerald-300">{t('slideTitle')} {activeSlide + 1} of {slides.length}</span>
        </div>

        <div className="bg-emerald-900/40 border border-emerald-900 p-6 rounded-2xl min-h-[220px] flex flex-col justify-between">
          <div className="space-y-3">
            <h2 className="text-lg font-extrabold text-orange-400 uppercase tracking-wide">
              {lang === 'bm' ? slides[activeSlide].titleBm : slides[activeSlide].title}
            </h2>
            <ul className="space-y-2.5 text-xs text-emerald-100 leading-relaxed pl-4 list-disc">
              {(lang === 'bm' ? slides[activeSlide].bulletsBm : slides[activeSlide].bullets).map((b, idx) => <li key={idx}>{b}</li>)}
            </ul>
          </div>

          <div className="flex gap-1.5 mt-6 justify-end">
            <button 
              disabled={activeSlide === 0} 
              onClick={() => setActiveSlide(prev => prev - 1)}
              className="px-4 py-2 bg-emerald-800 hover:bg-emerald-950 disabled:opacity-40 rounded-xl text-xs font-bold transition-all shadow"
            >
              Prev Slide
            </button>
            <button 
              disabled={activeSlide === slides.length - 1} 
              onClick={() => setActiveSlide(prev => prev + 1)}
              className="px-4 py-2 bg-emerald-800 hover:bg-emerald-950 disabled:opacity-40 rounded-xl text-xs font-bold transition-all shadow"
            >
              Next Slide
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}


interface ProductModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (data: any) => void;
  product: Product | null;
  suppliers: Supplier[];
  defaultSupplierId?: string;
}

export function ProductModal({ isOpen, onClose, onSave, product, suppliers, defaultSupplierId }: ProductModalProps) {
  const [name, setName] = useState('');
  const [category, setCategory] = useState('Chicken');
  const [price, setPrice] = useState('');
  const [moq, setMoq] = useState(5);
  const [stock, setStock] = useState(100);
  const [sugar, setSugar] = useState(0);
  const [sodium, setSodium] = useState(100);
  const [fat, setFat] = useState(2);
  const [isBannedType, setIsBannedType] = useState(false);
  const [bannedCategory, setBannedCategory] = useState('');

  useEffect(() => {
    if (product) {
      setName(product.name);
      setCategory(product.category);
      setPrice(product.price.toString());
      setMoq(product.moq);
      setStock(product.stock);
      setSugar(product.sugar);
      setSodium(product.sodium);
      setFat(product.fat);
      setIsBannedType(product.isBannedType);
      setBannedCategory(product.bannedCategory || '');
    } else {
      setName('');
      setCategory('Chicken');
      setPrice('');
      setMoq(5);
      setStock(100);
      setSugar(0);
      setSodium(100);
      setFat(2);
      setIsBannedType(false);
      setBannedCategory('');
    }
  }, [product, isOpen]);

  if (!isOpen) return null;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({
      id: product?.id,
      supplierId: product?.supplierId || defaultSupplierId || suppliers[0]?.id,
      name,
      category,
      price: parseFloat(price) || 0,
      moq,
      stock,
      sugar,
      sodium,
      fat,
      isBannedType,
      bannedCategory: isBannedType ? bannedCategory : ''
    });
    onClose();
  };

  return (
    <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in font-sans">
      <div className="bg-white rounded-3xl p-6 shadow-2xl max-w-lg w-full border border-slate-100 modal-pop">
        <div className="flex justify-between items-center border-b pb-3 mb-4">
          <h2 className="text-sm font-black uppercase text-slate-900">{product ? 'Modify Vetted SKU' : 'Publish Compliant SKU'}</h2>
          <button onClick={onClose} className="p-1 text-slate-400 hover:text-slate-600 rounded">
            <X size={16} />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">SKU Name</label>
              <input required type="text" value={name} onChange={e => setName(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700" />
            </div>
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Category</label>
              <select value={category} onChange={e => setCategory(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700">
                <option value="Chicken">Chicken</option>
                <option value="Processed Meat">Processed Meat</option>
                <option value="Finger Food">Finger Food</option>
                <option value="Drinks">Drinks</option>
                <option value="Frozen Kuih">Frozen Kuih</option>
              </select>
            </div>
          </div>

          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Wholesale Price (RM)</label>
              <input required type="number" step="0.01" value={price} onChange={e => setPrice(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700" />
            </div>
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Minimum Order Qty</label>
              <input required type="number" value={moq} onChange={e => setMoq(parseInt(e.target.value) || 1)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700" />
            </div>
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase tracking-wider mb-1">Stock Level</label>
              <input required type="number" value={stock} onChange={e => setStock(parseInt(e.target.value) || 0)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700" />
            </div>
          </div>

          <div className="bg-slate-50 p-4 rounded-2xl grid grid-cols-3 gap-3 border border-slate-200/60">
            <div>
              <label className="block text-[9px] font-bold text-slate-500 mb-1">Sugar (g / 100g)</label>
              <input required type="number" step="0.1" value={sugar} onChange={e => setSugar(parseFloat(e.target.value) || 0)} className="w-full p-2 bg-white border rounded text-xs text-slate-800 outline-none" />
            </div>
            <div>
              <label className="block text-[9px] font-bold text-slate-500 mb-1">Sodium (mg / 100g)</label>
              <input required type="number" value={sodium} onChange={e => setSodium(parseInt(e.target.value) || 0)} className="w-full p-2 bg-white border rounded text-xs text-slate-800 outline-none" />
            </div>
            <div>
              <label className="block text-[9px] font-bold text-slate-500 mb-1">Lipid Fat (g / 100g)</label>
              <input required type="number" step="0.1" value={fat} onChange={e => setFat(parseFloat(e.target.value) || 0)} className="w-full p-2 bg-white border rounded text-xs text-slate-800 outline-none" />
            </div>
          </div>

          <div className="flex items-center gap-2 bg-orange-50 border border-orange-100 p-3 rounded-2xl">
            <input 
              type="checkbox" 
              checked={isBannedType} 
              onChange={e => setIsBannedType(e.target.checked)} 
              id="bannedCheck"
              className="accent-orange-600 cursor-pointer"
            />
            <label htmlFor="bannedCheck" className="text-xs font-bold text-orange-900 cursor-pointer">Mark as KPM 13 Prohibited food category</label>
          </div>

          {isBannedType && (
            <div>
              <label className="block text-[10px] font-extrabold text-slate-500 uppercase mb-1">Prohibited Category Selection</label>
              <select value={bannedCategory} onChange={e => setBannedCategory(e.target.value)} className="w-full p-2 border border-slate-200 rounded-xl text-xs bg-slate-50 text-slate-800 outline-none focus:ring-2 focus:ring-emerald-700">
                <option value="">Select Category</option>
                <option value="Mee Segera & Ramen (Instant Noodles)">Mee Segera & Ramen (Instant Noodles)</option>
                <option value="Minuman Bergas & Soda (Carbonated Soft Drinks)">Minuman Bergas & Soda (Carbonated Soft Drinks)</option>
              </select>
            </div>
          )}

          <div className="flex justify-end gap-2 border-t pt-3">
            <button type="button" onClick={onClose} className="px-4 py-2 text-xs font-bold text-slate-500 hover:bg-slate-100 rounded-xl">Cancel</button>
            <button type="submit" className="px-4 py-2 bg-emerald-800 text-white text-xs font-bold rounded-xl uppercase shadow hover:bg-emerald-950">Commit SKU Vetting</button>
          </div>
        </form>
      </div>
    </div>
  );
}


function AppShell({ onLogout }: { onLogout: () => void }) {
  const { showToast } = useToast();
  const { lang, t } = useContext(LanguageContext)!;

  const [currentUser, setCurrentUser] = useState<User | null>(SEED_USERS[2]); 
  const [buyerProfile, setBuyerProfile] = useState<Buyer | null>(SEED_BUYERS[0]);
  const [supplierProfile, setSupplierProfile] = useState<Supplier | null>(null);

  const [activeTab, setActiveTab] = useState<TabKey>("overview");
  const [collapsed, setCollapsed] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");

  const [users, setUsers] = useState<User[]>(SEED_USERS);
  const [suppliers, setSuppliers] = useState<Supplier[]>(SEED_SUPPLIERS);
  const [buyers, setBuyers] = useState<Buyer[]>(SEED_BUYERS);
  const [products, setProducts] = useState<Product[]>(SEED_PRODUCTS);
  const [rules, setRules] = useState<ComplianceRule[]>(SEED_COMPLIANCE_RULES);
  const [orders, setOrders] = useState<Order[]>(SEED_ORDERS);
  const [recurring, setRecurring] = useState<RecurringOrder[]>(SEED_RECURRING);
  const [reviews, setReviews] = useState<Review[]>(SEED_REVIEWS);
  const [messages, setMessages] = useState<Message[]>(SEED_MESSAGES);
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [deliveries, setDeliveries] = useState<Delivery[]>(SEED_DELIVERIES);
  const [schedules, setSchedules] = useState<DeliverySchedule[]>(SEED_SCHEDULES);
  const [favorites, setFavorites] = useState<{ buyerId: string; supplierId: string }[]>([]);
  const [analytics, setAnalytics] = useState<AnalyticsData | null>(null);

  const [cart, setCart] = useState<CartItem[]>([]);
  const [productModalOpen, setProductModalOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);

  const auditedProducts = useMemo(() => {
    return products.map(p => {
      const sugarRule = rules.find(r => r.code === 'S_MAX_10G');
      const sodiumRule = rules.find(r => r.code === 'NA_MAX_400MG');
      const fatRule = rules.find(r => r.code === 'F_MAX_10G');
      const blacklistRule = rules.find(r => r.code === 'KPM_13_BLACK_LIST');

      let complianceStatus: 'allowed' | 'restricted' | 'prohibited' = 'allowed';
      let complianceNotes = "Passes KPM Vetting.";
      let complianceNotesEn = "Passes KPM Vetting.";

      if (blacklistRule?.active && p.isBannedType) {
        complianceStatus = 'prohibited';
        complianceNotes = `Item Larangan: Diklasifikasikan di bawah ${p.bannedCategory || "KPM Banned Foods"}.`;
        complianceNotesEn = `Prohibited Item: Classified under ${p.bannedCategory || "KPM Banned Foods"}.`;
      } else if (sugarRule?.active && p.sugar > 10) {
        complianceStatus = 'prohibited';
        complianceNotes = `Gula Terlampau Tinggi: Nilai ${p.sugar}g melebihi had KPM S_max 10g.`;
        complianceNotesEn = `Prohibited Sugar: sugar of ${p.sugar}g exceeds KPM S_max of 10g.`;
      } else if (sodiumRule?.active && p.sodium > 400) {
        complianceStatus = 'prohibited';
        complianceNotes = `Natrium Terlampau Tinggi: Nilai ${p.sodium}mg melebihi had KPM Na_max 400mg.`;
        complianceNotesEn = `Prohibited Sodium: sodium of ${p.sodium}mg exceeds KPM Na_max of 400mg.`;
      } else if (sugarRule?.active && p.sugar > 6) {
        complianceStatus = 'restricted';
        complianceNotes = "Terhad: Menghampiri had parameter gizi KPM.";
        complianceNotesEn = "Restricted: Near KPM threshold limit.";
      } else if (sodiumRule?.active && p.sodium > 300) {
        complianceStatus = 'restricted';
        complianceNotes = "Terhad: Menghampiri had parameter natrium KPM.";
        complianceNotesEn = "Borderline restricted SKU: Sodium is near Na_max.";
      }

      return {
        ...p,
        complianceStatus,
        complianceNotes,
        complianceNotesEn
      };
    });
  }, [products, rules]);

  const handleAuth = (user: User, profile: any) => {
    setCurrentUser(user);
    if (user.role === 'buyer') {
      setBuyerProfile(profile);
      setSupplierProfile(null);
    } else if (user.role === 'supplier') {
      setSupplierProfile(profile);
      setBuyerProfile(null);
    } else {
      setBuyerProfile(null);
      setSupplierProfile(null);
    }
    showToast(lang === 'bm' ? "Sesi Sistem Dihubungkan" : "System Session Connected", `Selamat kembali ${user.name}`);
  };

  const handleLogout = () => {
    setCurrentUser(null);
    setBuyerProfile(null);
    setSupplierProfile(null);
    onLogout();
  };

  const handleUpdateOrder = (id: string, patch: Record<string, any>) => {
    setOrders(prev => prev.map(o => o.id === id ? { ...o, ...patch } : o));
    showToast(lang === 'bm' ? "Log Pesanan Dikemaskini" : "Order Log Updated", "Fulfillment synced.");
  };

  const handleCheckout = async (payload: any) => {
    const orderNum = "CS-2026-" + Math.floor(1000 + Math.random() * 9000);
    const newOrder: Order = {
      id: "o-" + Date.now(),
      orderNumber: orderNum,
      buyerId: payload.buyerId,
      supplierId: payload.supplierId,
      items: cart.map(item => ({
        productId: item.product.id,
        productName: item.product.name,
        productNameEn: item.product.nameEn,
        quantity: item.quantity,
        price: item.product.price
      })),
      total: cartTotal,
      status: 'pending',
      paymentMethod: payload.paymentMethod,
      deliveryDate: payload.deliveryDate,
      deliveryWindow: payload.deliveryWindow,
      deliveryZone: payload.deliveryZone,
      date: new Date().toISOString()
    };

    setOrders(prev => [newOrder, ...prev]);
    showToast(lang === 'bm' ? "Kumpulan Pesanan Berjaya" : "Batch Commit Success", `${orderNum} generated. Dispatch manifested.`);
    return { supplierWhatsapp: "601112345678" };
  };

  const cartTotal = cart.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);

  const handleRepeatOrder = (order: Order) => {
    const repeated: Order = {
      ...order,
      id: "o-" + Date.now(),
      orderNumber: "CS-2026-" + Math.floor(1000 + Math.random() * 9000),
      status: 'pending',
      date: new Date().toISOString()
    };
    setOrders(prev => [repeated, ...prev]);
    showToast(lang === 'bm' ? "Kitaran Semula Ditetapkan" : "Cycle Re-manifested", repeated.orderNumber + " committed.");
  };

  const handleCancelOrder = (id: string) => {
    setOrders(prev => prev.map(o => o.id === id ? { ...o, status: 'cancelled' } : o));
    showToast(lang === 'bm' ? "Pesanan Dibatalkan" : "Order Cancelled", "Purchase run retracted.");
  };

  const handleSaveProduct = (p: any) => {
    if (p.id) {
      setProducts(prev => prev.map(prod => prod.id === p.id ? { ...prod, ...p } : prod));
      showToast(lang === 'bm' ? "SKU Dikemaskini" : "SKU Updated", "Changes pushed live.");
    } else {
      const added: Product = {
        ...p,
        id: "p-" + Date.now(),
        totalSold: 0,
        complianceStatus: 'allowed'
      };
      setProducts(prev => [added, ...prev]);
      showToast(lang === 'bm' ? "Saringan Vetting Lulus" : "SKU Vetting Passed", p.name + " listed on the market.");
    }
  };

  const handleDeleteProduct = (id: string) => {
    setProducts(prev => prev.filter(prod => prod.id !== id));
    showToast(lang === 'bm' ? "SKU Dipadamkan" : "SKU Removed", "Item catalog unlinked.");
  };

  const handleCreateRecurring = (rec: any) => {
    const added: RecurringOrder = {
      ...rec,
      id: "rec-" + Date.now()
    };
    setRecurring(prev => [added, ...prev]);
    showToast(lang === 'bm' ? "Jadual Kitaran Ditetapkan" : "Cycle Schedule Set", rec.name + " created.");
  };

  const handleToggleRule = (id: string, active: boolean) => {
    setRules(prev => prev.map(r => r.id === id ? { ...r, active } : r));
    showToast(active ? "Constraint Rule Live" : "Constraint Rule Paused", "Re-evaluating entire catalog.");
  };

  const handleCreateRule = (rule: any) => {
    const added: ComplianceRule = {
      ...rule,
      id: "cr-" + Date.now()
    };
    setRules(prev => [added, ...prev]);
    showToast("Compliance Rule Published", rule.code + " active.");
  };

  const handleDeleteRule = (id: string) => {
    setRules(prev => prev.filter(r => r.id !== id));
    showToast("Rule Removed", "Catalog re-scanned without constraints.");
  };

  const handleRescan = () => {
    showToast(lang === 'bm' ? "Saringan Automatik Selesai" : "Dynamic Scan Complete", "Entire inventory validated against active sandbox guidelines.");
  };

  const handleUpdateSupplier = (id: string, patch: any) => {
    setSuppliers(prev => prev.map(s => s.id === id ? { ...s, ...patch } : s));
    showToast("Wholesaler Updated", "Certification verification parsed.");
  };

  const handleBroadcast = (title: string, body: string, targetRole: string) => {
    const alert: Notification = {
      id: "not-" + Date.now(),
      userId: 'all',
      title,
      body,
      read: false,
      type: 'announcement'
    };
    setNotifications(prev => [alert, ...prev]);
    showToast("Alert Dispatch Broadcasted", "Broadcasting message to registered accounts.");
  };

  const handleToggleFavorite = (supId: string) => {
    showToast("Supplier Saved", "Linked inside your preferred vendor list.");
  };

  const handleAdvanceDelivery = (id: string, status: string) => {
    setDeliveries(prev => prev.map(d => d.id === id ? { ...d, status } : d));
    showToast("Delivery Check-in Recorded", "Proof of delivery captured.");
  };

  const handleAddSchedule = (sch: any) => {
    const added = {
      id: "sch-" + Date.now(),
      ...sch
    };
    setSchedules(prev => [added, ...prev]);
    showToast("Logistics Slot Published", "Early morning routing manifest linked.");
  };

  const displayName = buyerProfile?.businessName || supplierProfile?.companyName || currentUser?.name || "System Admin";
  const subtitle = currentUser?.role === 'buyer' ? 'Canteen Operator' : currentUser?.role === 'supplier' ? 'Accredited Supplier' : currentUser?.role === 'regulator' ? 'KPM Regulator' : 'Admin';

  if (!currentUser) {
    return <AuthScreen onAuth={handleAuth} onBackToLanding={handleLogout} />;
  }

  return (
    <div className="min-h-screen bg-slate-100 flex font-sans">
      <Sidebar 
        activeTab={activeTab}
        setActiveTab={setActiveTab}
        collapsed={collapsed}
        setCollapsed={setCollapsed}
        role={currentUser.role}
        pendingSupplierCount={0}
        cartCount={cart.length}
      />

      <div className="flex-1 flex flex-col min-w-0 justify-between">
        <div className="flex flex-col">
          <Header 
            currentUser={currentUser}
            displayName={displayName}
            subtitle={subtitle}
            zone={currentUser.zone}
            searchTerm={searchTerm}
            setSearchTerm={setSearchTerm}
            notifications={notifications}
            onMarkAllRead={() => setNotifications([])}
            onLogout={handleLogout}
          />

          <main className="p-6 bg-slate-50 flex-1">
            {activeTab === 'overview' && (
              <OverviewTab 
                currentUser={currentUser}
                buyerProfile={buyerProfile}
                supplierProfile={supplierProfile}
                analytics={analytics}
                orders={orders}
                suppliers={suppliers}
                products={auditedProducts}
                schedules={schedules}
                recurring={recurring}
                onNavigate={setActiveTab}
                onRepeatOrder={handleRepeatOrder}
              />
            )}

            {activeTab === 'blueprint' && (
              <div className="space-y-6 max-w-6xl animate-fade-in text-slate-800">
                <h1 className="text-2xl font-black text-slate-900">{lang === 'bm' ? 'Pelan Induk Rangka Kerja Jajahan' : 'Kota Bharu Pilot Blueprint'}</h1>
                <p className="text-xs text-slate-500">Dual-sided supply and demand synchronization launchpad.</p>
                
                <div className="bg-white p-5 rounded-3xl border border-slate-200/80 shadow-sm grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <h3 className="font-extrabold text-xs uppercase tracking-wider text-emerald-800 mb-2">
                      {lang === 'bm' ? 'Teras 1: Komitmen Permintaan Terkumpul' : 'Pillar 1: Consolidated Demand Locking'}
                    </h3>
                    <p className="text-xs text-slate-600 leading-relaxed font-sans">
                      {lang === 'bm'
                        ? 'Menyelaraskan 10-15 kantin sekolah anchor dalam rangkaian perolehan kit makanan sihat berkala. Pemborong boleh menawarkan diskaun sehingga 18% hasil daripada kestabilan permintaan harian.'
                        : 'By coordinating 10-15 high-enrollment Kota Bharu canteens into automated recurring weekly meal kits, baseload demand is stabilized. Suppliers confidently lower wholesale pricing by 18% in exchange for predictable, committed daily orders.'
                      }
                    </p>
                  </div>
                  <div>
                    <h3 className="font-extrabold text-xs uppercase tracking-wider text-orange-600 mb-2">
                      {lang === 'bm' ? 'Teras 2: Saringan Bekalan Halal Terakreditasi' : 'Pillar 2: Vetted Halal Supplier Pipeline'}
                    </h3>
                    <p className="text-xs text-slate-600 leading-relaxed">
                      {lang === 'bm'
                        ? 'Saringan SMEs pemprosesan makanan Kelantan secara terus. Parameter nutrisi disaring semasa invois dimuat naik untuk mengelakkan produk terlarang dipaparkan dalam katalog.'
                        : 'We accredit Kelantan frozen food processing SMEs. Ingredients are auto-audited against KPM nutrition rules during invoice uploads. Non-compliant items are blacklisted before transactions occur.'
                      }
                    </p>
                  </div>
                </div>

                <div className="bg-white p-5 rounded-3xl border border-slate-200/80 shadow-sm space-y-4">
                  <h3 className="font-extrabold text-xs uppercase tracking-wider text-emerald-800">
                    {lang === 'bm' ? 'Profil Pengedaran Mengikut Jajahan' : 'Kelantan Regional Profile distribution'}
                  </h3>
                  <div className="overflow-x-auto">
                    <table className="w-full text-left text-xs border-collapse">
                      <thead>
                        <tr className="bg-slate-50 text-slate-500 font-extrabold uppercase border-b">
                          <th className="p-3">{lang === 'bm' ? 'Jajahan' : 'District'}</th>
                          <th className="p-3">{lang === 'bm' ? 'Sekolah Terlibat' : 'Approx. Schools'}</th>
                          <th className="p-3">{lang === 'bm' ? 'Pemborong Sah' : 'Approx. Suppliers'}</th>
                          <th className="p-3">{lang === 'bm' ? 'Peranan Strategik' : 'Strategic Role'}</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y text-slate-700">
                        <tr>
                          <td className="p-3 font-bold">Kota Bharu</td>
                          <td className="p-3">300</td>
                          <td className="p-3">150</td>
                          <td className="p-3">{lang === 'bm' ? 'Hab Utama: Kepadatan sekolah bandar yang tinggi' : 'Anchor Hub: Dense urban school cluster, high supplier concentration'}</td>
                        </tr>
                        <tr>
                          <td className="p-3 font-bold">Pasir Mas</td>
                          <td className="p-3">200</td>
                          <td className="p-3">80</td>
                          <td className="p-3">{lang === 'bm' ? 'Kecairan Luar Bandar: Fokus kepada keluarga B40 dan koperasi tempatan' : 'Rural Liquidity: High B40 student count, poultry and meat co-ops'}</td>
                        </tr>
                        <tr>
                          <td className="p-3 font-bold">Tumpat</td>
                          <td className="p-3">150</td>
                          <td className="p-3">50</td>
                          <td className="p-3">{lang === 'bm' ? 'Logistik Pesisir: Pembekalan hasil laut sejuk beku berkualiti' : 'Coastal Logistics: Fisheries, fresh seafood cold-chain logs'}</td>
                        </tr>
                        <tr>
                          <td className="p-3 font-bold">Bachok</td>
                          <td className="p-3">120</td>
                          <td className="p-3">40</td>
                          <td className="p-3">{lang === 'bm' ? 'Inovasi Pakej: Koperasi tani membekalkan buah-buahan segar' : 'Bundle Innovation: Agricultural cooperatives, fresh fruit distribution'}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            )}

            {activeTab === 'marketplace' && (
              <MarketplaceTab 
                products={auditedProducts}
                suppliers={suppliers}
                schedules={schedules}
                buyerProfile={buyerProfile}
                role={currentUser.role}
                searchTerm={searchTerm}
                cart={cart}
                setCart={setCart}
                onCheckout={handleCheckout}
                onEditProduct={(p) => { setEditingProduct(p); setProductModalOpen(true); }}
                onDeleteProduct={handleDeleteProduct}
                onAddProduct={() => { setEditingProduct(null); setProductModalOpen(true); }}
              />
            )}

            {activeTab === 'orders' && (
              <OrdersTab 
                orders={orders}
                role={currentUser.role}
                buyerProfile={buyerProfile}
                supplierProfile={supplierProfile}
                searchTerm={searchTerm}
                suppliers={suppliers}
                onUpdateOrder={handleUpdateOrder}
                onRepeatOrder={handleRepeatOrder}
                onCancelOrder={handleCancelOrder}
              />
            )}

            {activeTab === 'deliveries' && (
              <DeliveriesTab 
                deliveries={deliveries}
                schedules={schedules}
                suppliers={suppliers}
                role={currentUser.role}
                supplierProfile={supplierProfile}
                onAdvanceDelivery={handleAdvanceDelivery}
                onAddSchedule={handleAddSchedule}
              />
            )}

            {activeTab === 'recurring' && (
              <RecurringTab 
                recurring={recurring}
                buyerProfile={buyerProfile}
                suppliers={suppliers}
                products={auditedProducts}
                onToggle={(id, active) => handleToggleRule(id, active)}
                onToggleAuto={(id, auto) => showToast("Auto confirm updated", "State updated.")}
                onDelete={(id) => setRecurring(prev => prev.filter(r => r.id !== id))}
                onCreate={handleCreateRecurring}
                onRunNow={(rec) => handleRepeatOrder({ ...orders[0], buyerId: rec.buyerId, supplierId: rec.supplierId, total: 180.00 })}
              />
            )}

            {activeTab === 'suppliers' && (
              <SuppliersTab 
                suppliers={suppliers}
                reviews={reviews}
                buyerProfile={buyerProfile}
                role={currentUser.role}
                favorites={favorites}
                onToggleFavorite={handleToggleFavorite}
              />
            )}

            {activeTab === 'compliance' && (
              <ComplianceTab 
                rules={rules}
                products={auditedProducts}
                analytics={analytics}
                role={currentUser.role}
                onToggleRule={handleToggleRule}
                onCreateRule={handleCreateRule}
                onDeleteRule={handleDeleteRule}
                onRescan={handleRescan}
              />
            )}

            {activeTab === 'chats' && (
              <ChatsTab 
                messages={messages}
                buyers={buyers}
                suppliers={suppliers}
                currentUser={currentUser}
                buyerProfile={buyerProfile}
                supplierProfile={supplierProfile}
                role={currentUser.role}
                onSend={(m) => setMessages(prev => [...prev, { ...m, id: "m-" + Date.now() }])}
              />
            )}

            {activeTab === 'analytics' && (
              <AnalyticsTab 
                analytics={analytics}
                orders={orders}
                role={currentUser.role}
                buyerProfile={buyerProfile}
                supplierProfile={supplierProfile}
                suppliers={suppliers}
              />
            )}

            {activeTab === 'admin' && (
              <AdminTab 
                analytics={analytics}
                suppliers={suppliers}
                buyers={buyers}
                orders={orders}
                users={users}
                onUpdateSupplier={handleUpdateSupplier}
                onBroadcast={handleBroadcast}
              />
            )}

            {activeTab === 'deck' && (
              <GcpDeckTab />
            )}
          </main>
        </div>

        <footer className="py-4 text-center text-[11px] text-slate-400 font-medium border-t border-slate-100 bg-white">
          {t('footerBranding')}
        </footer>
      </div>

      <ProductModal 
        isOpen={productModalOpen}
        onClose={() => setProductModalOpen(false)}
        onSave={handleSaveProduct}
        product={editingProduct}
        suppliers={suppliers}
        defaultSupplierId={supplierProfile?.id}
      />
    </div>
  );
}

function StatCard({ icon: Icon, title, value, subtext, color }: { icon: any, title: string, value: any, subtext: string, color: string }) {
  return (
    <div className={`bg-white p-5 rounded-2xl shadow-sm flex items-start gap-4 border border-slate-100 ${color}`}>
      <div className="p-3 rounded-xl bg-white shadow-sm shrink-0">
        <Icon className="w-5 h-5 text-slate-800" />
      </div>
      <div className="min-w-0">
        <span className="text-[9px] font-black uppercase tracking-wider text-slate-400 block">{title}</span>
        <strong className="text-xl font-black text-slate-900 leading-none mt-1 block">{value}</strong>
        <span className="text-[10px] text-slate-500 mt-1 block font-medium leading-normal">{subtext}</span>
      </div>
    </div>
  );
}

function ComplianceBadge({ status }: { status: 'allowed' | 'restricted' | 'prohibited' }) {
  const config = {
    allowed: { bg: 'bg-emerald-50 text-emerald-800 border-emerald-100', label: 'Allowed', icon: '✓' },
    restricted: { bg: 'bg-amber-50 text-amber-800 border-amber-100', label: 'Restricted', icon: '!' },
    prohibited: { bg: 'bg-rose-50 text-rose-800 border-rose-100', label: 'Prohibited', icon: '✕' },
  };
  const c = config[status] || config.allowed;
  
  return (
    <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[9px] font-extrabold border ${c.bg}`}>
      <span>{c.icon}</span> {c.label}
    </span>
  );
}

function OrderStatusBadge({ status }: { status: 'pending' | 'out_for_delivery' | 'delivered' | 'cancelled' }) {
  const config = {
    pending: { bg: 'bg-orange-50 text-orange-800 border-orange-100', label: 'Pending Cut-off' },
    out_for_delivery: { bg: 'bg-blue-50 text-blue-800 border-blue-100', label: 'In Transit' },
    delivered: { bg: 'bg-emerald-50 text-emerald-800 border-emerald-100', label: 'Delivered' },
    cancelled: { bg: 'bg-slate-50 text-slate-800 border-slate-100', label: 'Cancelled' },
  };
  const c = config[status] || config.pending;
  
  return (
    <span className={`px-2 py-0.5 rounded-full text-[9px] font-extrabold border ${c.bg}`}>
      {c.label}
    </span>
  );
}


export default function Page() {
  const [lang, setLangState] = useState<Language>('bm');
  const [currentScreen, setCurrentScreen] = useState<'landing' | 'dashboard'>('landing');

  const setLang = (newLang: Language) => {
    setLangState(newLang);
  };

  const t = useCallback((key: string) => {
    return TRANSLATIONS[lang][key as keyof typeof TRANSLATIONS['bm']] || key;
  }, [lang]);

  const value = useMemo(() => ({ lang, setLang, t }), [lang, t]);

  return (
    <LanguageContext.Provider value={value}>
      <ToastProvider>
        {currentScreen === 'landing' ? (
          <LandingScreen onLaunchDemo={() => setCurrentScreen('dashboard')} />
        ) : (
          <AppShell onLogout={() => setCurrentScreen('landing')} />
        )}
      </ToastProvider>
    </LanguageContext.Provider>
  );
}