import * as icon from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import React, { ReactElement, useCallback, useEffect, useMemo, useState } from 'react';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import LayoutAuthenticated from '../layouts/Authenticated';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';

type TabId =
  | 'dashboard'
  | 'products'
  | 'inventory'
  | 'orders'
  | 'customers'
  | 'payments'
  | 'shipping'
  | 'marketing'
  | 'reports'
  | 'settings';

type Product = {
  id: string;
  name: string;
  category: string;
  price: number;
  stock: number;
  reorderPoint: number;
  reorderPack: number;
  description: string;
  sold: number;
  margin: number;
  trend: number;
};

type Customer = {
  id: string;
  name: string;
  phone: string;
  email: string;
  address: string;
  segment: 'VIP' | 'Reguler' | 'Baru';
  orders: number;
  lifetimeValue: number;
};

type OrderStatus = 'Baru' | 'Diproses' | 'Dikirim' | 'Selesai';
type PaymentStatus = 'Menunggu' | 'Berhasil' | 'Gagal' | 'Refund';
type ShipmentStatus = 'Menunggu Pick Up' | 'Dikirim' | 'Terkirim' | 'Tahan QC';

type Order = {
  id: string;
  customerId: string;
  total: number;
  status: OrderStatus;
  paymentStatus: PaymentStatus;
  shipmentStatus: ShipmentStatus;
  channel: 'Web Store' | 'Marketplace' | 'Social Commerce' | 'B2B';
  createdAt: string;
  items: string[];
};

type Payment = {
  id: string;
  orderId: string;
  method: 'VA Bank' | 'QRIS' | 'Kartu Kredit' | 'COD' | 'Wallet';
  amount: number;
  status: PaymentStatus;
};

type Shipment = {
  id: string;
  orderId: string;
  destination: string;
  courier: string;
  eta: string;
  status: ShipmentStatus;
  risk: 'Rendah' | 'Sedang' | 'Tinggi';
};

type Campaign = {
  id: string;
  name: string;
  channel: 'Email' | 'Ads' | 'Affiliate' | 'Push';
  budget: number;
  status: 'Draft' | 'Aktif' | 'Selesai';
  conversion: number;
  revenue: number;
};

type LedgerItem = {
  id: string;
  title: string;
  detail: string;
  time: string;
  tone: 'info' | 'success' | 'warning' | 'danger';
};

type Settings = {
  storeName: string;
  currency: 'IDR';
  fulfillmentMode: 'Otomatis' | 'Manual Review';
  lowStockAlert: boolean;
  paymentAutoCapture: boolean;
};

type CommerceState = {
  products: Product[];
  customers: Customer[];
  orders: Order[];
  payments: Payment[];
  shipments: Shipment[];
  campaigns: Campaign[];
  ledger: LedgerItem[];
  settings: Settings;
  persistedAt?: string;
};

type CommerceAction = () => Promise<{ data: CommerceState }>;

const initialProducts: Product[] = [
  {
    id: 'SKU-EL-001',
    name: 'Vorta Smart Speaker X1',
    category: 'Elektronik',
    price: 1299000,
    stock: 42,
    reorderPoint: 12,
    reorderPack: 30,
    description: 'Speaker pintar untuk rumah, toko, dan kantor kecil.',
    sold: 318,
    margin: 28,
    trend: 12,
  },
  {
    id: 'SKU-FA-044',
    name: 'Nusa Everyday Tote',
    category: 'Fashion',
    price: 249000,
    stock: 9,
    reorderPoint: 16,
    reorderPack: 60,
    description: 'Tas kanvas premium untuk kreator dan pekerja mobile.',
    sold: 742,
    margin: 35,
    trend: 18,
  },
  {
    id: 'SKU-BE-117',
    name: 'Lumin Glow Serum',
    category: 'Beauty',
    price: 189000,
    stock: 24,
    reorderPoint: 20,
    reorderPack: 80,
    description: 'Serum wajah lokal dengan bundling campaign affiliate.',
    sold: 1094,
    margin: 42,
    trend: 25,
  },
  {
    id: 'SKU-HO-073',
    name: 'Bamboo Desk Organizer',
    category: 'Home Living',
    price: 159000,
    stock: 7,
    reorderPoint: 14,
    reorderPack: 45,
    description: 'Organizer meja kerja dari bambu daur ulang.',
    sold: 286,
    margin: 31,
    trend: -4,
  },
];

const initialCustomers: Customer[] = [
  {
    id: 'CUST-001',
    name: 'Alya Paramitha',
    phone: '+62 812 1000 2040',
    email: 'alya@vorta.demo',
    address: 'Jakarta Selatan',
    segment: 'VIP',
    orders: 18,
    lifetimeValue: 18450000,
  },
  {
    id: 'CUST-002',
    name: 'Raka Wijaya',
    phone: '+62 813 4400 8080',
    email: 'raka@vorta.demo',
    address: 'Bandung',
    segment: 'Reguler',
    orders: 7,
    lifetimeValue: 6390000,
  },
  {
    id: 'CUST-003',
    name: 'Sari Nusantara Mart',
    phone: '+62 21 5550 9911',
    email: 'procurement@sarinusa.demo',
    address: 'Surabaya',
    segment: 'VIP',
    orders: 31,
    lifetimeValue: 52800000,
  },
  {
    id: 'CUST-004',
    name: 'Dimas Kurnia',
    phone: '+62 857 9000 1133',
    email: 'dimas@vorta.demo',
    address: 'Yogyakarta',
    segment: 'Baru',
    orders: 1,
    lifetimeValue: 1299000,
  },
];

const initialOrders: Order[] = [
  {
    id: 'ORD-24061',
    customerId: 'CUST-001',
    total: 1548000,
    status: 'Diproses',
    paymentStatus: 'Berhasil',
    shipmentStatus: 'Menunggu Pick Up',
    channel: 'Web Store',
    createdAt: 'Hari ini, 09:24',
    items: ['Vorta Smart Speaker X1', 'Nusa Everyday Tote'],
  },
  {
    id: 'ORD-24062',
    customerId: 'CUST-002',
    total: 567000,
    status: 'Baru',
    paymentStatus: 'Menunggu',
    shipmentStatus: 'Menunggu Pick Up',
    channel: 'Marketplace',
    createdAt: 'Hari ini, 10:02',
    items: ['Lumin Glow Serum x3'],
  },
  {
    id: 'ORD-24063',
    customerId: 'CUST-003',
    total: 7950000,
    status: 'Dikirim',
    paymentStatus: 'Berhasil',
    shipmentStatus: 'Dikirim',
    channel: 'B2B',
    createdAt: 'Kemarin, 16:48',
    items: ['Bamboo Desk Organizer x50'],
  },
  {
    id: 'ORD-24064',
    customerId: 'CUST-004',
    total: 1299000,
    status: 'Baru',
    paymentStatus: 'Menunggu',
    shipmentStatus: 'Menunggu Pick Up',
    channel: 'Social Commerce',
    createdAt: 'Hari ini, 11:18',
    items: ['Vorta Smart Speaker X1'],
  },
];

const initialPayments: Payment[] = [
  { id: 'PAY-8801', orderId: 'ORD-24061', method: 'QRIS', amount: 1548000, status: 'Berhasil' },
  { id: 'PAY-8802', orderId: 'ORD-24062', method: 'VA Bank', amount: 567000, status: 'Menunggu' },
  { id: 'PAY-8803', orderId: 'ORD-24063', method: 'Kartu Kredit', amount: 7950000, status: 'Berhasil' },
  { id: 'PAY-8804', orderId: 'ORD-24064', method: 'Wallet', amount: 1299000, status: 'Menunggu' },
];

const initialShipments: Shipment[] = [
  {
    id: 'SHP-7101',
    orderId: 'ORD-24061',
    destination: 'Jakarta Selatan',
    courier: 'Vorta Express',
    eta: '4 jam',
    status: 'Menunggu Pick Up',
    risk: 'Rendah',
  },
  {
    id: 'SHP-7102',
    orderId: 'ORD-24063',
    destination: 'Surabaya',
    courier: 'Partner Cargo',
    eta: '1 hari',
    status: 'Dikirim',
    risk: 'Sedang',
  },
  {
    id: 'SHP-7103',
    orderId: 'ORD-24064',
    destination: 'Yogyakarta',
    courier: 'Instant Fleet',
    eta: '8 jam',
    status: 'Menunggu Pick Up',
    risk: 'Rendah',
  },
];

const initialCampaigns: Campaign[] = [
  {
    id: 'MKT-501',
    name: 'Payday Electronics Push',
    channel: 'Ads',
    budget: 4500000,
    status: 'Aktif',
    conversion: 5.8,
    revenue: 38250000,
  },
  {
    id: 'MKT-502',
    name: 'Beauty Affiliate Sprint',
    channel: 'Affiliate',
    budget: 2800000,
    status: 'Draft',
    conversion: 3.1,
    revenue: 11450000,
  },
  {
    id: 'MKT-503',
    name: 'VIP Repeat Buyer Email',
    channel: 'Email',
    budget: 650000,
    status: 'Selesai',
    conversion: 9.4,
    revenue: 19750000,
  },
];

const initialLedger: LedgerItem[] = [
  {
    id: 'LOG-1',
    title: 'Payment capture berhasil',
    detail: 'ORD-24061 lunas via QRIS dan siap masuk antrean pick up.',
    time: '2 menit lalu',
    tone: 'success',
  },
  {
    id: 'LOG-2',
    title: 'Low stock alert',
    detail: 'Nusa Everyday Tote dan Bamboo Desk Organizer di bawah reorder point.',
    time: '9 menit lalu',
    tone: 'warning',
  },
  {
    id: 'LOG-3',
    title: 'Campaign aktif',
    detail: 'Payday Electronics Push menghasilkan ROAS awal 8.5x.',
    time: '18 menit lalu',
    tone: 'info',
  },
];

const initialSettings: Settings = {
  storeName: 'VORTA Commerce HQ',
  currency: 'IDR',
  fulfillmentMode: 'Otomatis',
  lowStockAlert: true,
  paymentAutoCapture: true,
};

const vortaUniverseOrder = [
  {
    number: '1',
    title: 'VORTA Commerce',
    description:
      'Platform Perdagangan, Distribusi, Komunitas, dan Pembayaran Berbasis Kepercayaan.',
    href: '/vorta-commerce',
    iconName: 'mdiStorefrontOutline',
  },
  {
    number: '2',
    title: 'Vorta Synapse',
    description: 'Protokol Distribusi, Afiliasi, Dan Logistik Pintar Untuk Ekonomi Kreator.',
    href: '/vorta-synapse',
    iconName: 'mdiTransitConnectionVariant',
  },
  {
    number: '3',
    title: 'Mega Super-App',
    description: 'Chat Bisnis, Sosial, Marketplace, Dan Dompet Dalam Satu Ruang Kerja Ringan.',
    href: '/mega-super-app',
    iconName: 'mdiApps',
  },
  {
    number: '4',
    title: 'Vorta Nexus',
    description: 'Skor Kepercayaan 0-100 Untuk Identitas, Bisnis, Ulasan, Dan Akses Komunitas.',
    href: '/vorta-universe#vorta-overview',
    iconName: 'mdiShieldCheck',
  },
  {
    number: '5',
    title: 'Facta.Ai',
    description: 'Riset Bebas Seo Spam Dengan Truth Score Dan Peta Rujukan Langsung.',
    href: '/facta_queries/facta_queries-list',
    iconName: 'mdiShieldSearchOutline',
  },
];

const commerceVision =
  'Membangun ekosistem perdagangan digital berbasis kepercayaan terbesar yang menghubungkan seluruh rantai ekonomi dalam satu platform.';

const commerceMission = [
  'Membantu UMKM berkembang secara digital.',
  'Menghubungkan pembeli dan penjual secara aman.',
  'Mempercepat distribusi produk dan jasa.',
  'Mendukung ekonomi kreator dan afiliasi.',
  'Membangun komunitas bisnis yang aktif.',
  'Menyederhanakan komunikasi dan pembayaran.',
];

const commercePillars = [
  {
    title: 'Commerce',
    description: 'Pusat perdagangan digital.',
    features: [
      'Marketplace',
      'Toko Online',
      'Produk',
      'Keranjang Belanja',
      'Checkout',
      'Pesanan',
      'Pengiriman',
      'Retur',
      'Review',
    ],
  },
  {
    title: 'Distribution & Affiliate',
    description: 'Mesin pertumbuhan bisnis.',
    features: [
      'Affiliate Program',
      'Referral Program',
      'Komisi Otomatis',
      'Creator Partner',
      'Reseller Network',
      'Distributor Network',
      'Tracking Penjualan',
      'Dashboard Komisi',
    ],
  },
  {
    title: 'Smart Logistics',
    description: 'Sistem logistik terintegrasi.',
    features: [
      'Tracking Pengiriman',
      'Multi Kurir',
      'Pengiriman Lokal',
      'Pengiriman Nasional',
      'Estimasi Ongkir',
      'Smart Routing',
      'Manajemen Gudang',
    ],
  },
  {
    title: 'Social Commerce',
    description: 'Komunitas dan promosi dalam satu tempat.',
    features: ['Feed Sosial', 'Like', 'Komentar'],
  },
];

const tabs: { id: TabId; label: string; iconName: string }[] = [
  { id: 'dashboard', label: 'Dashboard', iconName: 'mdiViewDashboardOutline' },
  { id: 'products', label: 'Produk', iconName: 'mdiPackageVariantClosed' },
  { id: 'inventory', label: 'Inventori', iconName: 'mdiWarehouse' },
  { id: 'orders', label: 'Pesanan', iconName: 'mdiReceiptTextOutline' },
  { id: 'customers', label: 'Pelanggan', iconName: 'mdiAccountHeartOutline' },
  { id: 'payments', label: 'Pembayaran', iconName: 'mdiCreditCardOutline' },
  { id: 'shipping', label: 'Pengiriman', iconName: 'mdiTruckDeliveryOutline' },
  { id: 'marketing', label: 'Marketing', iconName: 'mdiBullhornOutline' },
  { id: 'reports', label: 'Laporan', iconName: 'mdiChartLine' },
  { id: 'settings', label: 'Pengaturan', iconName: 'mdiCogOutline' },
];

const formatCurrency = (value: number) =>
  new Intl.NumberFormat('id-ID', {
    style: 'currency',
    currency: 'IDR',
    maximumFractionDigits: 0,
  }).format(value);

const formatNumber = (value: number) => new Intl.NumberFormat('id-ID').format(value);

const resolveIcon = (iconName: string) =>
  iconName in icon
    ? (icon[iconName as keyof typeof icon] as string)
    : icon.mdiViewDashboardOutline;

const getCustomerName = (customers: Customer[], customerId: string) =>
  customers.find((customer) => customer.id === customerId)?.name || 'Pelanggan tidak diketahui';

const getStatusClass = (status: string) => {
  if (['Berhasil', 'Selesai', 'Terkirim', 'Aktif', 'VIP'].includes(status)) {
    return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-200';
  }

  if (['Menunggu', 'Baru', 'Menunggu Pick Up', 'Draft', 'Reguler'].includes(status)) {
    return 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-200';
  }

  if (['Gagal', 'Refund', 'Tahan QC'].includes(status)) {
    return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-200';
  }

  return 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-200';
};

const getToneClass = (tone: LedgerItem['tone']) => {
  if (tone === 'success') return 'bg-emerald-500';
  if (tone === 'warning') return 'bg-amber-500';
  if (tone === 'danger') return 'bg-red-500';

  return 'bg-blue-500';
};

const VortaCommercePage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const iconsColor = useAppSelector((state) => state.style.iconsColor);
  const [activeTab, setActiveTab] = useState<TabId>('dashboard');
  const [products, setProducts] = useState<Product[]>(initialProducts);
  const [customers, setCustomers] = useState<Customer[]>(initialCustomers);
  const [orders, setOrders] = useState<Order[]>(initialOrders);
  const [payments, setPayments] = useState<Payment[]>(initialPayments);
  const [shipments, setShipments] = useState<Shipment[]>(initialShipments);
  const [campaigns, setCampaigns] = useState<Campaign[]>(initialCampaigns);
  const [ledger, setLedger] = useState<LedgerItem[]>(initialLedger);
  const [settings, setSettings] = useState<Settings>(initialSettings);
  const [isLoadingCommerce, setIsLoadingCommerce] = useState(true);
  const [isSavingCommerce, setIsSavingCommerce] = useState(false);
  const [commerceError, setCommerceError] = useState<string | null>(null);
  const [persistedAt, setPersistedAt] = useState<string | null>(null);

  const applyCommerceState = useCallback((payload: CommerceState) => {
    setProducts(payload.products || initialProducts);
    setCustomers(payload.customers || initialCustomers);
    setOrders(payload.orders || initialOrders);
    setPayments(payload.payments || initialPayments);
    setShipments(payload.shipments || initialShipments);
    setCampaigns(payload.campaigns || initialCampaigns);
    setLedger(payload.ledger || initialLedger);
    setSettings(payload.settings || initialSettings);
    setPersistedAt(payload.persistedAt || new Date().toISOString());
  }, []);

  const loadCommerceState = useCallback(async () => {
    setIsLoadingCommerce(true);
    setCommerceError(null);

    try {
      const response = await axios.get<CommerceState>('/vorta-commerce/state');
      applyCommerceState(response.data);
    } catch (error) {
      console.error('Failed to load VORTA Commerce state:', error);
      setCommerceError('Data database belum bisa dimuat. Fallback demo lokal tetap ditampilkan.');
    } finally {
      setIsLoadingCommerce(false);
    }
  }, [applyCommerceState]);

  useEffect(() => {
    loadCommerceState();
  }, [loadCommerceState]);

  const runCommerceAction = useCallback(async (action: CommerceAction, errorMessage: string) => {
    setIsSavingCommerce(true);
    setCommerceError(null);

    try {
      const response = await action();
      applyCommerceState(response.data);
    } catch (error) {
      console.error(errorMessage, error);
      setCommerceError(`${errorMessage} Cek backend log untuk detail.`);
    } finally {
      setIsSavingCommerce(false);
    }
  }, [applyCommerceState]);

  const displayStoreName = settings.storeName
    .replace('VORTA-COMMERCE', 'VORTA Commerce')
    .replace('Vorta-Commerce', 'VORTA Commerce');

  const metrics = useMemo(() => {
    const paidRevenue = payments
      .filter((payment) => payment.status === 'Berhasil')
      .reduce((total, payment) => total + payment.amount, 0);
    const pendingRevenue = payments
      .filter((payment) => payment.status === 'Menunggu')
      .reduce((total, payment) => total + payment.amount, 0);
    const inventoryValue = products.reduce(
      (total, product) => total + product.price * product.stock,
      0,
    );
    const lowStockProducts = products.filter(
      (product) => product.stock <= product.reorderPoint,
    );
    const completedOrders = orders.filter((order) => order.status === 'Selesai').length;
    const successPaymentCount = payments.filter((payment) => payment.status === 'Berhasil').length;

    return {
      paidRevenue,
      pendingRevenue,
      inventoryValue,
      lowStockCount: lowStockProducts.length,
      lowStockProducts,
      openOrders: orders.filter((order) => order.status !== 'Selesai').length,
      completedOrders,
      totalOrders: orders.length,
      averageOrderValue: orders.length
        ? orders.reduce((total, order) => total + order.total, 0) / orders.length
        : 0,
      paymentSuccessRate: payments.length ? Math.round((successPaymentCount / payments.length) * 100) : 0,
      totalCustomers: customers.length,
      activeCampaigns: campaigns.filter((campaign) => campaign.status === 'Aktif').length,
      marketingRevenue: campaigns.reduce((total, campaign) => total + campaign.revenue, 0),
      totalStock: products.reduce((total, product) => total + product.stock, 0),
    };
  }, [campaigns, customers.length, orders, payments, products]);

  const bestSeller = useMemo(
    () => [...products].sort((first, second) => second.sold - first.sold)[0],
    [products],
  );

  const restockLowStock = () => {
    runCommerceAction(
      () => axios.post<CommerceState>('/vorta-commerce/inventory/restock'),
      'Gagal menjalankan restock cepat.',
    );
  };

  const createFlashOrder = () => {
    runCommerceAction(
      () => axios.post<CommerceState>('/vorta-commerce/orders/demo'),
      'Gagal membuat order demo.',
    );
  };

  const capturePayment = (paymentId: string) => {
    runCommerceAction(
      () => axios.post<CommerceState>(`/vorta-commerce/payments/${paymentId}/capture`),
      'Gagal capture payment.',
    );
  };

  const advanceOrder = (orderId: string) => {
    runCommerceAction(
      () => axios.post<CommerceState>(`/vorta-commerce/orders/${orderId}/advance`),
      'Gagal memajukan status order.',
    );
  };

  const completeShipment = (shipmentId: string) => {
    runCommerceAction(
      () => axios.post<CommerceState>(`/vorta-commerce/shipments/${shipmentId}/complete`),
      'Gagal menandai shipment terkirim.',
    );
  };

  const launchCampaign = (campaignId: string) => {
    runCommerceAction(
      () => axios.post<CommerceState>(`/vorta-commerce/campaigns/${campaignId}/launch`),
      'Gagal launch campaign.',
    );
  };

  const closeDailyReport = () => {
    runCommerceAction(
      () => axios.post<CommerceState>('/vorta-commerce/reports/close'),
      'Gagal mengunci laporan harian.',
    );
  };

  const toggleFulfillmentMode = () => {
    runCommerceAction(
      () => axios.patch<CommerceState>('/vorta-commerce/settings', {
        data: {
          fulfillmentMode: settings.fulfillmentMode === 'Otomatis' ? 'Manual Review' : 'Otomatis',
        },
      }),
      'Gagal mengubah fulfillment mode.',
    );
  };

  const toggleBooleanSetting = (key: 'lowStockAlert' | 'paymentAutoCapture') => {
    runCommerceAction(
      () => axios.patch<CommerceState>('/vorta-commerce/settings', {
        data: {
          [key]: !settings[key],
        },
      }),
      'Gagal menyimpan automation setting.',
    );
  };

  const renderMetricCard = (label: string, value: string, helper: string, iconName: string, accent: string) => (
    <CardBox className="border border-slate-100/80 bg-white/95 shadow-sm dark:border-dark-700 dark:bg-dark-900">
      <div className="flex items-start justify-between gap-4">
        <div>
          <p className="text-sm text-gray-500 dark:text-gray-400">{label}</p>
          <p className="mt-2 text-2xl font-bold text-slate-900 dark:text-white">{value}</p>
          <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">{helper}</p>
        </div>
        <div className={`rounded-2xl p-3 text-white ${accent}`}>
          <BaseIcon path={resolveIcon(iconName)} size="24" />
        </div>
      </div>
    </CardBox>
  );

  const renderDashboard = () => (
    <div className="space-y-6">
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
        {renderMetricCard(
          'Revenue lunas',
          formatCurrency(metrics.paidRevenue),
          `${metrics.paymentSuccessRate}% payment success rate`,
          'mdiCashMultiple',
          'bg-emerald-500',
        )}
        {renderMetricCard(
          'Open orders',
          formatNumber(metrics.openOrders),
          `${metrics.completedOrders} pesanan selesai`,
          'mdiReceiptClockOutline',
          'bg-blue-500',
        )}
        {renderMetricCard(
          'Nilai inventori',
          formatCurrency(metrics.inventoryValue),
          `${formatNumber(metrics.totalStock)} unit aktif`,
          'mdiWarehouse',
          'bg-violet-500',
        )}
        {renderMetricCard(
          'Low stock',
          formatNumber(metrics.lowStockCount),
          metrics.lowStockCount ? 'Perlu reorder otomatis' : 'Semua SKU aman',
          'mdiAlertCircleOutline',
          metrics.lowStockCount ? 'bg-amber-500' : 'bg-emerald-500',
        )}
      </div>

      <div className="grid grid-cols-1 gap-6 xl:grid-cols-3">
        <CardBox className="xl:col-span-2 border border-slate-100/80 dark:border-dark-700">
          <div className="mb-5 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
            <div>
              <h2 className="text-xl font-semibold">Command Center Commerce</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                Ringkasan real-time untuk produk, inventori, order, payment, dan pengiriman.
              </p>
            </div>
            <div className="flex flex-wrap gap-2">
              <BaseButton
                label="Buat Order Demo"
                icon={resolveIcon('mdiCartPlus')}
                color="info"
                small
                onClick={() => createFlashOrder()}
              />
              <BaseButton
                label="Auto Restock"
                icon={resolveIcon('mdiPackageVariantPlus')}
                color="success"
                small
                onClick={() => restockLowStock()}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
            <div className="rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
              <p className="text-sm text-gray-500 dark:text-gray-400">AOV</p>
              <p className="mt-2 text-2xl font-bold">{formatCurrency(metrics.averageOrderValue)}</p>
              <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">Average order value hari ini</p>
            </div>
            <div className="rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
              <p className="text-sm text-gray-500 dark:text-gray-400">Pending payment</p>
              <p className="mt-2 text-2xl font-bold">{formatCurrency(metrics.pendingRevenue)}</p>
              <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">Belum masuk cash-in</p>
            </div>
            <div className="rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
              <p className="text-sm text-gray-500 dark:text-gray-400">Marketing revenue</p>
              <p className="mt-2 text-2xl font-bold">{formatCurrency(metrics.marketingRevenue)}</p>
              <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">Dari {metrics.activeCampaigns} campaign aktif</p>
            </div>
          </div>

          <div className="mt-6 rounded-2xl border border-blue-100 bg-gradient-to-r from-blue-50 to-emerald-50 p-5 dark:border-blue-900/30 dark:from-blue-950/40 dark:to-emerald-950/20">
            <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
              <div>
                <p className="text-sm font-semibold tracking-wide text-blue-700 dark:text-blue-200">
                  Produk terlaris
                </p>
                <h3 className="mt-1 text-2xl font-bold">{bestSeller?.name}</h3>
                <p className="mt-1 text-sm text-gray-600 dark:text-gray-300">
                  {formatNumber(bestSeller?.sold || 0)} unit terjual • margin {bestSeller?.margin || 0}% • trend {bestSeller?.trend || 0}%
                </p>
              </div>
              <BaseButton
                label="Lihat Produk"
                icon={resolveIcon('mdiArrowRight')}
                color="info"
                onClick={() => setActiveTab('products')}
              />
            </div>
          </div>
        </CardBox>

        <CardBox className="border border-slate-100/80 dark:border-dark-700">
          <div className="mb-4 flex items-center justify-between">
            <div>
              <h2 className="text-xl font-semibold">Live Activity</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">Event terbaru sistem</p>
            </div>
            <BaseIcon path={resolveIcon('mdiPulse')} className="text-blue-500" size="24" />
          </div>
          <div className="space-y-4">
            {ledger.slice(0, 5).map((item) => (
              <div key={item.id} className="flex gap-3">
                <span className={`mt-1 h-3 w-3 flex-none rounded-full ${getToneClass(item.tone)}`} />
                <div>
                  <p className="font-semibold">{item.title}</p>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{item.detail}</p>
                  <p className="mt-1 text-xs text-gray-400">{item.time}</p>
                </div>
              </div>
            ))}
          </div>
        </CardBox>
      </div>
    </div>
  );

  const renderProducts = () => (
    <CardBox className="border border-slate-100/80 dark:border-dark-700">
      <div className="mb-5 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
        <div>
          <h2 className="text-xl font-semibold">Produk</h2>
          <p className="text-sm text-gray-500 dark:text-gray-400">Katalog produk utama seperti tabel `products`.</p>
        </div>
        <BaseButton
          label="Simulasi Order"
          icon={resolveIcon('mdiCartPlus')}
          color="info"
          small
          onClick={() => createFlashOrder()}
        />
      </div>
      <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-slate-100 text-left text-sm dark:divide-dark-700">
          <thead>
            <tr className="text-xs uppercase tracking-wide text-gray-500">
              <th className="py-3 pr-4">Produk</th>
              <th className="py-3 pr-4">Kategori</th>
              <th className="py-3 pr-4">Harga</th>
              <th className="py-3 pr-4">Stok</th>
              <th className="py-3 pr-4">Terjual</th>
              <th className="py-3 pr-4">Margin</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100 dark:divide-dark-700">
            {products.map((product) => (
              <tr key={product.id}>
                <td className="py-4 pr-4">
                  <p className="font-semibold">{product.name}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">{product.id} • {product.description}</p>
                </td>
                <td className="py-4 pr-4">{product.category}</td>
                <td className="py-4 pr-4 font-semibold">{formatCurrency(product.price)}</td>
                <td className="py-4 pr-4">
                  <span className={`rounded-full px-3 py-1 text-xs font-semibold ${product.stock <= product.reorderPoint ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-200' : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-200'}`}>
                    {formatNumber(product.stock)} unit
                  </span>
                </td>
                <td className="py-4 pr-4">{formatNumber(product.sold)}</td>
                <td className="py-4 pr-4">
                  <span className={product.trend >= 0 ? 'text-emerald-600' : 'text-red-500'}>
                    {product.margin}% • {product.trend >= 0 ? '+' : ''}{product.trend}%
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </CardBox>
  );

  const renderInventory = () => (
    <div className="grid grid-cols-1 gap-6 xl:grid-cols-3">
      <CardBox className="xl:col-span-2 border border-slate-100/80 dark:border-dark-700">
        <div className="mb-5 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <div>
            <h2 className="text-xl font-semibold">Inventori</h2>
            <p className="text-sm text-gray-500 dark:text-gray-400">Monitor stok, reorder point, dan nilai gudang.</p>
          </div>
          <BaseButton
            label="Auto Restock Semua Low Stock"
            icon={resolveIcon('mdiWarehouse')}
            color="success"
            small
            onClick={() => restockLowStock()}
          />
        </div>
        <div className="space-y-4">
          {products.map((product) => {
            const stockRatio = Math.min(100, Math.round((product.stock / (product.reorderPoint + product.reorderPack)) * 100));
            return (
              <div key={product.id} className="rounded-2xl border border-slate-100 p-4 dark:border-dark-700">
                <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
                  <div>
                    <p className="font-semibold">{product.name}</p>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      Stok {formatNumber(product.stock)} • Reorder point {product.reorderPoint} • Pack {product.reorderPack}
                    </p>
                  </div>
                  <span className={`w-fit rounded-full px-3 py-1 text-xs font-semibold ${product.stock <= product.reorderPoint ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-200' : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-200'}`}>
                    {product.stock <= product.reorderPoint ? 'Perlu Reorder' : 'Aman'}
                  </span>
                </div>
                <div className="mt-4 h-2 overflow-hidden rounded-full bg-slate-100 dark:bg-dark-800">
                  <div className="h-full rounded-full bg-blue-500" style={{ width: `${stockRatio}%` }} />
                </div>
              </div>
            );
          })}
        </div>
      </CardBox>
      <CardBox className="border border-slate-100/80 dark:border-dark-700">
        <h2 className="text-xl font-semibold">Purchase Signal</h2>
        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">SKU prioritas untuk reorder.</p>
        <div className="mt-5 space-y-3">
          {metrics.lowStockProducts.length ? (
            metrics.lowStockProducts.map((product) => (
              <div key={product.id} className="rounded-2xl bg-amber-50 p-4 dark:bg-amber-900/20">
                <p className="font-semibold">{product.name}</p>
                <p className="text-sm text-gray-500 dark:text-gray-300">
                  Rekomendasi beli {product.reorderPack} unit. Estimasi nilai {formatCurrency(product.reorderPack * product.price)}.
                </p>
              </div>
            ))
          ) : (
            <p className="rounded-2xl bg-emerald-50 p-4 text-sm text-emerald-700 dark:bg-emerald-900/20 dark:text-emerald-200">
              Semua SKU berada di atas reorder point.
            </p>
          )}
        </div>
      </CardBox>
    </div>
  );

  const renderOrders = () => (
    <CardBox className="border border-slate-100/80 dark:border-dark-700">
      <div className="mb-5 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
        <div>
          <h2 className="text-xl font-semibold">Pesanan</h2>
          <p className="text-sm text-gray-500 dark:text-gray-400">Pipeline dari order baru sampai selesai.</p>
        </div>
        <BaseButton
          label="Buat Order Demo"
          icon={resolveIcon('mdiCartPlus')}
          color="info"
          small
          onClick={() => createFlashOrder()}
        />
      </div>
      <div className="space-y-4">
        {orders.map((order) => (
          <div key={order.id} className="rounded-2xl border border-slate-100 p-4 dark:border-dark-700">
            <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
              <div>
                <div className="flex flex-wrap items-center gap-2">
                  <p className="text-lg font-semibold">{order.id}</p>
                  <span className={`rounded-full px-3 py-1 text-xs font-semibold ${getStatusClass(order.status)}`}>{order.status}</span>
                  <span className={`rounded-full px-3 py-1 text-xs font-semibold ${getStatusClass(order.paymentStatus)}`}>Payment {order.paymentStatus}</span>
                </div>
                <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  {getCustomerName(customers, order.customerId)} • {order.channel} • {order.createdAt}
                </p>
                <p className="mt-1 text-sm">{order.items.join(', ')}</p>
              </div>
              <div className="flex flex-col gap-2 md:flex-row md:items-center">
                <p className="font-bold md:mr-3">{formatCurrency(order.total)}</p>
                <BaseButton
                  label={order.status === 'Selesai' ? 'Selesai' : 'Majukan Status'}
                  icon={resolveIcon('mdiArrowRightCircleOutline')}
                  color={order.status === 'Selesai' ? 'success' : 'info'}
                  small
                  disabled={order.status === 'Selesai' || isSavingCommerce}
                  onClick={() => advanceOrder(order.id)}
                />
              </div>
            </div>
          </div>
        ))}
      </div>
    </CardBox>
  );

  const renderCustomers = () => (
    <CardBox className="border border-slate-100/80 dark:border-dark-700">
      <div className="mb-5">
        <h2 className="text-xl font-semibold">Pelanggan</h2>
        <p className="text-sm text-gray-500 dark:text-gray-400">CRM sederhana untuk segmentasi VIP, reguler, dan pelanggan baru.</p>
      </div>
      <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
        {customers.map((customer) => (
          <div key={customer.id} className="rounded-2xl border border-slate-100 p-4 dark:border-dark-700">
            <div className="flex items-start justify-between gap-4">
              <div>
                <p className="text-lg font-semibold">{customer.name}</p>
                <p className="text-sm text-gray-500 dark:text-gray-400">{customer.email} • {customer.phone}</p>
                <p className="mt-2 text-sm">{customer.address}</p>
              </div>
              <span className={`rounded-full px-3 py-1 text-xs font-semibold ${getStatusClass(customer.segment)}`}>{customer.segment}</span>
            </div>
            <div className="mt-4 grid grid-cols-2 gap-3 text-sm">
              <div className="rounded-xl bg-slate-50 p-3 dark:bg-dark-800">
                <p className="text-gray-500 dark:text-gray-400">Total order</p>
                <p className="font-semibold">{formatNumber(customer.orders)}</p>
              </div>
              <div className="rounded-xl bg-slate-50 p-3 dark:bg-dark-800">
                <p className="text-gray-500 dark:text-gray-400">Lifetime value</p>
                <p className="font-semibold">{formatCurrency(customer.lifetimeValue)}</p>
              </div>
            </div>
          </div>
        ))}
      </div>
    </CardBox>
  );

  const renderPayments = () => (
    <CardBox className="border border-slate-100/80 dark:border-dark-700">
      <div className="mb-5">
        <h2 className="text-xl font-semibold">Pembayaran</h2>
        <p className="text-sm text-gray-500 dark:text-gray-400">Payment capture, status settlement, dan metode transaksi.</p>
      </div>
      <div className="space-y-4">
        {payments.map((payment) => (
          <div key={payment.id} className="rounded-2xl border border-slate-100 p-4 dark:border-dark-700">
            <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
              <div>
                <div className="flex flex-wrap items-center gap-2">
                  <p className="font-semibold">{payment.id}</p>
                  <span className={`rounded-full px-3 py-1 text-xs font-semibold ${getStatusClass(payment.status)}`}>{payment.status}</span>
                </div>
                <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  {payment.orderId} • {payment.method} • {formatCurrency(payment.amount)}
                </p>
              </div>
              <BaseButton
                label={payment.status === 'Berhasil' ? 'Sudah Lunas' : 'Capture Payment'}
                icon={resolveIcon('mdiCheckCircleOutline')}
                color={payment.status === 'Berhasil' ? 'success' : 'info'}
                small
                disabled={payment.status === 'Berhasil' || isSavingCommerce}
                onClick={() => capturePayment(payment.id)}
              />
            </div>
          </div>
        ))}
      </div>
    </CardBox>
  );

  const renderShipping = () => (
    <CardBox className="border border-slate-100/80 dark:border-dark-700">
      <div className="mb-5">
        <h2 className="text-xl font-semibold">Pengiriman</h2>
        <p className="text-sm text-gray-500 dark:text-gray-400">Fulfillment, courier, ETA, dan risiko pengiriman.</p>
      </div>
      <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
        {shipments.map((shipment) => (
          <div key={shipment.id} className="rounded-2xl border border-slate-100 p-4 dark:border-dark-700">
            <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
              <div>
                <div className="flex flex-wrap items-center gap-2">
                  <p className="font-semibold">{shipment.id}</p>
                  <span className={`rounded-full px-3 py-1 text-xs font-semibold ${getStatusClass(shipment.status)}`}>{shipment.status}</span>
                </div>
                <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  {shipment.orderId} • {shipment.destination} • {shipment.courier}
                </p>
                <p className="mt-2 text-sm">ETA {shipment.eta} • Risiko {shipment.risk}</p>
              </div>
              <BaseButton
                label={shipment.status === 'Terkirim' ? 'Terkirim' : 'Tandai Terkirim'}
                icon={resolveIcon('mdiTruckCheckOutline')}
                color={shipment.status === 'Terkirim' ? 'success' : 'info'}
                small
                disabled={shipment.status === 'Terkirim' || isSavingCommerce}
                onClick={() => completeShipment(shipment.id)}
              />
            </div>
          </div>
        ))}
      </div>
    </CardBox>
  );

  const renderMarketing = () => (
    <CardBox className="border border-slate-100/80 dark:border-dark-700">
      <div className="mb-5">
        <h2 className="text-xl font-semibold">Marketing</h2>
        <p className="text-sm text-gray-500 dark:text-gray-400">Campaign, channel, budget, conversion, dan revenue.</p>
      </div>
      <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
        {campaigns.map((campaign) => (
          <div key={campaign.id} className="rounded-2xl border border-slate-100 p-4 dark:border-dark-700">
            <div className="mb-4 flex items-start justify-between gap-3">
              <div>
                <p className="font-semibold">{campaign.name}</p>
                <p className="text-sm text-gray-500 dark:text-gray-400">{campaign.channel} • {campaign.id}</p>
              </div>
              <span className={`rounded-full px-3 py-1 text-xs font-semibold ${getStatusClass(campaign.status)}`}>{campaign.status}</span>
            </div>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between"><span>Budget</span><strong>{formatCurrency(campaign.budget)}</strong></div>
              <div className="flex justify-between"><span>Conversion</span><strong>{campaign.conversion}%</strong></div>
              <div className="flex justify-between"><span>Revenue</span><strong>{formatCurrency(campaign.revenue)}</strong></div>
            </div>
            <BaseButton
              label={campaign.status === 'Aktif' ? 'Boost Campaign' : 'Launch Campaign'}
              icon={resolveIcon('mdiRocketLaunchOutline')}
              color="info"
              small
              className="mt-4 w-full"
              onClick={() => launchCampaign(campaign.id)}
            />
          </div>
        ))}
      </div>
    </CardBox>
  );

  const renderReports = () => {
    const paidOrders = orders.filter((order) => order.paymentStatus === 'Berhasil').length;
    const shippedOrders = orders.filter((order) => order.shipmentStatus === 'Terkirim').length;
    const roas = campaigns.length
      ? campaigns.reduce((total, campaign) => total + campaign.revenue, 0) /
        campaigns.reduce((total, campaign) => total + campaign.budget, 0)
      : 0;

    return (
      <div className="grid grid-cols-1 gap-6 xl:grid-cols-2">
        <CardBox className="border border-slate-100/80 dark:border-dark-700">
          <div className="mb-5 flex items-center justify-between">
            <div>
              <h2 className="text-xl font-semibold">Laporan Eksekutif</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">Snapshot performa commerce.</p>
            </div>
            <BaseButton
              label="Kunci Laporan"
              icon={resolveIcon('mdiFileChartOutline')}
              color="info"
              small
              disabled={isSavingCommerce}
              onClick={() => closeDailyReport()}
            />
          </div>
          <div className="space-y-4">
            <div className="flex items-center justify-between rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
              <span>Revenue lunas</span>
              <strong>{formatCurrency(metrics.paidRevenue)}</strong>
            </div>
            <div className="flex items-center justify-between rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
              <span>Paid orders</span>
              <strong>{paidOrders}/{orders.length}</strong>
            </div>
            <div className="flex items-center justify-between rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
              <span>Delivered orders</span>
              <strong>{shippedOrders}/{orders.length}</strong>
            </div>
            <div className="flex items-center justify-between rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
              <span>Marketing ROAS</span>
              <strong>{roas.toFixed(1)}x</strong>
            </div>
          </div>
        </CardBox>
        <CardBox className="border border-slate-100/80 dark:border-dark-700">
          <h2 className="text-xl font-semibold">API & Database Mapping</h2>
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
            MVP ini mengikuti struktur yang kamu minta dan siap dinaikkan ke Sequelize migration/API permanen.
          </p>
          <div className="mt-5 grid grid-cols-1 gap-3 text-sm md:grid-cols-2">
            {[
              'users',
              'products',
              'inventory',
              'customers',
              'orders',
              'payments',
              'shipping',
              'marketing',
              'reports',
              'dashboard',
            ].map((moduleName) => (
              <div key={moduleName} className="rounded-xl border border-slate-100 p-3 font-mono dark:border-dark-700">
                /api/{moduleName}
              </div>
            ))}
          </div>
        </CardBox>
      </div>
    );
  };

  const renderSettings = () => (
    <div className="grid grid-cols-1 gap-6 xl:grid-cols-2">
      <CardBox className="border border-slate-100/80 dark:border-dark-700">
        <h2 className="text-xl font-semibold">Pengaturan Toko</h2>
        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">Konfigurasi operasional aplikasi utama.</p>
        <div className="mt-5 space-y-4">
          <div className="rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
            <p className="text-sm text-gray-500 dark:text-gray-400">Nama toko</p>
            <p className="font-semibold">{displayStoreName}</p>
          </div>
          <div className="rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
            <p className="text-sm text-gray-500 dark:text-gray-400">Mata uang</p>
            <p className="font-semibold">{settings.currency}</p>
          </div>
          <div className="rounded-2xl bg-slate-50 p-4 dark:bg-dark-800">
            <p className="text-sm text-gray-500 dark:text-gray-400">Fulfillment mode</p>
            <div className="mt-2 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
              <p className="font-semibold">{settings.fulfillmentMode}</p>
              <BaseButton
                label="Toggle Mode"
                icon={resolveIcon('mdiSwapHorizontal')}
                color="info"
                small
                disabled={isSavingCommerce}
                onClick={() => toggleFulfillmentMode()}
              />
            </div>
          </div>
        </div>
      </CardBox>
      <CardBox className="border border-slate-100/80 dark:border-dark-700">
        <h2 className="text-xl font-semibold">Automation</h2>
        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">Kontrol rule otomatis untuk commerce operations.</p>
        <div className="mt-5 space-y-4">
          <div className="flex items-center justify-between rounded-2xl border border-slate-100 p-4 dark:border-dark-700">
            <div>
              <p className="font-semibold">Low stock alert</p>
              <p className="text-sm text-gray-500 dark:text-gray-400">Kirim peringatan saat SKU di bawah reorder point.</p>
            </div>
            <BaseButton
              label={settings.lowStockAlert ? 'Aktif' : 'Nonaktif'}
              color={settings.lowStockAlert ? 'success' : 'warning'}
              small
              disabled={isSavingCommerce}
              onClick={() => toggleBooleanSetting('lowStockAlert')}
            />
          </div>
          <div className="flex items-center justify-between rounded-2xl border border-slate-100 p-4 dark:border-dark-700">
            <div>
              <p className="font-semibold">Payment auto-capture</p>
              <p className="text-sm text-gray-500 dark:text-gray-400">Otomatis capture payment setelah callback gateway valid.</p>
            </div>
            <BaseButton
              label={settings.paymentAutoCapture ? 'Aktif' : 'Nonaktif'}
              color={settings.paymentAutoCapture ? 'success' : 'warning'}
              small
              disabled={isSavingCommerce}
              onClick={() => toggleBooleanSetting('paymentAutoCapture')}
            />
          </div>
        </div>
      </CardBox>
    </div>
  );

  const renderActiveTab = () => {
    if (activeTab === 'products') return renderProducts();
    if (activeTab === 'inventory') return renderInventory();
    if (activeTab === 'orders') return renderOrders();
    if (activeTab === 'customers') return renderCustomers();
    if (activeTab === 'payments') return renderPayments();
    if (activeTab === 'shipping') return renderShipping();
    if (activeTab === 'marketing') return renderMarketing();
    if (activeTab === 'reports') return renderReports();
    if (activeTab === 'settings') return renderSettings();

    return renderDashboard();
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('1. VORTA Commerce')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={resolveIcon('mdiStorefrontOutline')}
          title="1. VORTA Commerce"
          main
        >
          <BaseButton
            label={isSavingCommerce ? 'Menyimpan...' : isLoadingCommerce ? 'Memuat DB...' : 'Database Aktif'}
            icon={resolveIcon('mdiDatabaseCheckOutline')}
            color="success"
            small
            disabled
          />
        </SectionTitleLineWithButton>

        {commerceError ? (
          <div className="mb-4 rounded-2xl border border-red-200 bg-red-50 p-4 text-sm font-medium text-red-700 dark:border-red-900/40 dark:bg-red-900/20 dark:text-red-200">
            {commerceError}
          </div>
        ) : null}

        {(isLoadingCommerce || isSavingCommerce) ? (
          <div className="mb-4 rounded-2xl border border-blue-200 bg-blue-50 p-4 text-sm font-medium text-blue-700 dark:border-blue-900/40 dark:bg-blue-900/20 dark:text-blue-200">
            {isLoadingCommerce ? 'Memuat data VORTA Commerce dari database...' : 'Menyimpan perubahan ke database...'}
          </div>
        ) : null}

        <div className="mb-6 overflow-hidden rounded-3xl bg-gradient-to-r from-slate-950 via-blue-950 to-emerald-900 p-6 text-white shadow-xl">
          <div className="grid grid-cols-1 gap-6 xl:grid-cols-3">
            <div className="xl:col-span-2">
              <p className="text-sm font-semibold tracking-[0.35em] text-emerald-200">VORTA UNIVERSE • 1. VORTA Commerce</p>
              <h1 className="mt-3 text-3xl font-black md:text-5xl">Platform Perdagangan, Distribusi, Komunitas, dan Pembayaran Berbasis Kepercayaan.</h1>
              <p className="mt-4 max-w-3xl text-sm text-slate-200 md:text-base">
                VORTA Commerce adalah platform utama dalam ekosistem VORTA Universe yang menghubungkan pembeli, penjual, UMKM, kreator, perusahaan, komunitas, afiliator, dan mitra logistik melalui sistem perdagangan berbasis kepercayaan (Trust-Based Commerce). VORTA Commerce tidak hanya berfungsi sebagai marketplace, tetapi juga sebagai pusat aktivitas bisnis digital yang menggabungkan perdagangan, distribusi, afiliasi, logistik, komunikasi, komunitas, dan pembayaran dalam satu platform terpadu. Dengan dukungan VORTA Nexus Trust Score, setiap identitas, toko, produk, ulasan, transaksi, dan aktivitas komunitas memiliki tingkat kepercayaan yang dapat diukur dan diverifikasi.
              </p>
              <div className="mt-6 flex flex-wrap gap-2">
                <BaseButton
                  label="Buat Order Demo"
                  icon={resolveIcon('mdiCartPlus')}
                  color="success"
                  disabled={isSavingCommerce}
                  onClick={() => createFlashOrder()}
                />
                <BaseButton
                  label="Restock Cepat"
                  icon={resolveIcon('mdiPackageVariantPlus')}
                  color="info"
                  disabled={isSavingCommerce}
                  onClick={() => restockLowStock()}
                />
                <BaseButton
                  label="Buka Laporan"
                  icon={resolveIcon('mdiChartLine')}
                  color="whiteDark"
                  onClick={() => setActiveTab('reports')}
                />
              </div>
            </div>
            <div className="rounded-3xl border border-white/10 bg-white/10 p-5 backdrop-blur">
              <p className="text-sm text-slate-200">Operator</p>
              <p className="mt-1 text-xl font-bold">
                {currentUser?.firstName || currentUser?.email || 'Admin VORTA'}
              </p>
              <div className="mt-5 space-y-3 text-sm">
                <div className="flex justify-between"><span>Store</span><strong>{displayStoreName}</strong></div>
                <div className="flex justify-between"><span>Mode</span><strong>{settings.fulfillmentMode}</strong></div>
                <div className="flex justify-between"><span>Open orders</span><strong>{metrics.openOrders}</strong></div>
                <div className="flex justify-between"><span>Low stock</span><strong>{metrics.lowStockCount}</strong></div>
                <div className="flex justify-between"><span>Sync</span><strong>{persistedAt ? 'Persisten' : 'Lokal'}</strong></div>
              </div>
            </div>
          </div>
        </div>

        <CardBox className="mb-6 border border-slate-100/80 dark:border-dark-700">
          <div className="mb-5 flex flex-col gap-2 lg:flex-row lg:items-end lg:justify-between">
            <div>
              <p className="text-sm font-semibold tracking-[0.28em] text-blue-600 dark:text-blue-300">VORTA UNIVERSE</p>
              <h2 className="mt-2 text-2xl font-black text-slate-900 dark:text-white">Urutan menu utama dashboard</h2>
              <p className="mt-2 max-w-3xl text-sm text-gray-500 dark:text-gray-400">
                Semua tombol produk VORTA di dashboard mengikuti urutan 1 sampai 5 sesuai struktur ekosistem.
              </p>
            </div>
          </div>
          <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-5">
            {vortaUniverseOrder.map((item) => (
              <div
                key={item.number}
                className="flex h-full flex-col rounded-2xl border border-slate-100 bg-slate-50 p-4 dark:border-dark-700 dark:bg-dark-800"
              >
                <div className="mb-4 flex items-center justify-between gap-3">
                  <span className="grid h-10 w-10 place-items-center rounded-xl bg-blue-600 text-sm font-black text-white">
                    {item.number}
                  </span>
                  <BaseIcon path={resolveIcon(item.iconName)} className={iconsColor} size={24} />
                </div>
                <h3 className="text-lg font-black text-slate-900 dark:text-white">{item.title}</h3>
                <p className="mt-2 flex-1 text-sm leading-6 text-gray-500 dark:text-gray-400">{item.description}</p>
                <BaseButton
                  href={item.href}
                  label={`Buka ${item.title}`}
                  color={item.number === '1' ? 'info' : 'white'}
                  outline={item.number !== '1'}
                  small
                  className="mt-4 w-full"
                />
              </div>
            ))}
          </div>
        </CardBox>


        <CardBox className="mb-6 border border-emerald-100/80 dark:border-emerald-900/30">
          <div className="grid gap-6 xl:grid-cols-[0.9fr_1.1fr]">
            <div>
              <p className="text-sm font-semibold tracking-[0.28em] text-emerald-600 dark:text-emerald-300">1. VORTA Commerce</p>
              <h2 className="mt-2 text-2xl font-black text-slate-900 dark:text-white">
                Platform Perdagangan, Distribusi, Komunitas, dan Pembayaran Berbasis Kepercayaan
              </h2>
              <p className="mt-4 text-sm leading-7 text-gray-600 dark:text-gray-300">
                VORTA Commerce adalah platform utama dalam ekosistem VORTA Universe yang menghubungkan pembeli, penjual, UMKM, kreator, perusahaan, komunitas, afiliator, dan mitra logistik melalui sistem perdagangan berbasis kepercayaan (Trust-Based Commerce). VORTA Commerce tidak hanya berfungsi sebagai marketplace, tetapi juga sebagai pusat aktivitas bisnis digital yang menggabungkan perdagangan, distribusi, afiliasi, logistik, komunikasi, komunitas, dan pembayaran dalam satu platform terpadu. Dengan dukungan VORTA Nexus Trust Score, setiap identitas, toko, produk, ulasan, transaksi, dan aktivitas komunitas memiliki tingkat kepercayaan yang dapat diukur dan diverifikasi.
              </p>
              <div className="mt-5 rounded-2xl border border-emerald-100 bg-emerald-50 p-4 dark:border-emerald-900/40 dark:bg-emerald-900/20">
                <p className="text-xs font-black uppercase tracking-[0.22em] text-emerald-700 dark:text-emerald-200">Visi</p>
                <p className="mt-2 text-sm leading-7 text-emerald-900 dark:text-emerald-100">{commerceVision}</p>
              </div>
            </div>

            <div className="space-y-4">
              <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4 dark:border-dark-700 dark:bg-dark-800">
                <p className="text-xs font-black uppercase tracking-[0.22em] text-blue-600 dark:text-blue-300">Misi</p>
                <div className="mt-3 grid gap-2 sm:grid-cols-2">
                  {commerceMission.map((mission) => (
                    <div
                      key={mission}
                      className="rounded-xl border border-slate-100 bg-white px-3 py-2 text-sm text-slate-600 dark:border-dark-700 dark:bg-dark-900 dark:text-slate-300"
                    >
                      {mission}
                    </div>
                  ))}
                </div>
              </div>

              <div className="grid gap-3 md:grid-cols-2">
                {commercePillars.map((pillar, index) => (
                  <div
                    key={pillar.title}
                    className="rounded-2xl border border-slate-100 bg-white p-4 dark:border-dark-700 dark:bg-dark-900"
                  >
                    <div className="mb-3 flex items-start gap-3">
                      <span className="grid h-9 w-9 flex-none place-items-center rounded-xl bg-emerald-500 text-sm font-black text-white">
                        {index + 1}
                      </span>
                      <div>
                        <h3 className="font-black text-slate-900 dark:text-white">{pillar.title}</h3>
                        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">{pillar.description}</p>
                      </div>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      {pillar.features.map((feature) => (
                        <span
                          key={feature}
                          className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600 dark:bg-dark-800 dark:text-slate-300"
                        >
                          {feature}
                        </span>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </CardBox>

        <div className="mb-6 flex gap-2 overflow-x-auto pb-2">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              type="button"
              onClick={() => setActiveTab(tab.id)}
              className={`inline-flex flex-none items-center gap-2 rounded-2xl border px-4 py-2 text-sm font-semibold transition-colors ${
                activeTab === tab.id
                  ? 'border-blue-500 bg-blue-500 text-white shadow-sm'
                  : 'border-slate-200 bg-white text-slate-700 hover:border-blue-300 hover:text-blue-600 dark:border-dark-700 dark:bg-dark-900 dark:text-slate-200'
              }`}
            >
              <BaseIcon path={resolveIcon(tab.iconName)} size="18" />
              {tab.label}
            </button>
          ))}
        </div>

        {renderActiveTab()}
      </SectionMain>
    </>
  );
};

VortaCommercePage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default VortaCommercePage;
