import * as icon from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, 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;
};

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 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 [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 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 pushLedger = (title: string, detail: string, tone: LedgerItem['tone'] = 'info') => {
    setLedger((current) => [
      {
        id: `LOG-${Date.now()}`,
        title,
        detail,
        time: 'Baru saja',
        tone,
      },
      ...current,
    ].slice(0, 8));
  };

  const restockLowStock = () => {
    const lowStockProducts = products.filter((product) => product.stock <= product.reorderPoint);

    if (!lowStockProducts.length) {
      pushLedger('Inventori aman', 'Tidak ada produk di bawah reorder point saat ini.', 'success');
      return;
    }

    setProducts((current) =>
      current.map((product) =>
        product.stock <= product.reorderPoint
          ? { ...product, stock: product.stock + product.reorderPack }
          : product,
      ),
    );
    pushLedger(
      'Auto-restock dibuat',
      `${lowStockProducts.length} SKU masuk purchase order otomatis dari inventori.`,
      'success',
    );
  };

  const createFlashOrder = () => {
    const product = products.find((item) => item.id === 'SKU-BE-117') || products[0];
    const quantity = 3;

    if (product.stock < quantity) {
      pushLedger('Order gagal dibuat', `${product.name} tidak punya stok cukup.`, 'danger');
      return;
    }

    const orderNumber = orders.length + 24061;
    const paymentNumber = payments.length + 8801;
    const shipmentNumber = shipments.length + 7101;
    const total = product.price * quantity + 25000;
    const nextOrder: Order = {
      id: `ORD-${orderNumber}`,
      customerId: 'CUST-002',
      total,
      status: 'Baru',
      paymentStatus: 'Menunggu',
      shipmentStatus: 'Menunggu Pick Up',
      channel: 'Social Commerce',
      createdAt: 'Baru saja',
      items: [`${product.name} x${quantity}`],
    };

    setProducts((current) =>
      current.map((item) =>
        item.id === product.id
          ? { ...item, stock: item.stock - quantity, sold: item.sold + quantity }
          : item,
      ),
    );
    setOrders((current) => [nextOrder, ...current]);
    setPayments((current) => [
      {
        id: `PAY-${paymentNumber}`,
        orderId: nextOrder.id,
        method: 'QRIS',
        amount: total,
        status: 'Menunggu',
      },
      ...current,
    ]);
    setShipments((current) => [
      {
        id: `SHP-${shipmentNumber}`,
        orderId: nextOrder.id,
        destination: 'Bandung',
        courier: 'Vorta Express',
        eta: '6 jam',
        status: 'Menunggu Pick Up',
        risk: 'Rendah',
      },
      ...current,
    ]);
    setCustomers((current) =>
      current.map((customer) =>
        customer.id === 'CUST-002'
          ? {
              ...customer,
              orders: customer.orders + 1,
              lifetimeValue: customer.lifetimeValue + total,
            }
          : customer,
      ),
    );
    pushLedger('Flash order dibuat', `${nextOrder.id} dibuat dari Social Commerce.`, 'success');
  };

  const capturePayment = (paymentId: string) => {
    const payment = payments.find((item) => item.id === paymentId);

    if (!payment || payment.status === 'Berhasil') return;

    setPayments((current) =>
      current.map((item) => (item.id === paymentId ? { ...item, status: 'Berhasil' } : item)),
    );
    setOrders((current) =>
      current.map((order) =>
        order.id === payment.orderId
          ? { ...order, paymentStatus: 'Berhasil', status: order.status === 'Baru' ? 'Diproses' : order.status }
          : order,
      ),
    );
    pushLedger('Pembayaran sukses', `${payment.orderId} ditandai lunas via ${payment.method}.`, 'success');
  };

  const advanceOrder = (orderId: string) => {
    const order = orders.find((item) => item.id === orderId);

    if (!order) return;

    const nextStatus: Record<OrderStatus, OrderStatus> = {
      Baru: 'Diproses',
      Diproses: 'Dikirim',
      Dikirim: 'Selesai',
      Selesai: 'Selesai',
    };
    const next = nextStatus[order.status];

    setOrders((current) =>
      current.map((item) =>
        item.id === orderId
          ? {
              ...item,
              status: next,
              shipmentStatus:
                next === 'Dikirim' ? 'Dikirim' : next === 'Selesai' ? 'Terkirim' : item.shipmentStatus,
            }
          : item,
      ),
    );
    setShipments((current) =>
      current.map((shipment) =>
        shipment.orderId === orderId
          ? {
              ...shipment,
              status:
                next === 'Dikirim' ? 'Dikirim' : next === 'Selesai' ? 'Terkirim' : shipment.status,
            }
          : shipment,
      ),
    );
    pushLedger('Status pesanan diperbarui', `${orderId} berpindah ke status ${next}.`, 'info');
  };

  const completeShipment = (shipmentId: string) => {
    const shipment = shipments.find((item) => item.id === shipmentId);

    if (!shipment || shipment.status === 'Terkirim') return;

    setShipments((current) =>
      current.map((item) => (item.id === shipmentId ? { ...item, status: 'Terkirim', eta: 'Selesai' } : item)),
    );
    setOrders((current) =>
      current.map((order) =>
        order.id === shipment.orderId
          ? { ...order, status: 'Selesai', shipmentStatus: 'Terkirim' }
          : order,
      ),
    );
    pushLedger('Paket terkirim', `${shipment.orderId} selesai oleh ${shipment.courier}.`, 'success');
  };

  const launchCampaign = (campaignId: string) => {
    const campaign = campaigns.find((item) => item.id === campaignId);

    if (!campaign) return;

    setCampaigns((current) =>
      current.map((item) =>
        item.id === campaignId
          ? {
              ...item,
              status: 'Aktif',
              conversion: Number((item.conversion + 0.9).toFixed(1)),
              revenue: item.revenue + Math.round(item.budget * 2.4),
            }
          : item,
      ),
    );
    pushLedger('Campaign diluncurkan', `${campaign.name} aktif dengan budget ${formatCurrency(campaign.budget)}.`, 'success');
  };

  const closeDailyReport = () => {
    pushLedger(
      'Laporan harian dikunci',
      `${orders.length} pesanan, ${formatCurrency(metrics.paidRevenue)} revenue lunas, ${metrics.lowStockCount} SKU perlu perhatian.`,
      'info',
    );
  };

  const toggleFulfillmentMode = () => {
    setSettings((current) => ({
      ...current,
      fulfillmentMode: current.fulfillmentMode === 'Otomatis' ? 'Manual Review' : 'Otomatis',
    }));
    pushLedger('Pengaturan fulfillment berubah', 'Mode fulfillment toko diperbarui.', 'info');
  };

  const toggleBooleanSetting = (key: 'lowStockAlert' | 'paymentAutoCapture') => {
    setSettings((current) => ({ ...current, [key]: !current[key] }));
  };

  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 uppercase 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'}
                  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'}
                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'}
                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
              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">{settings.storeName}</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
                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
              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
              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('VORTA-COMMERCE')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={resolveIcon('mdiStorefrontOutline')}
          title="VORTA-COMMERCE"
          main
        >
          <BaseButton
            label="Aplikasi Utama"
            icon={resolveIcon('mdiStarFourPointsOutline')}
            color="success"
            small
            disabled
          />
        </SectionTitleLineWithButton>

        <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 uppercase tracking-[0.35em] text-emerald-200">Commerce Operating System</p>
              <h1 className="mt-3 text-3xl font-black md:text-5xl">Dashboard utama untuk produk, order, pembayaran, dan fulfillment.</h1>
              <p className="mt-4 max-w-3xl text-sm text-slate-200 md:text-base">
                MVP ini menyatukan frontend, API module, dan rancangan database VORTA-COMMERCE dalam satu command center yang langsung bisa diuji.
              </p>
              <div className="mt-6 flex flex-wrap gap-2">
                <BaseButton
                  label="Buat Order Demo"
                  icon={resolveIcon('mdiCartPlus')}
                  color="success"
                  onClick={() => createFlashOrder()}
                />
                <BaseButton
                  label="Restock Cepat"
                  icon={resolveIcon('mdiPackageVariantPlus')}
                  color="info"
                  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>{settings.storeName}</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>
            </div>
          </div>
        </div>

        <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;
