'use client'

import { useEffect, useState } from "react"
import Link from "next/link"
import { PageHeader } from "@/components/ui/page-header"
import { KpiCard } from "@/components/ui/kpi-card"
import { SectionCard } from "@/components/ui/section-card"
import { StatusBadge } from "@/components/ui/status-badge"
import { AvatarBadge } from "@/components/ui/avatar-badge"
import { Modal } from "@/components/ui/modal"
import {
  Wallet,
  Coins,
  Activity,
  PackageCheck,
  AlertTriangle,
  ChevronLeft,
  TrendingUp,
  Users,
  ShieldCheck,
  FileText,
  RefreshCw,
  Radio,
  Square,
} from "lucide-react"
import { formatDateTime, formatGold, formatMoney, formatNumber, timeAgo } from "@/lib/format"
import { useDashboard } from "@/hooks/useDashboard"
import { useMarketPrices } from "@/hooks/useMarketPrices"
import { useAuth } from "@/contexts/auth-context"
import type { MarketPriceRead, MarketPriceStatus } from "@/types"
import i18n from "@/lib/i18n";

const STATUS_LABEL: Record<string, { label: string; tone: "success" | "danger" | "processing" | "pending" | "warning" | "info" | "neutral" }> = {
  completed: { label: i18n.t('app.admin.page.text_1'), tone: "success" },
  pending: { label: i18n.t('app.admin.page.text_2'), tone: "pending" },
  failed: { label: i18n.t('app.admin.page.text_3'), tone: "danger" },
  incident: { label: i18n.t('app.admin.page.text_4'), tone: "warning" },
  cancelled: { label: i18n.t('app.admin.page.text_5'), tone: "neutral" },
  flagged: { label: i18n.t('app.admin.page.text_6'), tone: "danger" },
  successful: { label: i18n.t('app.admin.page.text_7'), tone: "success" },
  processing: { label: i18n.t('app.admin.page.text_8'), tone: "processing" },
  reserved: { label: i18n.t('app.admin.page.text_9'), tone: "info" },
  shipped: { label: i18n.t('app.admin.page.text_10'), tone: "processing" },
  delivered: { label: i18n.t('app.admin.page.text_11'), tone: "success" },
  blocked: { label: i18n.t('app.admin.page.text_12'), tone: "danger" },
}

const DISPLAY_STORAGE_KEY = "dashboard_display_preferences"

const DEFAULT_DISPLAY_CONFIG = {
  kpis: {
    totalAssets: true,
    goldCustody: true,
    cashWallets: true,
    ordersToday: true,
    pendingRedemptions: true,
    openAlerts: true,
  },
  sections: {
    liveGoldPrice: true,
    liveSilverPrice: true,
    riskAlerts: true,
    recentActivity: true,
    transfersAndRedemptions: true,
    quickLinks: true,
  },
}

type DisplayConfig = typeof DEFAULT_DISPLAY_CONFIG

function mergeDisplayConfig(value: unknown): DisplayConfig {
  if (!value || typeof value !== "object") return DEFAULT_DISPLAY_CONFIG
  const partial = value as Partial<DisplayConfig>

  return {
    kpis: { ...DEFAULT_DISPLAY_CONFIG.kpis, ...(partial.kpis || {}) },
    sections: { ...DEFAULT_DISPLAY_CONFIG.sections, ...(partial.sections || {}) },
  }
}

const MARKET_LABELS = {
  gold: "\u0633\u0639\u0631 \u0627\u0644\u0630\u0647\u0628 \u0627\u0644\u0645\u0628\u0627\u0634\u0631",
  silver: "\u0633\u0639\u0631 \u0627\u0644\u0641\u0636\u0629 \u0627\u0644\u0645\u0628\u0627\u0634\u0631",
  refreshNow: "\u062a\u062d\u062f\u064a\u062b \u0641\u0648\u0631\u064a",
  liveMode: "\u0627\u0644\u062a\u062d\u062f\u064a\u062b \u0627\u0644\u0645\u0628\u0627\u0634\u0631",
  lastSaved: "\u0622\u062e\u0631 \u0633\u0639\u0631 \u0645\u062d\u0641\u0648\u0638",
  stale: "\u0627\u0644\u0633\u0639\u0631 \u0642\u062f\u064a\u0645",
  failed: "\u0641\u0634\u0644 \u0627\u0644\u062a\u062d\u062f\u064a\u062b",
  rateLimited: "\u062a\u0645 \u062a\u062c\u0627\u0648\u0632 \u062d\u062f \u0627\u0644\u0637\u0644\u0628\u0627\u062a",
  noData: "\u0644\u0627 \u064a\u0648\u062c\u062f \u0633\u0639\u0631 \u0645\u062d\u0641\u0648\u0638",
  nextRefresh: "\u0627\u0644\u062a\u062d\u062f\u064a\u062b \u0627\u0644\u062a\u0627\u0644\u064a",
  remaining: "\u0627\u0644\u0637\u0644\u0628\u0627\u062a \u0627\u0644\u0645\u062a\u0628\u0642\u064a\u0629",
}

function marketStatusTone(status?: MarketPriceStatus | string): "success" | "danger" | "warning" | "info" | "neutral" {
  if (status === "success") return "success"
  if (status === "stale") return "warning"
  if (status === "rate_limited") return "danger"
  if (status === "failed") return "danger"
  return "neutral"
}

function marketStatusLabel(price?: MarketPriceRead | null) {
  if (!price) return MARKET_LABELS.lastSaved
  if (price.status === "rate_limited") return MARKET_LABELS.rateLimited
  if (price.status === "failed") return MARKET_LABELS.failed
  if (price.status === "no_data") return MARKET_LABELS.noData
  if (price.is_stale || price.status === "stale") return MARKET_LABELS.stale
  return "Fresh"
}

function MarketPriceCard({
  price,
  metal,
  meta,
}: {
  price?: MarketPriceRead
  metal: "gold" | "silver"
  meta: {
    remainingRequests: number
    nextAllowedManualRefreshAt?: string | null
    nextScheduledRefreshAt?: string | null
    liveModeEnabled: boolean
    liveModeExpiresAt?: string | null
  }
}) {
  const currency = price?.currency_code ?? "SAR"
  const isGold = metal === "gold"
  const title = isGold ? MARKET_LABELS.gold : MARKET_LABELS.silver
  const gramOne = isGold ? price?.price_gram : price?.price_gram
  const gramTwo = isGold ? undefined : price?.price_gram_925
  const gramThree = isGold ? undefined : price?.price_gram_900

  return (
    <SectionCard
      className={isGold ? "bg-gradient-to-br from-[#111218] to-[#1a1c25] text-white border-[#2a2d38]" : "bg-gradient-to-br from-[#101216] to-[#20242b] text-white border-[#343943]"}
      padded={false}
      title={<span className="text-white">{title}</span>}
      description={<span className="text-white/60">{price?.source_code || MARKET_LABELS.lastSaved}</span>}
      icon={<Coins className={isGold ? "h-5 w-5 text-gold-400" : "h-5 w-5 text-slate-200"} />}
      actions={
        <span className="inline-flex items-center gap-1.5">
          {meta.liveModeEnabled && (
            <StatusBadge tone="info" size="sm">
              Live
            </StatusBadge>
          )}
          <StatusBadge tone={marketStatusTone(price?.status)} size="sm">
            {marketStatusLabel(price)}
          </StatusBadge>
        </span>
      }
    >
      <div className="px-5 py-5">
        <div className="flex items-baseline gap-2">
          <span className="text-[34px] font-bold tracking-tight tabular-nums">{formatNumber(price?.mid_price ?? null, 2)}</span>
          <span className="text-[13px] text-white/60">{currency} / oz</span>
        </div>
        {(price?.is_stale || price?.status === "stale") && (
          <div className="mt-1 text-[11.5px] font-semibold text-amber-300">{MARKET_LABELS.lastSaved}</div>
        )}

        <div className="mt-4 grid grid-cols-3 gap-2">
          <div className="rounded-lg bg-white/5 border border-white/10 p-3">
            <div className="text-[10.5px] text-white/50 mb-1 uppercase tracking-wider">Bid</div>
            <div className="text-[15px] font-bold tabular-nums">{formatNumber(price?.bid_price ?? null, 2)}</div>
          </div>
          <div className="rounded-lg bg-white/5 border border-white/10 p-3">
            <div className="text-[10.5px] text-white/50 mb-1 uppercase tracking-wider">Ask</div>
            <div className="text-[15px] font-bold tabular-nums">{formatNumber(price?.ask_price ?? null, 2)}</div>
          </div>
          <div className={isGold ? "rounded-lg bg-gold-500/10 border border-gold-500/30 p-3" : "rounded-lg bg-slate-300/10 border border-slate-200/30 p-3"}>
            <div className={isGold ? "text-[10.5px] text-gold-400 mb-1 uppercase tracking-wider" : "text-[10.5px] text-slate-200 mb-1 uppercase tracking-wider"}>Gram</div>
            <div className={isGold ? "text-[15px] font-bold tabular-nums text-gold-400" : "text-[15px] font-bold tabular-nums text-slate-100"}>{formatNumber(gramOne ?? null, 4)}</div>
          </div>
        </div>

        {!isGold && (
          <div className="mt-2 grid grid-cols-2 gap-2">
            <div className="rounded-lg bg-white/5 border border-white/10 p-3">
              <div className="text-[10.5px] text-white/50 mb-1 uppercase tracking-wider">925</div>
              <div className="text-[14px] font-bold tabular-nums">{formatNumber(gramTwo ?? null, 4)}</div>
            </div>
            <div className="rounded-lg bg-white/5 border border-white/10 p-3">
              <div className="text-[10.5px] text-white/50 mb-1 uppercase tracking-wider">900</div>
              <div className="text-[14px] font-bold tabular-nums">{formatNumber(gramThree ?? null, 4)}</div>
            </div>
          </div>
        )}

        <div className="mt-5 pt-4 border-t border-white/10 space-y-2 text-[11.5px]">
          <div className="flex items-center justify-between gap-3">
            <span className="text-white/50">{i18n.t('app.admin.page.text_62')}</span>
            <span className="font-semibold text-white tabular-nums">{price?.last_successful_update_at ? formatDateTime(price.last_successful_update_at) : "—"}</span>
          </div>
          <div className="flex items-center justify-between gap-3">
            <span className="text-white/50">{MARKET_LABELS.remaining}</span>
            <span className="font-semibold text-white tabular-nums">{formatNumber(meta.remainingRequests, 0)}</span>
          </div>
          <div className="flex items-center justify-between gap-3">
            <span className="text-white/50">{MARKET_LABELS.nextRefresh}</span>
            <span className="font-semibold text-white tabular-nums">{meta.nextAllowedManualRefreshAt ? formatDateTime(meta.nextAllowedManualRefreshAt) : (meta.nextScheduledRefreshAt ? formatDateTime(meta.nextScheduledRefreshAt) : "—")}</span>
          </div>
          {meta.liveModeEnabled && (
            <div className="flex items-center justify-between gap-3">
              <span className="text-white/50">{MARKET_LABELS.liveMode}</span>
              <span className="font-semibold text-white tabular-nums">{meta.liveModeExpiresAt ? formatDateTime(meta.liveModeExpiresAt) : "—"}</span>
            </div>
          )}
        </div>
      </div>
    </SectionCard>
  )
}

export default function DashboardPage() {
  const { overview, isLoading, error, fetchOverview } = useDashboard()
  const { user } = useAuth()
  const {
    marketPrices,
    isLoadingMarketPrices,
    marketPriceError,
    fetchMarketPrices,
    refreshMarketPrices,
    startLiveMode,
    stopLiveMode,
  } = useMarketPrices()
  const [customizeOpen, setCustomizeOpen] = useState(false)
  const [displayConfig, setDisplayConfig] = useState<DisplayConfig>(DEFAULT_DISPLAY_CONFIG)
  const roleCodes = new Set((user?.roles ?? []).map((role) => role.code))
  const permissionCodes = new Set(user?.permissions ?? [])
  const isSuperAdmin = roleCodes.has("super_admin")
  const canReadMarketPrices = isSuperAdmin || permissionCodes.has("market_prices:read")
  const canRefreshMarketPrices = isSuperAdmin || permissionCodes.has("market_prices:refresh")
  const canManageLiveMode = isSuperAdmin || permissionCodes.has("market_prices:live_mode")

  useEffect(() => {
    fetchOverview()
  }, [fetchOverview])

  useEffect(() => {
    if (canReadMarketPrices) {
      fetchMarketPrices()
    }
  }, [canReadMarketPrices, fetchMarketPrices])

  useEffect(() => {
    try {
      const stored = localStorage.getItem(DISPLAY_STORAGE_KEY)
      if (stored) {
        setDisplayConfig(mergeDisplayConfig(JSON.parse(stored)))
      }
    } catch {
      localStorage.removeItem(DISPLAY_STORAGE_KEY)
    }
  }, [])

  function saveDisplayConfig(next: DisplayConfig) {
    setDisplayConfig(next)
    localStorage.setItem(DISPLAY_STORAGE_KEY, JSON.stringify(next))
  }

  function toggleKpi(key: keyof DisplayConfig["kpis"]) {
    saveDisplayConfig({
      ...displayConfig,
      kpis: {
        ...displayConfig.kpis,
        [key]: !displayConfig.kpis[key],
      },
    })
  }

  function toggleSection(key: keyof DisplayConfig["sections"]) {
    saveDisplayConfig({
      ...displayConfig,
      sections: {
        ...displayConfig.sections,
        [key]: !displayConfig.sections[key],
      },
    })
  }

  function resetDisplayConfig() {
    saveDisplayConfig(DEFAULT_DISPLAY_CONFIG)
  }

  if (isLoading && !overview) {
    return (
      <div className="flex h-[50vh] items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
          <p className="text-sm text-muted-foreground">{i18n.t('app.admin.page.text_51')}</p>
        </div>
      </div>
    )
  }

  if (error && !overview) {
    return (
      <div className="flex h-[50vh] items-center justify-center">
        <div className="flex flex-col items-center gap-4 text-center">
          <AlertTriangle className="h-10 w-10 text-red-500" />
          <p className="text-base font-semibold text-red-500">{i18n.t('app.admin.page.text_52')}</p>
          <p className="text-sm text-muted-foreground max-w-md">{error}</p>
          <button 
            onClick={() => fetchOverview()}
            className="mt-4 h-9 px-4 rounded-lg bg-gold-500 hover:bg-gold-600 text-white text-[12.5px] font-semibold transition"
          >
            {i18n.t('app.admin.page.text_53')}</button>
        </div>
      </div>
    )
  }

  const customersCount = overview?.total_customers ?? 0
  const activeCustomers = overview?.active_customers ?? 0
  const ordersTodayCount = overview?.total_orders_today ?? 0
  const pendingRedemptions = overview?.pending_redemptions ?? 0
  const openAlerts = overview?.open_alerts ?? 0
  const cashAvailable = Number(overview?.cash_available ?? 0)
  const cashHeld = Number(overview?.cash_held ?? 0)
  const goldAvailable = Number(overview?.gold_available ?? 0)
  const goldHeld = Number(overview?.gold_held ?? 0)
  const spotPrice = Number(overview?.spot_price ?? 0)
  const spotDelta = Number(overview?.spot_delta ?? 0)
  const spotPct = Number(overview?.spot_pct ?? 0)
  const silverSpotPrice = Number(overview?.silver_spot_price ?? 0)
  const silverDelta = Number(overview?.silver_delta ?? 0)
  const silverPct = Number(overview?.silver_pct ?? 0)
  const currentCurrency = overview?.currency ?? "USD"

  const latestPriceData = overview ? {
    spot_price: Number(overview.spot_price),
    buy_price: Number(overview.buy_price),
    sell_price: Number(overview.sell_price),
    spread_bps: Number(overview.spread_bps),
    source: overview.price_source,
    captured_at: overview.price_updated_at,
  } : {
    spot_price: 0,
    buy_price: 0,
    sell_price: 0,
    spread_bps: 0,
    source: "",
    captured_at: "",
  }

  const latestSilverPriceData = overview ? {
    spot_price: Number(overview.silver_spot_price ?? 0),
    bid_price: Number(overview.silver_bid_price ?? 0),
    ask_price: Number(overview.silver_ask_price ?? 0),
    source: overview.silver_price_source,
    captured_at: overview.silver_price_updated_at,
    currency: overview.silver_currency || currentCurrency,
  } : {
    spot_price: 0,
    bid_price: 0,
    ask_price: 0,
    source: "",
    captured_at: "",
    currency: currentCurrency,
  }

  const recentOrders = [...(overview?.recent_orders ?? [])].sort((a: any, b: any) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
  const recentTransfers = overview?.recent_transfers ?? []
  const recentRedemptions = overview?.recent_redemptions ?? []
  const alerts = [...(overview?.alerts ?? [])].sort((a: any, b: any) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())

  const combinedTransfersAndRedemptions = [
    ...recentTransfers.map((t: any) => ({ ...t, _type: 'transfer', _date: new Date(t.initiated_at).getTime() })),
    ...recentRedemptions.map((r: any) => ({ ...r, _type: 'redemption', _date: new Date(r.requested_at).getTime() }))
  ].sort((a, b) => b._date - a._date).slice(0, 5)

  const goldOz = (goldAvailable + goldHeld) / 31.1035
  const totalAssets = cashAvailable + cashHeld + (goldAvailable + goldHeld) * spotPrice
  const criticalInv = 0

  const kpis = [
    {
      key: "totalAssets" as const,
      label: i18n.t('app.admin.page.text_13'),
      value: formatMoney(totalAssets, currentCurrency),
      unit: currentCurrency,
      hint: i18n.t('app.admin.page.text_14'),
      icon: Wallet,
      tone: "gold" as const,
      accent: true,
    },
    {
      key: "goldCustody" as const,
      label: i18n.t('app.admin.page.text_15'),
      value: formatNumber(goldOz, 0),
      unit: i18n.t('app.admin.page.text_16'),
      hint: i18n.t('app.admin.page.text_17'),
      icon: Coins,
      tone: "gold" as const,
    },
    {
      key: "cashWallets" as const,
      label: i18n.t('app.admin.page.text_18'),
      value: formatMoney(cashAvailable, currentCurrency),
      unit: i18n.t('app.admin.page.text_19'),
      hint: i18n.t('app.admin.page.text_held', { amount: formatMoney(cashHeld, currentCurrency) }),
      icon: Wallet,
      tone: "info" as const,
    },
    {
      key: "ordersToday" as const,
      label: i18n.t('app.admin.page.text_20'),
      value: formatNumber(ordersTodayCount, 0),
      hint: i18n.t('app.admin.page.text_21'),
      icon: Activity,
      tone: "success" as const,
    },
    {
      key: "pendingRedemptions" as const,
      label: i18n.t('app.admin.page.text_22'),
      value: formatNumber(pendingRedemptions, 0),
      hint: i18n.t('app.admin.page.text_23'),
      icon: PackageCheck,
      tone: "warning" as const,
    },
    {
      key: "openAlerts" as const,
      label: i18n.t('app.admin.page.text_24'),
      value: formatNumber(openAlerts, 0),
      hint: i18n.t('app.admin.page.text_25'),
      icon: AlertTriangle,
      tone: "danger" as const,
    },
  ]

  const visibleKpis = kpis.filter((k) => displayConfig.kpis[k.key])
  const kpiOptions = kpis.map((k) => ({ key: k.key, label: k.label }))
  const sectionOptions: { key: keyof DisplayConfig["sections"]; label: string }[] = [
    { key: "liveGoldPrice", label: i18n.t('app.admin.page.text_56') },
    { key: "liveSilverPrice", label: "سعر الفضة المباشر" },
    { key: "riskAlerts", label: i18n.t('app.admin.page.text_30') },
    { key: "recentActivity", label: i18n.t('app.admin.page.text_39') },
    { key: "transfersAndRedemptions", label: i18n.t('app.admin.page.text_43') },
    { key: "quickLinks", label: i18n.t('app.admin.page.text_75') },
  ]
  const visiblePriceCards = canReadMarketPrices ? Number(displayConfig.sections.liveGoldPrice) + Number(displayConfig.sections.liveSilverPrice) : 0
  const riskAlertsClassName = visiblePriceCards === 0 ? "lg:col-span-4" : visiblePriceCards === 1 ? "lg:col-span-3" : "lg:col-span-2"
  const marketGoldPrice = marketPrices?.prices.find((price) => price.metal_type === "gold")
  const marketSilverPrice = marketPrices?.prices.find((price) => price.metal_type === "silver")
  const marketPriceMeta = {
    remainingRequests: marketPrices?.remaining_requests ?? 0,
    nextAllowedManualRefreshAt: marketPrices?.next_allowed_manual_refresh_at,
    nextScheduledRefreshAt: marketPrices?.next_scheduled_refresh_at,
    liveModeEnabled: Boolean(marketPrices?.live_mode.enabled),
    liveModeExpiresAt: marketPrices?.live_mode.expires_at,
  }

  return (
    <>
      <PageHeader
        title={i18n.t('app.admin.page.text_26')}
        description={i18n.t('app.admin.page.text_27')}
        badge={
          <span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 px-2.5 py-1 text-[11px] font-semibold">
            <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
            {i18n.t('app.admin.page.text_54')}</span>
        }
        actions={
          <>
            <button
              type="button"
              onClick={() => setCustomizeOpen(true)}
              className="h-9 px-4 rounded-lg border border-border bg-card text-[12.5px] font-medium text-foreground hover:bg-muted transition"
            >
              {i18n.t('app.admin.page.text_55')}</button>
            {canRefreshMarketPrices && (
              <button
                type="button"
                onClick={() => refreshMarketPrices()}
                disabled={isLoadingMarketPrices}
                className="h-9 px-4 rounded-lg bg-gold-500 hover:bg-gold-600 disabled:opacity-50 text-white text-[12.5px] font-semibold shadow-sm transition inline-flex items-center gap-1.5"
              >
                <RefreshCw className={`h-3.5 w-3.5 ${isLoadingMarketPrices ? "animate-spin" : ""}`} />
                {MARKET_LABELS.refreshNow}
              </button>
            )}
            {canManageLiveMode && marketPrices?.live_mode.enabled && (
              <button
                type="button"
                onClick={() => stopLiveMode()}
                disabled={isLoadingMarketPrices}
                className="h-9 px-3 rounded-lg border border-red-200 bg-red-50 text-[12.5px] font-semibold text-red-700 hover:bg-red-100 disabled:opacity-50 transition inline-flex items-center gap-1.5"
              >
                <Square className="h-3.5 w-3.5" />
                Stop Live
              </button>
            )}
            {canManageLiveMode && !marketPrices?.live_mode.enabled && (
              <button
                type="button"
                onClick={() => startLiveMode({ interval_seconds: 300, duration_minutes: 15 })}
                disabled={isLoadingMarketPrices}
                className="h-9 px-3 rounded-lg border border-emerald-200 bg-emerald-50 text-[12.5px] font-semibold text-emerald-700 hover:bg-emerald-100 disabled:opacity-50 transition inline-flex items-center gap-1.5"
              >
                <Radio className="h-3.5 w-3.5" />
                {MARKET_LABELS.liveMode}
              </button>
            )}
          </>
        }
      />

      <Modal
        open={customizeOpen}
        onClose={() => setCustomizeOpen(false)}
        title={i18n.t('app.admin.page.text_76')}
        description={i18n.t('app.admin.page.text_77')}
        size="md"
        footer={
          <>
            <button
              type="button"
              onClick={resetDisplayConfig}
              className="h-9 px-4 rounded-lg border border-border bg-card text-[12.5px] font-semibold text-foreground hover:bg-muted transition"
            >
              {i18n.t('app.admin.page.text_78')}
            </button>
            <button
              type="button"
              onClick={() => setCustomizeOpen(false)}
              className="h-9 px-4 rounded-lg bg-gold-500 hover:bg-gold-600 text-white text-[12.5px] font-semibold shadow-sm transition"
            >
              {i18n.t('app.admin.page.text_79')}
            </button>
          </>
        }
      >
        <div className="space-y-5">
          <div>
            <h3 className="text-[13px] font-bold text-foreground mb-2">{i18n.t('app.admin.page.text_80')}</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
              {kpiOptions.map((item) => (
                <label key={item.key} className="flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-[12.5px] font-medium text-foreground">
                  <input
                    type="checkbox"
                    checked={displayConfig.kpis[item.key]}
                    onChange={() => toggleKpi(item.key)}
                    className="h-4 w-4 rounded border-border accent-gold-500"
                  />
                  {item.label}
                </label>
              ))}
            </div>
          </div>

          <div>
            <h3 className="text-[13px] font-bold text-foreground mb-2">{i18n.t('app.admin.page.text_81')}</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
              {sectionOptions.map((item) => (
                <label key={item.key} className="flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-[12.5px] font-medium text-foreground">
                  <input
                    type="checkbox"
                    checked={displayConfig.sections[item.key]}
                    onChange={() => toggleSection(item.key)}
                    className="h-4 w-4 rounded border-border accent-gold-500"
                  />
                  {item.label}
                </label>
              ))}
            </div>
          </div>
        </div>
      </Modal>

      {visibleKpis.length > 0 && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-3">
          {visibleKpis.map(({ key, ...k }) => (
            <KpiCard key={key} {...k} />
          ))}
        </div>
      )}

      {marketPriceError && canReadMarketPrices && (
        <div className="mt-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-[12.5px] font-medium text-amber-800">
          {marketPriceError}
        </div>
      )}

      {((canReadMarketPrices && (displayConfig.sections.liveGoldPrice || displayConfig.sections.liveSilverPrice)) || displayConfig.sections.riskAlerts) && (
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-4 mt-4">
          {canReadMarketPrices && displayConfig.sections.liveGoldPrice && (
            <MarketPriceCard price={marketGoldPrice} metal="gold" meta={marketPriceMeta} />
          )}

          {canReadMarketPrices && displayConfig.sections.liveSilverPrice && (
            <MarketPriceCard price={marketSilverPrice} metal="silver" meta={marketPriceMeta} />
          )}

          {false && displayConfig.sections.liveGoldPrice && (
            <SectionCard
              className="bg-gradient-to-br from-[#111218] to-[#1a1c25] text-white border-[#2a2d38]"
              padded={false}
              title={<span className="text-white">{i18n.t('app.admin.page.text_56')}</span>}
              description={<span className="text-white/60">{latestPriceData?.source ?? "â€”"}</span>}
              icon={<Coins className="h-5 w-5 text-gold-400" />}
              actions={
                <span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 px-2 py-0.5 text-[10.5px] font-semibold">
                  <span className="h-1.5 w-1.5 rounded-full bg-emerald-400 animate-pulse" />
                  {i18n.t('app.admin.page.text_57')}</span>
              }
            >
              <div className="px-5 py-5">
                <div className="flex items-baseline gap-2">
                  <span className="text-[36px] font-bold tracking-tight tabular-nums">{formatNumber(spotPrice, 2)}</span>
                  <span className="text-[13px] text-white/60">{overview?.currency ?? "USD"} / oz</span>
                </div>
                <div className={`mt-1 flex items-center gap-2 text-[12.5px] font-semibold tabular-nums ${spotDelta >= 0 ? "text-emerald-400" : "text-red-400"}`}>
                  <TrendingUp className={`h-4 w-4 ${spotDelta < 0 ? "rotate-180" : ""}`} />
                  {spotDelta >= 0 ? "+" : ""}
                  {formatNumber(spotDelta, 2)} ({formatNumber(spotPct, 2)}%)
                </div>

                <div className="mt-5 grid grid-cols-3 gap-3">
                  <div className="rounded-lg bg-white/5 border border-white/10 p-3">
                    <div className="text-[10.5px] text-white/50 mb-1 uppercase tracking-wider">{i18n.t('app.admin.page.text_58')}</div>
                    <div className="text-[16px] font-bold tabular-nums">{formatNumber(overview?.price_gram_24k ?? 0, 4)}</div>
                    <div className="text-[10px] text-white/40 mt-1">{overview?.currency ?? "USD"}</div>
                  </div>
                  <div className="rounded-lg bg-white/5 border border-white/10 p-3">
                    <div className="text-[10.5px] text-white/50 mb-1 uppercase tracking-wider">{i18n.t('app.admin.page.text_59')}</div>
                    <div className="text-[16px] font-bold tabular-nums">{formatNumber(overview?.price_gram_22k ?? 0, 4)}</div>
                    <div className="text-[10px] text-white/40 mt-1">{overview?.currency ?? "USD"}</div>
                  </div>
                  <div className="rounded-lg bg-gold-500/10 border border-gold-500/30 p-3">
                    <div className="text-[10.5px] text-gold-400 mb-1 uppercase tracking-wider">{i18n.t('app.admin.page.text_60')}</div>
                    <div className="text-[16px] font-bold tabular-nums text-gold-400">{formatNumber(overview?.price_gram_21k ?? 0, 4)}</div>
                    <div className="text-[10px] text-gold-500/60 mt-1">{overview?.currency ?? "USD"}</div>
                  </div>
                </div>

                <div className="mt-5 pt-4 border-t border-white/10">
                  <div className="flex items-center justify-between text-[11.5px]">
                    <div>
                      <div className="text-white/50">{i18n.t('app.admin.page.text_61')}</div>
                      <div className="font-semibold text-white mt-0.5">{latestPriceData?.source ?? "â€”"}</div>
                    </div>
                    <div className="text-left">
                      <div className="text-white/50">{i18n.t('app.admin.page.text_62')}</div>
                      <div className="font-semibold text-white mt-0.5 tabular-nums">
                        {latestPriceData ? formatDateTime(latestPriceData.captured_at) : "â€”"}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </SectionCard>
          )}

          {false && displayConfig.sections.liveSilverPrice && (
            <SectionCard
              className="bg-gradient-to-br from-[#101216] to-[#20242b] text-white border-[#343943]"
              padded={false}
              title={<span className="text-white">سعر الفضة المباشر</span>}
              description={<span className="text-white/60">{latestSilverPriceData?.source ?? "—"}</span>}
              icon={<Coins className="h-5 w-5 text-slate-200" />}
              actions={
                <span className="inline-flex items-center gap-1.5 rounded-full bg-cyan-500/15 text-cyan-300 border border-cyan-500/30 px-2 py-0.5 text-[10.5px] font-semibold">
                  <span className="h-1.5 w-1.5 rounded-full bg-cyan-300 animate-pulse" />
                  مباشر
                </span>
              }
            >
              <div className="px-5 py-5">
                <div className="flex items-baseline gap-2">
                  <span className="text-[36px] font-bold tracking-tight tabular-nums">{formatNumber(silverSpotPrice, 2)}</span>
                  <span className="text-[13px] text-white/60">{latestSilverPriceData?.currency ?? currentCurrency} / oz</span>
                </div>
                <div className={`mt-1 flex items-center gap-2 text-[12.5px] font-semibold tabular-nums ${silverDelta >= 0 ? "text-emerald-400" : "text-red-400"}`}>
                  <TrendingUp className={`h-4 w-4 ${silverDelta < 0 ? "rotate-180" : ""}`} />
                  {silverDelta >= 0 ? "+" : ""}
                  {formatNumber(silverDelta, 2)} ({formatNumber(silverPct, 2)}%)
                </div>

                <div className="mt-5 grid grid-cols-3 gap-3">
                  <div className="rounded-lg bg-white/5 border border-white/10 p-3">
                    <div className="text-[10.5px] text-white/50 mb-1 uppercase tracking-wider">جرام 999</div>
                    <div className="text-[16px] font-bold tabular-nums">{formatNumber(overview?.silver_price_gram ?? 0, 4)}</div>
                    <div className="text-[10px] text-white/40 mt-1">{latestSilverPriceData?.currency ?? currentCurrency}</div>
                  </div>
                  <div className="rounded-lg bg-white/5 border border-white/10 p-3">
                    <div className="text-[10.5px] text-white/50 mb-1 uppercase tracking-wider">جرام 925</div>
                    <div className="text-[16px] font-bold tabular-nums">{formatNumber(overview?.silver_price_gram_925 ?? 0, 4)}</div>
                    <div className="text-[10px] text-white/40 mt-1">{latestSilverPriceData?.currency ?? currentCurrency}</div>
                  </div>
                  <div className="rounded-lg bg-slate-300/10 border border-slate-200/30 p-3">
                    <div className="text-[10.5px] text-slate-200 mb-1 uppercase tracking-wider">جرام 900</div>
                    <div className="text-[16px] font-bold tabular-nums text-slate-100">{formatNumber(overview?.silver_price_gram_900 ?? 0, 4)}</div>
                    <div className="text-[10px] text-slate-200/60 mt-1">{latestSilverPriceData?.currency ?? currentCurrency}</div>
                  </div>
                </div>

                <div className="mt-5 pt-4 border-t border-white/10">
                  <div className="flex items-center justify-between text-[11.5px]">
                    <div>
                      <div className="text-white/50">{i18n.t('app.admin.page.text_61')}</div>
                      <div className="font-semibold text-white mt-0.5">{latestSilverPriceData?.source ?? "—"}</div>
                    </div>
                    <div className="text-left">
                      <div className="text-white/50">{i18n.t('app.admin.page.text_62')}</div>
                      <div className="font-semibold text-white mt-0.5 tabular-nums">
                        {latestSilverPriceData?.captured_at ? formatDateTime(latestSilverPriceData.captured_at) : "—"}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </SectionCard>
          )}

          {displayConfig.sections.riskAlerts && (
            <SectionCard
              className={riskAlertsClassName}
              title={i18n.t('app.admin.page.text_30')}
              description={i18n.t('app.admin.page.text_31')}
              icon={<AlertTriangle className="h-5 w-5 text-amber-600" />}
              actions={
                <Link href="/risk-aml" className="text-[12px] font-semibold text-gold-600 hover:text-gold-700">
                  {i18n.t('app.admin.page.text_63')}</Link>
              }
              padded={false}
            >
              {alerts.length === 0 ? (
                <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.page.text_64')}</div>
              ) : (
                <ul className="divide-y divide-border">
                  {alerts.map((a: any) => (
                    <li key={a.alert_code} className="flex items-start gap-3 px-5 py-3.5 hover:bg-muted/30 transition">
                      <div className="mt-0.5">
                        <StatusBadge
                          tone={
                            a.severity === "critical" || a.severity === "high"
                              ? "danger"
                              : a.severity === "medium"
                                ? "warning"
                                : "info"
                          }
                          size="sm"
                          dot
                        >
                          {a.severity === "critical" ? i18n.t('app.admin.page.text_32') : a.severity === "high" ? i18n.t('app.admin.page.text_33') : a.severity === "medium" ? i18n.t('app.admin.page.text_34') : i18n.t('app.admin.page.text_35')}
                        </StatusBadge>
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="text-[13px] font-semibold text-foreground">{a.rule_name}</div>
                        <div className="text-[12px] text-muted-foreground leading-relaxed mt-0.5">
                          {a.alert_code} â€” {a.status === "open" ? i18n.t('app.admin.page.text_36') : a.status === "under_review" ? i18n.t('app.admin.page.text_37') : i18n.t('app.admin.page.text_38')}
                        </div>
                      </div>
                      <span className="text-[11px] text-muted-foreground shrink-0 whitespace-nowrap">{timeAgo(a.created_at)}</span>
                    </li>
                  ))}
                </ul>
              )}
            </SectionCard>
          )}
        </div>
      )}

      {(displayConfig.sections.recentActivity || displayConfig.sections.transfersAndRedemptions) && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mt-4">
          {displayConfig.sections.recentActivity && (
            <SectionCard
              className={displayConfig.sections.transfersAndRedemptions ? "lg:col-span-2" : "lg:col-span-3"}
              title={i18n.t('app.admin.page.text_39')}
              description={i18n.t('app.admin.page.text_40')}
              actions={
                <Link href="/orders" className="inline-flex items-center gap-1 text-[12px] font-semibold text-gold-600 hover:text-gold-700">
                  {i18n.t('app.admin.page.text_65')}<ChevronLeft className="h-3.5 w-3.5" />
                </Link>
              }
              padded={false}
            >
              {recentOrders.length === 0 ? (
                <div className="px-5 py-8 text-center text-[12.5px] text-muted-foreground">{i18n.t('app.admin.page.text_66')}</div>
              ) : (
                <table className="w-full text-right">
                  <thead>
                    <tr className="border-b border-border bg-muted/30">
                      <th className="px-5 py-2.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.page.text_67')}</th>
                      <th className="px-4 py-2.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.page.text_68')}</th>
                      <th className="px-4 py-2.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.page.text_69')}</th>
                      <th className="px-4 py-2.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.page.text_70')}</th>
                      <th className="px-4 py-2.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.page.text_71')}</th>
                      <th className="px-4 py-2.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">{i18n.t('app.admin.page.text_72')}</th>
                      <th className="px-5 py-2.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground text-left">{i18n.t('app.admin.page.text_73')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {recentOrders.map((o: any) => {
                      const st = STATUS_LABEL[o.status] ?? { label: o.status, tone: "neutral" as const }
                      return (
                        <tr key={o.order_code} className="border-b border-border/70 hover:bg-muted/30 transition">
                          <td className="px-5 py-3">
                            <span className="text-[12.5px] font-semibold text-gold-700 tabular-nums">{o.order_code}</span>
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-2.5">
                              <AvatarBadge name={o.customers?.name ?? ""} size="sm" />
                              <span className="text-[12.5px] font-medium text-foreground">{o.customers?.name ?? "â€”"}</span>
                            </div>
                          </td>
                          <td className="px-4 py-3 text-[12.5px] text-muted-foreground">{o.side === "buy" ? i18n.t('app.admin.page.text_41') : i18n.t('app.admin.page.text_42')}</td>
                          <td className="px-4 py-3">
                            <span className="text-[12.5px] font-semibold text-foreground tabular-nums">{formatGold(Number(o.quantity) / 31.1035)}</span>
                          </td>
                          <td className="px-4 py-3 text-[12.5px] tabular-nums">{formatMoney(o.total_amount)}</td>
                          <td className="px-4 py-3">
                            <StatusBadge tone={st.tone} size="sm">
                              {st.label}
                            </StatusBadge>
                          </td>
                          <td className="px-5 py-3 text-[12px] text-muted-foreground tabular-nums text-left">{timeAgo(o.created_at)}</td>
                        </tr>
                      )
                    })}
                  </tbody>
                </table>
              )}
            </SectionCard>
          )}

          {displayConfig.sections.transfersAndRedemptions && (
            <SectionCard
              className={displayConfig.sections.recentActivity ? undefined : "lg:col-span-3"}
              title={i18n.t('app.admin.page.text_43')}
              description={i18n.t('app.admin.page.text_44')}
              icon={<ShieldCheck className="h-5 w-5 text-gold-600" />}
            >
              {combinedTransfersAndRedemptions.length === 0 ? (
                <p className="text-[13px] text-muted-foreground text-center py-8">{i18n.t('app.admin.page.text_74')}</p>
              ) : (
                <ul className="space-y-3">
                  {combinedTransfersAndRedemptions.map((item: any) => {
                    if (item._type === 'transfer') {
                      const st = STATUS_LABEL[item.status] ?? { label: item.status, tone: "neutral" as const }
                      return (
                        <li key={`transfer-${item.transfer_code}`} className="rounded-lg border border-border p-3">
                          <div className="flex items-start justify-between mb-1">
                            <div className="text-[13px] font-semibold text-foreground">{item.transfer_code}</div>
                            <StatusBadge tone={st.tone} size="sm">
                              {st.label}
                            </StatusBadge>
                          </div>
                          <div className="text-[11.5px] text-muted-foreground">
                            {item.sender?.name ?? "â€”"} â€¢ {formatNumber(item.quantity, 2)}
                          </div>
                          <div className="text-[10.5px] text-muted-foreground mt-1">{timeAgo(item.initiated_at)}</div>
                        </li>
                      )
                    } else {
                      const st = STATUS_LABEL[item.status] ?? { label: item.status, tone: "neutral" as const }
                      return (
                        <li key={`redemption-${item.code}`} className="rounded-lg border border-border p-3">
                          <div className="flex items-start justify-between mb-1">
                            <div className="text-[13px] font-semibold text-foreground">{item.code}</div>
                            <StatusBadge tone={st.tone} size="sm">
                              {st.label}
                            </StatusBadge>
                          </div>
                          <div className="text-[11.5px] text-muted-foreground">
                            {item.customers?.name ?? "â€”"} â€¢ {item.product_name}
                          </div>
                          <div className="text-[10.5px] text-muted-foreground mt-1">{timeAgo(item.requested_at)}</div>
                        </li>
                      )
                    }
                  })}
                </ul>
              )}
            </SectionCard>
          )}
        </div>
      )}

      {displayConfig.sections.quickLinks && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-4">
          {[
            { title: i18n.t('app.admin.page.text_45'), value: formatNumber(customersCount, 0), icon: Users, href: "/customers", desc: i18n.t('app.admin.page.text_active', { count: activeCustomers }) },
            { title: i18n.t('app.admin.page.text_46'), value: "0", icon: ShieldCheck, href: "/kyc", desc: i18n.t('app.admin.page.text_47') },
            { title: i18n.t('app.admin.page.text_48'), value: formatNumber(criticalInv, 0), icon: FileText, href: "/inventory", desc: i18n.t('app.admin.page.text_49') },
            { title: i18n.t('app.admin.page.text_50'), value: formatMoney(spotPrice, currentCurrency), icon: TrendingUp, href: "/pricing", desc: `${spotDelta >= 0 ? "+" : ""}${formatNumber(spotPct, 2)}%` },
          ].map((x) => (
            <Link
              key={x.title}
              href={x.href}
              className="group rounded-xl border border-border bg-card p-4 flex items-center gap-3 hover:border-gold-300 hover:shadow-sm transition"
            >
              <div className="flex h-11 w-11 items-center justify-center rounded-lg bg-gold-50 text-gold-700 group-hover:bg-gold-100 transition">
                <x.icon className="h-5 w-5" strokeWidth={1.75} />
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-[11.5px] text-muted-foreground">{x.title}</div>
                <div className="text-[18px] font-bold text-foreground tabular-nums leading-tight">{x.value}</div>
                <div className="text-[10.5px] text-muted-foreground">{x.desc}</div>
              </div>
              <ChevronLeft className="h-4 w-4 text-muted-foreground group-hover:text-gold-600 transition" />
            </Link>
          ))}
        </div>
      )}

    </>
  )
}
