بلاک‌ها · پنل مدیریت
ری‌اکت ۱۹ و Next.js با پیاده‌سازی دسترس‌پذیری داخلی دیگویو ۳ با Composition APISvelte ۵ با runesانگولار با signals و دایرکتیوهای standaloneجتپک کامپوز با KotliniOS — هنوز پورت نشده

تأیید هزینه‌ها، دوپنل

پیش‌نمایش تمام‌صفحه

فهرست در یک سو و جزئیاتِ همیشه‌بازِ هزینه در سوی دیگر (در دسکتاپ)، برای بررسیِ پشتِ‌سرهم؛ در تبلت و موبایل جزئیات Sheet می‌شود.

۱. نصب کامپوننت‌ها

این بلاک از ۲۵ آیتم دیگ استفاده می‌کند: alertavatarbadgebuttoncardchipcontrol-sizedescription-listdropdown-menuempty-stateiconslist-rowpage-compositionpaginationpersiansearch-fieldselectsheetskeletonstat-tiletabletext-fieldtimelinetoasttoggle-group

پکیج‌منیجر پیش‌فرض Node.jsنصب سریع با لینک سخت و دیسک مشترکYarn نسخهٔ ۲ به بالا (Berry)رانتایم و پکیج‌منیجر Bun
npx digdesign@latest add https://docs.digdesign.ir/r/alert.json https://docs.digdesign.ir/r/avatar.json https://docs.digdesign.ir/r/badge.json https://docs.digdesign.ir/r/button.json https://docs.digdesign.ir/r/card.json https://docs.digdesign.ir/r/chip.json https://docs.digdesign.ir/r/control-size.json https://docs.digdesign.ir/r/description-list.json https://docs.digdesign.ir/r/dropdown-menu.json https://docs.digdesign.ir/r/empty-state.json https://docs.digdesign.ir/r/icons.json https://docs.digdesign.ir/r/list-row.json https://docs.digdesign.ir/r/page-composition.json https://docs.digdesign.ir/r/pagination.json https://docs.digdesign.ir/r/persian.json https://docs.digdesign.ir/r/search-field.json https://docs.digdesign.ir/r/select.json https://docs.digdesign.ir/r/sheet.json https://docs.digdesign.ir/r/skeleton.json https://docs.digdesign.ir/r/stat-tile.json https://docs.digdesign.ir/r/table.json https://docs.digdesign.ir/r/text-field.json https://docs.digdesign.ir/r/timeline.json https://docs.digdesign.ir/r/toast.json https://docs.digdesign.ir/r/toggle-group.json
pnpm dlx digdesign@latest add https://docs.digdesign.ir/r/alert.json https://docs.digdesign.ir/r/avatar.json https://docs.digdesign.ir/r/badge.json https://docs.digdesign.ir/r/button.json https://docs.digdesign.ir/r/card.json https://docs.digdesign.ir/r/chip.json https://docs.digdesign.ir/r/control-size.json https://docs.digdesign.ir/r/description-list.json https://docs.digdesign.ir/r/dropdown-menu.json https://docs.digdesign.ir/r/empty-state.json https://docs.digdesign.ir/r/icons.json https://docs.digdesign.ir/r/list-row.json https://docs.digdesign.ir/r/page-composition.json https://docs.digdesign.ir/r/pagination.json https://docs.digdesign.ir/r/persian.json https://docs.digdesign.ir/r/search-field.json https://docs.digdesign.ir/r/select.json https://docs.digdesign.ir/r/sheet.json https://docs.digdesign.ir/r/skeleton.json https://docs.digdesign.ir/r/stat-tile.json https://docs.digdesign.ir/r/table.json https://docs.digdesign.ir/r/text-field.json https://docs.digdesign.ir/r/timeline.json https://docs.digdesign.ir/r/toast.json https://docs.digdesign.ir/r/toggle-group.json
yarn dlx digdesign@latest add https://docs.digdesign.ir/r/alert.json https://docs.digdesign.ir/r/avatar.json https://docs.digdesign.ir/r/badge.json https://docs.digdesign.ir/r/button.json https://docs.digdesign.ir/r/card.json https://docs.digdesign.ir/r/chip.json https://docs.digdesign.ir/r/control-size.json https://docs.digdesign.ir/r/description-list.json https://docs.digdesign.ir/r/dropdown-menu.json https://docs.digdesign.ir/r/empty-state.json https://docs.digdesign.ir/r/icons.json https://docs.digdesign.ir/r/list-row.json https://docs.digdesign.ir/r/page-composition.json https://docs.digdesign.ir/r/pagination.json https://docs.digdesign.ir/r/persian.json https://docs.digdesign.ir/r/search-field.json https://docs.digdesign.ir/r/select.json https://docs.digdesign.ir/r/sheet.json https://docs.digdesign.ir/r/skeleton.json https://docs.digdesign.ir/r/stat-tile.json https://docs.digdesign.ir/r/table.json https://docs.digdesign.ir/r/text-field.json https://docs.digdesign.ir/r/timeline.json https://docs.digdesign.ir/r/toast.json https://docs.digdesign.ir/r/toggle-group.json
bunx --bun digdesign@latest add https://docs.digdesign.ir/r/alert.json https://docs.digdesign.ir/r/avatar.json https://docs.digdesign.ir/r/badge.json https://docs.digdesign.ir/r/button.json https://docs.digdesign.ir/r/card.json https://docs.digdesign.ir/r/chip.json https://docs.digdesign.ir/r/control-size.json https://docs.digdesign.ir/r/description-list.json https://docs.digdesign.ir/r/dropdown-menu.json https://docs.digdesign.ir/r/empty-state.json https://docs.digdesign.ir/r/icons.json https://docs.digdesign.ir/r/list-row.json https://docs.digdesign.ir/r/page-composition.json https://docs.digdesign.ir/r/pagination.json https://docs.digdesign.ir/r/persian.json https://docs.digdesign.ir/r/search-field.json https://docs.digdesign.ir/r/select.json https://docs.digdesign.ir/r/sheet.json https://docs.digdesign.ir/r/skeleton.json https://docs.digdesign.ir/r/stat-tile.json https://docs.digdesign.ir/r/table.json https://docs.digdesign.ir/r/text-field.json https://docs.digdesign.ir/r/timeline.json https://docs.digdesign.ir/r/toast.json https://docs.digdesign.ir/r/toggle-group.json
پکیج‌منیجر پیش‌فرض Node.jsنصب سریع با لینک سخت و دیسک مشترکYarn نسخهٔ ۲ به بالا (Berry)رانتایم و پکیج‌منیجر Bun
npx digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field timeline toast toggle-group --framework vue
pnpm dlx digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field timeline toast toggle-group --framework vue
yarn dlx digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field timeline toast toggle-group --framework vue
bunx --bun digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field timeline toast toggle-group --framework vue
پکیج‌منیجر پیش‌فرض Node.jsنصب سریع با لینک سخت و دیسک مشترکYarn نسخهٔ ۲ به بالا (Berry)رانتایم و پکیج‌منیجر Bun
npx digdesign@latest add button --framework svelte
pnpm dlx digdesign@latest add button --framework svelte
yarn dlx digdesign@latest add button --framework svelte
bunx --bun digdesign@latest add button --framework svelte
پکیج‌منیجر پیش‌فرض Node.jsنصب سریع با لینک سخت و دیسک مشترکYarn نسخهٔ ۲ به بالا (Berry)رانتایم و پکیج‌منیجر Bun
npx digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state icons list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field textarea timeline toast toggle-group use-is-mobile --framework angular
pnpm dlx digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state icons list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field textarea timeline toast toggle-group use-is-mobile --framework angular
yarn dlx digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state icons list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field textarea timeline toast toggle-group use-is-mobile --framework angular
bunx --bun digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state icons list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field textarea timeline toast toggle-group use-is-mobile --framework angular
پکیج‌منیجر پیش‌فرض Node.jsنصب سریع با لینک سخت و دیسک مشترکYarn نسخهٔ ۲ به بالا (Berry)رانتایم و پکیج‌منیجر Bun
npx digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field timeline toast toggle-group --framework android
pnpm dlx digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field timeline toast toggle-group --framework android
yarn dlx digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field timeline toast toggle-group --framework android
bunx --bun digdesign@latest add alert avatar badge button card chip control-size description-list dropdown-menu empty-state list-row page-composition pagination persian search-field select sheet skeleton stat-tile table text-field timeline toast toggle-group --framework android

۲. کد صفحه

کد را در صفحهٔ پروژه‌تان بگذارید (React: app/<route>/page.tsx) و متن‌ها، داده و هندلرها را با محصول خودتان عوض کنید. با سوییچر فریم‌ورک کدِ همین صفحه در فریم‌ورک دیگر را ببینید.

expense-approval-split.tsx
"use client"

import * as React from "react"

import {
  AvatarGenderIcon,
  CheckCircleIcon,
  ChevronEndIcon,
  CircleXIcon,
  ClockIcon,
  FileTextIcon,
  ReceiptIcon,
  RefreshIcon,
  SearchIcon,
  SettingsIcon,
} from "@/components/icons"
import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Avatar } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Chip, ChipCloseButton } from "@/components/ui/chip"
import { ControlSizeProvider } from "@/components/ui/control-size"
import {
  DescriptionList,
  DescriptionListDetails,
  DescriptionListItem,
  DescriptionListTerm,
} from "@/components/ui/description-list"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { EmptyState, EmptyStateActions, EmptyStateDescription, EmptyStateTitle } from "@/components/ui/empty-state"
import { ListGroup, ListRow } from "@/components/ui/list-row"
import { PageActions, PageDescription, PageHeader, PageHeading, PageTitle } from "@/components/ui/page-composition"
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination"
import { SearchField } from "@/components/ui/search-field"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { Skeleton, SkeletonGroup } from "@/components/ui/skeleton"
import { StatTile, StatTileIcon, StatTileLabel, StatTileValue } from "@/components/ui/stat-tile"
import { type SortDescriptor } from "@/components/ui/table"
import {
  TextField,
  TextFieldDescription,
  TextFieldError,
  TextFieldLabel,
  TextFieldTextarea,
} from "@/components/ui/text-field"
import {
  Timeline,
  TimelineContent,
  TimelineIndicator,
  TimelineItem,
  TimelineTime,
  TimelineTitle,
} from "@/components/ui/timeline"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { toast } from "@/components/ui/toast"
import { useIsMobile } from "@/hooks/use-mobile"
import { formatCurrency, formatJalali, formatJalaliDateTime, formatNumber, toFaDigits, toSearchKey } from "@/lib/persian"
import { avatarPhoto } from "@/lib/stock-images"

type ExpenseStatus = "pending" | "approved" | "rejected"
type Category = "travel" | "lodging" | "equipment" | "software" | "ads" | "hospitality"
type Load = "loading" | "ready" | "error"

const CATEGORIES: Record<Category, string> = {
  travel: "سفر",
  lodging: "اقامت",
  equipment: "تجهیزات",
  software: "نرم‌افزار",
  ads: "تبلیغات",
  hospitality: "پذیرایی",
}

const STATUS: Record<ExpenseStatus, { label: string; color: "warning" | "success" | "destructive" }> = {
  pending: { label: "در انتظار تأیید", color: "warning" },
  approved: { label: "تأییدشده", color: "success" },
  rejected: { label: "ردشده", color: "destructive" },
}

type HistoryItem = { at: string; actor: string; text: string; tone: "default" | "primary" | "success" | "destructive" }

type Expense = {
  id: string
  title: string
  vendor: string
  category: Category
  amount: number
  date: string
  employee: { name: string; dept: string; gender: "male" | "female" }
  status: ExpenseStatus
  method: string
  project: string
  receipt?: { name: string; size: string }
  note: string
  policy?: string
  rejectReason?: string
  history: HistoryItem[]
  /** نخستین ثبتِ تصمیم برای این هزینه با خطای شبکه تمام می‌شود (برای نمایشِ حالتِ خطا). */
  failOnce?: boolean
}

const REVIEWER = "الهام کاظمی"
const MIN_REASON = 10
const MAX_REASON = 300
const PAGE_SIZE = 6

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
const millions = (value: number) => `${formatNumber(value / 1_000_000, { maximumFractionDigits: 1 })} میلیون`

function seed(
  id: string,
  title: string,
  vendor: string,
  category: Category,
  amount: number,
  date: string,
  employee: Expense["employee"],
  status: ExpenseStatus,
  extra: Partial<Expense> & Pick<Expense, "method" | "project" | "note">,
): Expense {
  const history: HistoryItem[] = [{ at: date, actor: employee.name, text: "هزینه را ثبت کرد.", tone: "default" }]
  if (extra.receipt) history.push({ at: date, actor: employee.name, text: "رسید را پیوست کرد.", tone: "primary" })
  if (status === "approved") history.push({ at: date, actor: REVIEWER, text: "هزینه را تأیید کرد.", tone: "success" })
  if (status === "rejected") history.push({ at: date, actor: REVIEWER, text: "هزینه را رد کرد.", tone: "destructive" })
  return { id, title, vendor, category, amount, date, employee, status, history, ...extra }
}

const RECEIPT = { name: "receipt.pdf", size: "۲۴۰ کیلوبایت" }
const OVER_LIMIT = "مبلغ از سقف ۵۰ میلیون تومانی بالاتر است و تأیید مدیر مالی هم لازم دارد."

const INITIAL_EXPENSES: Expense[] = [
  seed("EXP-1521", "بلیت هواپیما تهران، شیراز", "ایران‌ایر", "travel", 14_800_000, "2026-10-26T09:10:00", { name: "سارا محمدی", dept: "فروش", gender: "female" }, "pending", { method: "کارت سازمانی", project: "نمایشگاه شیراز", note: "رفت‌وآمد تیم فروش برای نمایشگاه سالانه.", receipt: RECEIPT, failOnce: true }),
  seed("EXP-1520", "اشتراک سالانهٔ ابزار طراحی", "فیگما", "software", 96_000_000, "2026-10-25T14:30:00", { name: "کیان مرادی", dept: "محصول", gender: "male" }, "pending", { method: "کارت سازمانی", project: "زیرساخت محصول", note: "تمدید ۱۶ صندلی برای تیم طراحی.", policy: OVER_LIMIT, receipt: { name: "invoice.pdf", size: "۱٫۲ مگابایت" } }),
  seed("EXP-1519", "اقامت سه‌شبه در هتل", "هتل پارسیان", "lodging", 21_600_000, "2026-10-24T18:05:00", { name: "نیلوفر احمدی", dept: "فروش", gender: "female" }, "pending", { method: "پرداخت شخصی", project: "نمایشگاه شیراز", note: "اقامت در زمان برگزاری نمایشگاه.", receipt: RECEIPT }),
  seed("EXP-1518", "کمپین تبلیغات جست‌وجو، مهر", "گوگل ادز", "ads", 38_500_000, "2026-10-23T11:20:00", { name: "پرهام نوری", dept: "بازاریابی", gender: "male" }, "pending", { method: "کارت سازمانی", project: "کمپین پاییز", note: "بودجهٔ ماهانهٔ کمپین پاییزه.", receipt: RECEIPT }),
  seed("EXP-1517", "ناهار کاری با مشتری", "رستوران نایب", "hospitality", 3_200_000, "2026-10-22T13:40:00", { name: "مهسا توکلی", dept: "فروش", gender: "female" }, "approved", { method: "پرداخت شخصی", project: "حساب‌های کلیدی", note: "جلسهٔ تمدید قرارداد.", receipt: RECEIPT }),
  seed("EXP-1516", "نمایشگر ۲۷ اینچ برای تیم فنی", "دیجی‌کالا", "equipment", 27_900_000, "2026-10-21T10:00:00", { name: "بهراد صالحی", dept: "مهندسی", gender: "male" }, "approved", { method: "کارت سازمانی", project: "زیرساخت محصول", note: "دو دستگاه برای کارمندان تازه‌وارد.", receipt: RECEIPT }),
  seed("EXP-1515", "دورهٔ آنلاین امنیت وب", "فرادرس", "software", 4_900_000, "2026-10-20T16:15:00", { name: "ترانه شریفی", dept: "مهندسی", gender: "female" }, "approved", { method: "پرداخت شخصی", project: "ارتقای مهارت", note: "طبق برنامهٔ آموزشی سالانه.", receipt: RECEIPT }),
  seed("EXP-1514", "تاکسی اینترنتی، هفتهٔ آخر", "اسنپ", "travel", 1_850_000, "2026-10-19T20:30:00", { name: "امیر رضایی", dept: "فروش", gender: "male" }, "rejected", { method: "پرداخت شخصی", project: "حساب‌های کلیدی", note: "چند سفر درون‌شهری.", rejectReason: "رسید تاکسی‌ها پیوست نشده بود؛ لطفاً رسیدها را اضافه و دوباره ثبت کنید." }),
  seed("EXP-1513", "اشتراک سرور آزمایشی", "لیارا", "software", 12_400_000, "2026-10-18T09:50:00", { name: "کیان مرادی", dept: "محصول", gender: "male" }, "approved", { method: "کارت سازمانی", project: "زیرساخت محصول", note: "سرور آزمایشیِ ماهانه.", receipt: RECEIPT }),
  seed("EXP-1512", "چاپ بروشور نمایشگاه", "چاپ نگار", "ads", 9_300_000, "2026-10-17T12:00:00", { name: "پرهام نوری", dept: "بازاریابی", gender: "male" }, "pending", { method: "پرداخت شخصی", project: "نمایشگاه شیراز", note: "۵۰۰ بروشور رنگی.", receipt: RECEIPT }),
  seed("EXP-1511", "پذیرایی جلسهٔ فصلی", "کافه رست", "hospitality", 2_150_000, "2026-10-16T15:45:00", { name: "نیلوفر احمدی", dept: "فروش", gender: "female" }, "approved", { method: "کارت سازمانی", project: "عملیات", note: "جلسهٔ مرور فصل.", receipt: RECEIPT }),
  seed("EXP-1510", "اقامت یک‌شبهٔ تبریز", "هتل شهریار", "lodging", 6_800_000, "2026-10-15T08:20:00", { name: "مهسا توکلی", dept: "فروش", gender: "female" }, "rejected", { method: "پرداخت شخصی", project: "حساب‌های کلیدی", note: "سفر کاری تبریز.", receipt: RECEIPT, rejectReason: "سفر قبل از ثبت درخواست مجوز انجام شده است." }),
  seed("EXP-1509", "لپ‌تاپ برای استخدام تازه", "آیتی‌بازار", "equipment", 74_000_000, "2026-10-14T11:10:00", { name: "بهراد صالحی", dept: "مهندسی", gender: "male" }, "pending", { method: "کارت سازمانی", project: "زیرساخت محصول", note: "یک دستگاه با پردازندهٔ قوی.", policy: OVER_LIMIT, receipt: { name: "laptop.pdf", size: "۱٫۱ مگابایت" } }),
  seed("EXP-1508", "هدیهٔ مشتریان پایان سال", "گالری آوا", "hospitality", 18_200_000, "2026-10-06T13:15:00", { name: "پرهام نوری", dept: "بازاریابی", gender: "male" }, "rejected", { method: "پرداخت شخصی", project: "کمپین پاییز", note: "۳۰ بسته هدیه.", receipt: RECEIPT, rejectReason: "بودجهٔ هدیه در این فصل بسته شده است؛ در فصل بعد ثبت شود." }),
]

function EmployeeAvatar({ employee, size = "sm" }: { employee: Expense["employee"]; size?: "sm" | "default" }) {
  return (
    <Avatar
      size={size}
      alt={employee.name}
      src={avatarPhoto(employee.name, employee.gender)}
      icon={<AvatarGenderIcon gender={employee.gender} />}
      className="ring-1 ring-border"
    />
  )
}

function StatusBadge({ status }: { status: ExpenseStatus }) {
  return (
    <Badge variant="soft" color={STATUS[status].color} className="gap-1.5">
      <span aria-hidden className="size-1.5 rounded-full bg-current" />
      {STATUS[status].label}
    </Badge>
  )
}

/** منطقِ مشترکِ صفحه: دریافت، فیلتر، مرتب‌سازی، تصمیم با بازگردانی و بازگشتِ فوکوس. */
function useExpenseApproval() {
  const [expenses, setExpenses] = React.useState<Expense[]>(INITIAL_EXPENSES)
  const [load, setLoad] = React.useState<Load>("loading")
  const [query, setQuery] = React.useState("")
  const [status, setStatus] = React.useState<"all" | ExpenseStatus>("all")
  const [category, setCategory] = React.useState<"all" | Category>("all")
  const [sort, setSort] = React.useState<SortDescriptor>({ column: "date", direction: "descending" })
  const [page, setPage] = React.useState(1)
  const [selectedId, setSelectedId] = React.useState<string | null>(null)
  const [open, setOpen] = React.useState(false)
  const [busy, setBusy] = React.useState<"approve" | "reject" | null>(null)
  const [actionError, setActionError] = React.useState<string | null>(null)
  const failed = React.useRef(new Set<string>())

  const fetchData = React.useCallback(async (mode: "ok" | "error" | "empty" = "ok") => {
    setLoad("loading")
    await wait(900)
    if (mode === "error") return setLoad("error")
    setExpenses(mode === "empty" ? [] : INITIAL_EXPENSES)
    setLoad("ready")
  }, [])

  React.useEffect(() => {
    // دریافتِ اولیه؛ با API واقعی جایش را بدهید.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    fetchData()
  }, [fetchData])

  const key = toSearchKey(query)
  const filtered = expenses
    .filter(
      (e) =>
        (status === "all" || e.status === status) &&
        (category === "all" || e.category === category) &&
        toSearchKey(`${e.title} ${e.vendor} ${e.employee.name} ${e.id}`).includes(key),
    )
    .sort((a, b) => {
      const order =
        sort.column === "amount"
          ? a.amount - b.amount
          : sort.column === "employee"
            ? a.employee.name.localeCompare(b.employee.name, "fa")
            : a.date.localeCompare(b.date)
      return sort.direction === "ascending" ? order : -order
    })
  const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))
  const currentPage = Math.min(page, pageCount)
  const rows = filtered.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE)
  const filtersActive = !!query || status !== "all" || category !== "all"

  function clearFilters() {
    setQuery("")
    setStatus("all")
    setCategory("all")
    setPage(1)
  }

  function openExpense(id: string) {
    setSelectedId(id)
    setActionError(null)
    setOpen(true)
  }

  // بستنِ پنل فوکوس را به دکمهٔ همان ردیف برمی‌گرداند (هر بازکننده data-open-id دارد).
  function onOpenChange(next: boolean) {
    setOpen(next)
    if (next) return
    const id = selectedId
    setTimeout(() => document.querySelector<HTMLElement>(`[data-open-id="${id}"]`)?.focus(), 50)
  }

  async function decide(id: string, next: "approved" | "rejected", reason?: string) {
    const before = expenses.find((e) => e.id === id)
    if (!before) return
    setBusy(next === "approved" ? "approve" : "reject")
    setActionError(null)
    await wait(800)
    if (before.failOnce && !failed.current.has(id)) {
      failed.current.add(id)
      setBusy(null)
      setActionError("ارتباط با سرور برقرار نشد. هزینه تغییری نکرد؛ دوباره تلاش کنید.")
      toast.error("تصمیم ثبت نشد", { description: "اتصال قطع شد؛ دوباره تلاش کنید." })
      return
    }
    const entry: HistoryItem =
      next === "approved"
        ? { at: new Date().toISOString(), actor: REVIEWER, text: "هزینه را تأیید کرد.", tone: "success" }
        : { at: new Date().toISOString(), actor: REVIEWER, text: "هزینه را رد کرد.", tone: "destructive" }
    setExpenses((list) =>
      list.map((e) => (e.id === id ? { ...e, status: next, rejectReason: reason, history: [...e.history, entry] } : e)),
    )
    setBusy(null)
    toast.success(next === "approved" ? "هزینه تأیید شد" : "هزینه رد شد", {
      description: before.title,
      action: {
        label: "بازگردانی",
        onClick: () => {
          setExpenses((list) => list.map((e) => (e.id === id ? before : e)))
          toast("به وضعیت «در انتظار تأیید» برگشت.")
        },
      },
    })
  }

  const count = (s: ExpenseStatus) => expenses.filter((e) => e.status === s).length
  const pending = expenses.filter((e) => e.status === "pending")
  const metrics = [
    { icon: <ClockIcon />, tone: "warning" as const, label: "در انتظار تأیید", value: toFaDigits(pending.length), hint: `${millions(pending.reduce((n, e) => n + e.amount, 0))} تومان` },
    { icon: <CheckCircleIcon />, tone: "success" as const, label: "تأییدشده این ماه", value: millions(expenses.filter((e) => e.status === "approved").reduce((n, e) => n + e.amount, 0)), hint: `${toFaDigits(count("approved"))} هزینه` },
    { icon: <CircleXIcon />, tone: "destructive" as const, label: "ردشده", value: toFaDigits(count("rejected")), hint: "با دلیل ثبت شده" },
    { icon: <ReceiptIcon />, tone: "primary" as const, label: "کل هزینه‌ها", value: toFaDigits(expenses.length), hint: "در این ماه" },
  ]

  return {
    expenses, load, fetchData, query, setQuery, status, setStatus, category, setCategory, sort, setSort,
    setPage, currentPage, pageCount, rows, filtered, filtersActive, clearFilters,
    selected: expenses.find((e) => e.id === selectedId) ?? null, selectedId, open, openExpense, onOpenChange,
    busy, actionError, approve: (id: string) => decide(id, "approved"), reject: (id: string, reason: string) => decide(id, "rejected", reason),
    pending, metrics,
  }
}

type Approval = ReturnType<typeof useExpenseApproval>

function PageTop({ approval }: { approval: Approval }) {
  return (
    <PageHeader>
      <PageHeading>
        <PageTitle>هزینه‌های سازمان</PageTitle>
        <PageDescription>هزینه‌های ثبت‌شدهٔ تیم‌ها را بررسی و تأیید یا رد کنید.</PageDescription>
      </PageHeading>
      <PageActions>
        <Badge variant="soft" color="warning" className="h-7 px-3 text-sm">
          {toFaDigits(approval.pending.length)} مورد منتظر شماست
        </Badge>
        {/* فقط برای نمایش: حالت‌های بارگذاری، خطا و خالی را شبیه‌سازی می‌کند؛ در محصول حذفش کنید. */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="icon" aria-label="شبیه‌سازی وضعیت‌ها">
              <SettingsIcon />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuLabel>شبیه‌سازی وضعیت‌ها</DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem onSelect={() => approval.fetchData("ok")}>بارگذاری دوباره</DropdownMenuItem>
            <DropdownMenuItem onSelect={() => approval.fetchData("error")}>خطای دریافت</DropdownMenuItem>
            <DropdownMenuItem onSelect={() => approval.fetchData("empty")}>فهرست خالی</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </PageActions>
    </PageHeader>
  )
}

function Summary({ approval }: { approval: Approval }) {
  return (
    <section aria-label="خلاصهٔ هزینه‌ها" className="grid grid-cols-2 gap-3 lg:grid-cols-4">
      {approval.metrics.map((m) => (
        <StatTile key={m.label} className="gap-3 p-4">
          <div className="flex items-center gap-3">
            <StatTileIcon tone={m.tone} className="size-9">{m.icon}</StatTileIcon>
            <StatTileLabel>{m.label}</StatTileLabel>
          </div>
          {approval.load === "loading" ? <Skeleton className="h-8 w-24" /> : <StatTileValue className="text-xl sm:text-3xl">{m.value}</StatTileValue>}
          <span className="text-xs text-muted-foreground">{approval.load === "loading" ? " " : m.hint}</span>
        </StatTile>
      ))}
    </section>
  )
}

function Filters({ approval }: { approval: Approval }) {
  const { query, setQuery, status, setStatus, category, setCategory, setPage, filtersActive, clearFilters } = approval
  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-center">
        <SearchField
          aria-label="جست‌وجوی هزینه"
          placeholder="جست‌وجوی عنوان، فروشنده یا نام ثبت‌کننده"
          value={query}
          onValueChange={(v) => {
            setQuery(v)
            setPage(1)
          }}
          className="min-w-0 flex-1 lg:max-w-sm"
        />
        <div className="min-w-0 overflow-x-auto lg:ms-auto">
          <ControlSizeProvider size="lg" mobileSize="default" asChild>
            <ToggleGroup
              type="single"
              variant="segmented"
              aria-label="فیلتر وضعیت"
              value={status}
              onValueChange={(v) => {
                if (!v) return
                setStatus(v as "all" | ExpenseStatus)
                setPage(1)
              }}
            >
              <ToggleGroupItem value="all">همه</ToggleGroupItem>
              <ToggleGroupItem value="pending">در انتظار</ToggleGroupItem>
              <ToggleGroupItem value="approved">تأییدشده</ToggleGroupItem>
              <ToggleGroupItem value="rejected">ردشده</ToggleGroupItem>
            </ToggleGroup>
          </ControlSizeProvider>
        </div>
        <Select
          value={category}
          onValueChange={(v) => {
            setCategory(v as "all" | Category)
            setPage(1)
          }}
        >
          <SelectTrigger aria-label="فیلتر دسته" className="w-full lg:w-44">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">همهٔ دسته‌ها</SelectItem>
            {(Object.keys(CATEGORIES) as Category[]).map((c) => (
              <SelectItem key={c} value={c}>
                {CATEGORIES[c]}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="flex min-h-8 flex-wrap items-center gap-2" aria-live="polite">
        <span className="text-sm text-muted-foreground">
          {approval.load === "loading" ? "در حال دریافت…" : `${toFaDigits(approval.filtered.length)} هزینه`}
        </span>
        {query ? (
          <Chip>
            «{query}»
            <ChipCloseButton aria-label="پاک‌کردن جست‌وجو" onClick={() => setQuery("")}>
              <span aria-hidden>×</span>
            </ChipCloseButton>
          </Chip>
        ) : null}
        {category !== "all" ? (
          <Chip>
            {CATEGORIES[category]}
            <ChipCloseButton aria-label="پاک‌کردن فیلتر دسته" onClick={() => setCategory("all")}>
              <span aria-hidden>×</span>
            </ChipCloseButton>
          </Chip>
        ) : null}
        {filtersActive ? (
          <Button variant="ghost" size="sm" onClick={clearFilters}>
            پاک‌کردنِ فیلترها
          </Button>
        ) : null}
      </div>
    </div>
  )
}

function ListSkeleton() {
  return (
    <SkeletonGroup aria-busy="true" aria-label="در حال بارگذاری هزینه‌ها" className="flex flex-col gap-3 rounded-xl border border-border bg-card p-4">
      {Array.from({ length: 6 }, (_, i) => (
        <div key={i} className="flex items-center gap-4">
          <Skeleton className="size-9 rounded-full" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="hidden h-4 w-24 sm:block" />
          <Skeleton className="h-6 w-20" />
        </div>
      ))}
    </SkeletonGroup>
  )
}

function LoadError({ approval }: { approval: Approval }) {
  return (
    <Alert color="destructive" role="alert">
      <AlertTitle>هزینه‌ها بارگذاری نشد</AlertTitle>
      <AlertDescription>اتصال به سرور قطع شد. داده‌ای از دست نرفته است.</AlertDescription>
      <AlertAction>
        <Button variant="outline" onClick={() => approval.fetchData()}>
          <RefreshIcon />
          تلاش دوباره
        </Button>
      </AlertAction>
    </Alert>
  )
}

function EmptyList({ approval }: { approval: Approval }) {
  const none = approval.expenses.length === 0
  return (
    <EmptyState variant="bordered" className="py-14">
      <SearchIcon aria-hidden className="size-8 text-placeholder" />
      <EmptyStateTitle>{none ? "هنوز هزینه‌ای ثبت نشده" : "هزینه‌ای با این مشخصات نیست"}</EmptyStateTitle>
      <EmptyStateDescription>
        {none ? "وقتی همکاران هزینه ثبت کنند، برای بررسی همین‌جا می‌آید." : "عبارت دیگری را جست‌وجو کنید یا فیلترها را بردارید."}
      </EmptyStateDescription>
      <EmptyStateActions>
        <Button variant="outline" onClick={none ? () => approval.fetchData() : approval.clearFilters}>
          {none ? <RefreshIcon /> : null}
          {none ? "بارگذاری دوباره" : "پاک‌کردنِ فیلترها"}
        </Button>
      </EmptyStateActions>
    </EmptyState>
  )
}

function Pager({ approval }: { approval: Approval }) {
  const { currentPage, pageCount, setPage, filtered } = approval
  return (
    <footer className="flex flex-wrap items-center justify-between gap-3">
      <span className="text-sm text-muted-foreground">
        نمایش {toFaDigits((currentPage - 1) * PAGE_SIZE + 1)} تا {toFaDigits(Math.min(currentPage * PAGE_SIZE, filtered.length))} از{" "}
        {toFaDigits(filtered.length)} هزینه
      </span>
      <Pagination className="mx-0 w-auto">
        <PaginationContent>
          <PaginationItem>
            <PaginationPrevious
              href="#"
              aria-disabled={currentPage === 1}
              onClick={(ev) => {
                ev.preventDefault()
                setPage(Math.max(1, currentPage - 1))
              }}
            />
          </PaginationItem>
          {Array.from({ length: pageCount }, (_, i) => i + 1).map((n) => (
            <PaginationItem key={n}>
              <PaginationLink
                href="#"
                isActive={n === currentPage}
                onClick={(ev) => {
                  ev.preventDefault()
                  setPage(n)
                }}
              >
                {toFaDigits(n)}
              </PaginationLink>
            </PaginationItem>
          ))}
          <PaginationItem>
            <PaginationNext
              href="#"
              aria-disabled={currentPage === pageCount}
              onClick={(ev) => {
                ev.preventDefault()
                setPage(Math.min(pageCount, currentPage + 1))
              }}
            />
          </PaginationItem>
        </PaginationContent>
      </Pagination>
    </footer>
  )
}

/**
 * محتوای جزئیات: خلاصه، هشدارها، مشخصات (DescriptionList)، رسید، تاریخچه (Timeline) و
 * اقدام. «رد» دلیلِ حداقل ۱۰ نویسه می‌خواهد؛ خطای درون‌خطی، فوکوس به فیلد و بازگشتِ فوکوس به دکمهٔ رد.
 */
function ExpensePanel({
  expense,
  busy,
  error,
  onApprove,
  onReject,
  heading,
  footerClassName,
}: {
  expense: Expense
  busy: "approve" | "reject" | null
  error: string | null
  onApprove: (id: string) => void
  onReject: (id: string, reason: string) => void
  heading: React.ReactNode
  footerClassName?: string
}) {
  const [rejecting, setRejecting] = React.useState(false)
  const [reason, setReason] = React.useState("")
  const [touched, setTouched] = React.useState(false)
  const textareaRef = React.useRef<HTMLTextAreaElement>(null)
  const rejectTriggerRef = React.useRef<HTMLButtonElement>(null)
  const resultRef = React.useRef<HTMLDivElement>(null)
  const lastStatus = React.useRef(expense.status)

  // با تغییرِ هزینه، فرمِ رد از نو شروع می‌شود.
  React.useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setRejecting(false)
    setReason("")
    setTouched(false)
  }, [expense.id])

  React.useEffect(() => {
    if (rejecting) textareaRef.current?.focus()
  }, [rejecting])

  // بعد از ثبتِ تصمیم دکمه‌ها می‌روند؛ فوکوس به نتیجه می‌رود تا گم نشود.
  React.useEffect(() => {
    if (lastStatus.current === "pending" && expense.status !== "pending") resultRef.current?.focus()
    lastStatus.current = expense.status
  }, [expense.status])

  const trimmed = reason.trim()
  const reasonError = !trimmed
    ? "نوشتن دلیل برای ردِ هزینه الزامی است."
    : trimmed.length < MIN_REASON
      ? `دلیل را کمی کامل‌تر بنویسید؛ دست‌کم ${toFaDigits(MIN_REASON)} نویسه.`
      : undefined
  const showError = touched && !!reasonError

  function submitReject(event: React.FormEvent) {
    event.preventDefault()
    setTouched(true)
    if (reasonError) return textareaRef.current?.focus()
    onReject(expense.id, trimmed)
  }

  function cancelReject() {
    setRejecting(false)
    setReason("")
    setTouched(false)
    requestAnimationFrame(() => rejectTriggerRef.current?.focus())
  }

  return (
    <>
      <div className="flex flex-col gap-2 border-b border-border p-5 pe-14">
        <div className="flex flex-wrap items-center gap-2">
          <StatusBadge status={expense.status} />
          <bdi dir="ltr" className="text-xs text-muted-foreground">{expense.id}</bdi>
        </div>
        {heading}
        <p className="text-sm text-muted-foreground">
          {expense.vendor}، {CATEGORIES[expense.category]}
        </p>
      </div>

      <div className="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto p-5">
        <p className="text-3xl font-semibold tabular-nums">{formatCurrency(expense.amount)}</p>

        <div ref={resultRef} tabIndex={-1} className="flex flex-col gap-3 outline-none">
          {expense.policy && expense.status === "pending" ? (
            <Alert color="warning" variant="flat">
              <AlertTitle>نیاز به توجه</AlertTitle>
              <AlertDescription>{expense.policy}</AlertDescription>
            </Alert>
          ) : null}
          {expense.status === "rejected" && expense.rejectReason ? (
            <Alert color="destructive" variant="flat">
              <AlertTitle>دلیل رد</AlertTitle>
              <AlertDescription>{expense.rejectReason}</AlertDescription>
            </Alert>
          ) : null}
          {expense.status === "approved" ? (
            <Alert color="success" variant="flat">
              <AlertTitle>این هزینه تأیید شده است</AlertTitle>
              <AlertDescription>مبلغ در نوبت پرداخت بعدی تسویه می‌شود.</AlertDescription>
            </Alert>
          ) : null}
          {error ? (
            <Alert color="destructive" role="alert">
              <AlertTitle>ثبت نشد</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          ) : null}
        </div>

        <div className="flex items-center gap-3">
          <EmployeeAvatar employee={expense.employee} size="default" />
          <div className="flex min-w-0 flex-col">
            <span className="font-medium">{expense.employee.name}</span>
            <span className="text-sm text-muted-foreground">بخش {expense.employee.dept}</span>
          </div>
        </div>

        <DescriptionList columns={2}>
          <DescriptionListItem>
            <DescriptionListTerm>تاریخ ثبت</DescriptionListTerm>
            <DescriptionListDetails>{formatJalaliDateTime(expense.date)}</DescriptionListDetails>
          </DescriptionListItem>
          <DescriptionListItem>
            <DescriptionListTerm>روش پرداخت</DescriptionListTerm>
            <DescriptionListDetails>{expense.method}</DescriptionListDetails>
          </DescriptionListItem>
          <DescriptionListItem>
            <DescriptionListTerm>پروژه</DescriptionListTerm>
            <DescriptionListDetails>{expense.project}</DescriptionListDetails>
          </DescriptionListItem>
          <DescriptionListItem>
            <DescriptionListTerm>دسته</DescriptionListTerm>
            <DescriptionListDetails>{CATEGORIES[expense.category]}</DescriptionListDetails>
          </DescriptionListItem>
          <DescriptionListItem full>
            <DescriptionListTerm>توضیح</DescriptionListTerm>
            <DescriptionListDetails>{expense.note}</DescriptionListDetails>
          </DescriptionListItem>
        </DescriptionList>

        <section aria-labelledby={`receipt-${expense.id}`} className="flex flex-col gap-3">
          <h3 id={`receipt-${expense.id}`} className="font-medium">رسید</h3>
          {expense.receipt ? (
            <ListGroup>
              <ListRow
                leading={<FileTextIcon aria-hidden className="size-5" />}
                title={<bdi dir="ltr">{expense.receipt.name}</bdi>}
                subtitle={expense.receipt.size}
              />
            </ListGroup>
          ) : (
            <p className="text-sm text-muted-foreground">رسیدی پیوست نشده است.</p>
          )}
        </section>

        <section aria-labelledby={`history-${expense.id}`} className="flex flex-col gap-3">
          <h3 id={`history-${expense.id}`} className="font-medium">تاریخچه</h3>
          <Timeline>
            {[...expense.history].reverse().map((item, index) => (
              <TimelineItem key={index}>
                <TimelineIndicator tone={item.tone} />
                <TimelineContent>
                  <TimelineTitle className="font-normal">
                    <span className="font-semibold">{item.actor}</span> {item.text}
                  </TimelineTitle>
                  <TimelineTime dateTime={item.at}>{formatJalaliDateTime(item.at)}</TimelineTime>
                </TimelineContent>
              </TimelineItem>
            ))}
          </Timeline>
        </section>
      </div>

      {expense.status === "pending" ? (
        rejecting ? (
          <form noValidate onSubmit={submitReject} className="flex flex-col gap-4 border-t border-border bg-subtle p-5">
            <TextField invalid={showError} required>
              <TextFieldLabel>دلیل رد هزینه</TextFieldLabel>
              <TextFieldTextarea
                ref={textareaRef}
                rows={3}
                maxLength={MAX_REASON}
                placeholder="مثلاً رسید پیوست نشده است"
                value={reason}
                disabled={busy === "reject"}
                onValueChange={setReason}
                onBlur={() => setTouched(true)}
              />
              {showError ? (
                <TextFieldError>{reasonError}</TextFieldError>
              ) : (
                <TextFieldDescription>
                  ثبت‌کننده این متن را می‌بیند. {toFaDigits(reason.length)} از {toFaDigits(MAX_REASON)} نویسه
                </TextFieldDescription>
              )}
            </TextField>
            <div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
              <Button type="button" variant="outline" disabled={busy === "reject"} onClick={cancelReject}>
                انصراف
              </Button>
              <Button type="submit" color="destructive" disabled={busy === "reject"}>
                {busy === "reject" ? "در حال ثبت…" : "ثبت رد هزینه"}
              </Button>
            </div>
          </form>
        ) : (
          <div className={footerClassName ?? "flex flex-col-reverse gap-3 border-t border-border p-5 sm:flex-row sm:justify-end"}>
            <Button ref={rejectTriggerRef} variant="outline" color="destructive" disabled={busy !== null} onClick={() => setRejecting(true)}>
              <CircleXIcon />
              رد هزینه
            </Button>
            <Button disabled={busy !== null} onClick={() => onApprove(expense.id)}>
              <CheckCircleIcon />
              {busy === "approve" ? "در حال تأیید…" : "تأیید هزینه"}
            </Button>
          </div>
        )
      ) : null}
    </>
  )
}

function ExpenseSheet({ approval }: { approval: Approval }) {
  const { selected, open, onOpenChange, busy, actionError, approve, reject } = approval
  return (
    <Sheet open={open} onOpenChange={(next) => !busy && onOpenChange(next)}>
      <ControlSizeProvider size="lg" asChild>
        <SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-md">
          <SheetHeader className="sr-only">
            <SheetDescription>جزئیات هزینه و تصمیم‌گیری</SheetDescription>
          </SheetHeader>
          {selected ? (
            <ExpensePanel
              expense={selected}
              busy={busy}
              error={actionError}
              onApprove={approve}
              onReject={reject}
              heading={<SheetTitle className="text-xl leading-snug">{selected.title}</SheetTitle>}
            />
          ) : null}
        </SheetContent>
      </ControlSizeProvider>
    </Sheet>
  )
}

function CompactRow({ expense, onOpen, selected }: { expense: Expense; onOpen: (id: string) => void; selected?: boolean }) {
  return (
    <li className={`flex min-w-0 items-center gap-3 py-3.5 ${selected ? "bg-muted" : ""}`}>
      <EmployeeAvatar employee={expense.employee} />
      <span className="flex min-w-0 flex-1 flex-col gap-0.5">
        <span className="truncate text-sm font-medium">{expense.title}</span>
        <span className="truncate text-xs text-muted-foreground">
          {expense.employee.name}، {formatJalali(expense.date)}
        </span>
      </span>
      <span className="flex shrink-0 flex-col items-end gap-1">
        <span className="text-sm font-semibold tabular-nums">{formatCurrency(expense.amount)}</span>
        <StatusBadge status={expense.status} />
      </span>
      <Button variant="ghost" size="icon" data-open-id={expense.id} aria-current={selected || undefined} aria-label={`مشاهدهٔ جزئیات ${expense.title}`} onClick={() => onOpen(expense.id)}>
        <ChevronEndIcon />
      </Button>
    </li>
  )
}

export default function ExpenseApprovalSplitBlock() {
  const approval = useExpenseApproval()
  const { load, filtered, openExpense, selected, pending, busy, actionError, approve, reject } = approval
  const wide = !useIsMobile(1024)
  const current = selected ?? pending[0] ?? null

  return (
    <ControlSizeProvider size="lg" asChild>
      <div className="mx-auto flex w-full max-w-7xl flex-col gap-6 p-4 sm:p-6 lg:p-8">
        <PageTop approval={approval} />

        {load === "error" ? (
          <LoadError approval={approval} />
        ) : (
          <>
            <Summary approval={approval} />
            <div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_26rem]">
              <section aria-label="فهرست هزینه‌ها" className="flex min-w-0 flex-col gap-6">
                <Filters approval={approval} />
                {load === "loading" ? (
                  <ListSkeleton />
                ) : filtered.length === 0 ? (
                  <EmptyList approval={approval} />
                ) : (
                  <ListGroup>
                    {filtered.map((e) => (
                      <CompactRow key={e.id} expense={e} onOpen={openExpense} selected={wide && current?.id === e.id} />
                    ))}
                  </ListGroup>
                )}
              </section>
              {wide && load === "ready" ? (
                <Card className="sticky top-6 flex max-h-[calc(100dvh-3rem)] flex-col overflow-hidden p-0" aria-label="جزئیات هزینه">
                  {current ? (
                    <ExpensePanel
                      expense={current}
                      busy={busy}
                      error={actionError}
                      onApprove={approve}
                      onReject={reject}
                      heading={<h2 className="text-xl font-semibold leading-snug">{current.title}</h2>}
                    />
                  ) : (
                    <EmptyState className="py-14">
                      <EmptyStateTitle>هزینه‌ای برای بررسی نیست</EmptyStateTitle>
                      <EmptyStateDescription>یک هزینه را از فهرست انتخاب کنید.</EmptyStateDescription>
                    </EmptyState>
                  )}
                </Card>
              ) : null}
            </div>
          </>
        )}

        {wide ? null : <ExpenseSheet approval={approval} />}
      </div>
    </ControlSizeProvider>
  )
}
expense-approval-split.vue
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from "vue"

import Alert from "@/components/ui/Alert.vue"
import AlertAction from "@/components/ui/AlertAction.vue"
import AlertDescription from "@/components/ui/AlertDescription.vue"
import AlertTitle from "@/components/ui/AlertTitle.vue"
import Avatar from "@/components/ui/Avatar.vue"
import Badge from "@/components/ui/Badge.vue"
import Button from "@/components/ui/Button.vue"
import Card from "@/components/ui/Card.vue"
import Chip from "@/components/ui/Chip.vue"
import ChipCloseButton from "@/components/ui/ChipCloseButton.vue"
import ControlSize from "@/components/ui/ControlSize.vue"
import DescriptionList from "@/components/ui/DescriptionList.vue"
import DescriptionListDetails from "@/components/ui/DescriptionListDetails.vue"
import DescriptionListItem from "@/components/ui/DescriptionListItem.vue"
import DescriptionListTerm from "@/components/ui/DescriptionListTerm.vue"
import DropdownMenu from "@/components/ui/DropdownMenu.vue"
import DropdownMenuContent from "@/components/ui/DropdownMenuContent.vue"
import DropdownMenuItem from "@/components/ui/DropdownMenuItem.vue"
import DropdownMenuLabel from "@/components/ui/DropdownMenuLabel.vue"
import DropdownMenuSeparator from "@/components/ui/DropdownMenuSeparator.vue"
import DropdownMenuTrigger from "@/components/ui/DropdownMenuTrigger.vue"
import EmptyState from "@/components/ui/EmptyState.vue"
import EmptyStateActions from "@/components/ui/EmptyStateActions.vue"
import EmptyStateDescription from "@/components/ui/EmptyStateDescription.vue"
import EmptyStateTitle from "@/components/ui/EmptyStateTitle.vue"
import ListGroup from "@/components/ui/ListGroup.vue"
import ListRow from "@/components/ui/ListRow.vue"
import PageActions from "@/components/ui/PageActions.vue"
import PageDescription from "@/components/ui/PageDescription.vue"
import PageHeader from "@/components/ui/PageHeader.vue"
import PageHeading from "@/components/ui/PageHeading.vue"
import PageTitle from "@/components/ui/PageTitle.vue"
import Pagination from "@/components/ui/Pagination.vue"
import PaginationContent from "@/components/ui/PaginationContent.vue"
import PaginationItem from "@/components/ui/PaginationItem.vue"
import PaginationLink from "@/components/ui/PaginationLink.vue"
import PaginationNext from "@/components/ui/PaginationNext.vue"
import PaginationPrevious from "@/components/ui/PaginationPrevious.vue"
import SearchField from "@/components/ui/SearchField.vue"
import Select from "@/components/ui/Select.vue"
import SelectContent from "@/components/ui/SelectContent.vue"
import SelectItem from "@/components/ui/SelectItem.vue"
import SelectTrigger from "@/components/ui/SelectTrigger.vue"
import SelectValue from "@/components/ui/SelectValue.vue"
import Sheet from "@/components/ui/Sheet.vue"
import SheetContent from "@/components/ui/SheetContent.vue"
import SheetDescription from "@/components/ui/SheetDescription.vue"
import SheetHeader from "@/components/ui/SheetHeader.vue"
import SheetTitle from "@/components/ui/SheetTitle.vue"
import Skeleton from "@/components/ui/Skeleton.vue"
import SkeletonGroup from "@/components/ui/SkeletonGroup.vue"
import StatTile from "@/components/ui/StatTile.vue"
import StatTileIcon from "@/components/ui/StatTileIcon.vue"
import StatTileLabel from "@/components/ui/StatTileLabel.vue"
import StatTileValue from "@/components/ui/StatTileValue.vue"
import TextField from "@/components/ui/TextField.vue"
import TextFieldDescription from "@/components/ui/TextFieldDescription.vue"
import TextFieldError from "@/components/ui/TextFieldError.vue"
import TextFieldLabel from "@/components/ui/TextFieldLabel.vue"
import TextFieldTextarea from "@/components/ui/TextFieldTextarea.vue"
import Timeline from "@/components/ui/Timeline.vue"
import TimelineContent from "@/components/ui/TimelineContent.vue"
import TimelineIndicator from "@/components/ui/TimelineIndicator.vue"
import TimelineItem from "@/components/ui/TimelineItem.vue"
import TimelineTime from "@/components/ui/TimelineTime.vue"
import TimelineTitle from "@/components/ui/TimelineTitle.vue"
import ToggleGroup from "@/components/ui/ToggleGroup.vue"
import ToggleGroupItem from "@/components/ui/ToggleGroupItem.vue"
import { toast } from "@/components/ui/Toast.vue"
import { DigIcon, type DigIconName } from "@/lib/icons"
import { formatCurrency, formatJalali, formatJalaliDateTime, formatNumber, toFaDigits, toSearchKey } from "@/lib/persian"
import { useIsMobile } from "@/lib/use-is-mobile"

// stock-images:begin
/** تصویرهای کتابخانهٔ دیگ (همان آدرس‌های `stockImages` نسخهٔ React). */
const stockImages: Record<string, { src: string; alt: string }> = {
  personWoman1: { src: "https://docs.digdesign.ir/images/person-woman-1.webp", alt: "پرترهٔ زنی با روسری" },
  personWoman2: { src: "https://docs.digdesign.ir/images/person-woman-2.webp", alt: "پرترهٔ زنی با کتِ طوسی" },
  personWoman3: { src: "https://docs.digdesign.ir/images/person-woman-3.webp", alt: "پرترهٔ زنی خندان" },
  personMan1: { src: "https://docs.digdesign.ir/images/person-man-1.webp", alt: "پرترهٔ مردی با لبخند" },
  personMan2: { src: "https://docs.digdesign.ir/images/person-man-2.webp", alt: "پرترهٔ مردی با تیشرتِ سفید" },
}
// stock-images:end

const AVATAR_ICON = "size-[95%] translate-y-1 text-[color-mix(in_oklab,var(--muted-foreground)_55%,var(--muted))]"

/** همان `avatarPhoto` نسخهٔ React: از روی نام، یکی از عکس‌های آماده را انتخاب می‌کند (گاهی هیچ، تا حروفِ اولِ نام بنشیند). */
function avatarPhoto(name: string, gender: "male" | "female"): string | undefined {
  let hash = 0
  for (const char of name) hash = (hash * 31 + char.charCodeAt(0)) >>> 0
  if (hash % 4 === 3) return undefined
  const pool = gender === "female" ? ["personWoman1", "personWoman2", "personWoman3"] : ["personMan1", "personMan2"]
  return stockImages[pool[hash % pool.length]].src
}

type SortDescriptor = { column: string; direction: "ascending" | "descending" }
type ExpenseStatus = "pending" | "approved" | "rejected"
type Category = "travel" | "lodging" | "equipment" | "software" | "ads" | "hospitality"
type Load = "loading" | "ready" | "error"

const CATEGORIES: Record<Category, string> = {
  travel: "سفر",
  lodging: "اقامت",
  equipment: "تجهیزات",
  software: "نرم‌افزار",
  ads: "تبلیغات",
  hospitality: "پذیرایی",
}
const CATEGORY_KEYS = Object.keys(CATEGORIES) as Category[]

const STATUS: Record<ExpenseStatus, { label: string; color: "warning" | "success" | "destructive" }> = {
  pending: { label: "در انتظار تأیید", color: "warning" },
  approved: { label: "تأییدشده", color: "success" },
  rejected: { label: "ردشده", color: "destructive" },
}

type HistoryItem = { at: string; actor: string; text: string; tone: "default" | "primary" | "success" | "destructive" }

type Expense = {
  id: string
  title: string
  vendor: string
  category: Category
  amount: number
  date: string
  employee: { name: string; dept: string; gender: "male" | "female" }
  status: ExpenseStatus
  method: string
  project: string
  receipt?: { name: string; size: string }
  note: string
  policy?: string
  rejectReason?: string
  history: HistoryItem[]
  /** نخستین ثبتِ تصمیم برای این هزینه با خطای شبکه تمام می‌شود (برای نمایشِ حالتِ خطا). */
  failOnce?: boolean
}

const REVIEWER = "الهام کاظمی"
const MIN_REASON = 10
const MAX_REASON = 300
const PAGE_SIZE = 6

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
const millions = (value: number) => `${formatNumber(value / 1_000_000, { maximumFractionDigits: 1 })} میلیون`

function seed(
  id: string,
  title: string,
  vendor: string,
  category: Category,
  amount: number,
  date: string,
  employee: Expense["employee"],
  status: ExpenseStatus,
  extra: Partial<Expense> & Pick<Expense, "method" | "project" | "note">,
): Expense {
  const history: HistoryItem[] = [{ at: date, actor: employee.name, text: "هزینه را ثبت کرد.", tone: "default" }]
  if (extra.receipt) history.push({ at: date, actor: employee.name, text: "رسید را پیوست کرد.", tone: "primary" })
  if (status === "approved") history.push({ at: date, actor: REVIEWER, text: "هزینه را تأیید کرد.", tone: "success" })
  if (status === "rejected") history.push({ at: date, actor: REVIEWER, text: "هزینه را رد کرد.", tone: "destructive" })
  return { id, title, vendor, category, amount, date, employee, status, history, ...extra }
}

const RECEIPT = { name: "receipt.pdf", size: "۲۴۰ کیلوبایت" }
const OVER_LIMIT = "مبلغ از سقف ۵۰ میلیون تومانی بالاتر است و تأیید مدیر مالی هم لازم دارد."

const INITIAL_EXPENSES: Expense[] = [
  seed("EXP-1521", "بلیت هواپیما تهران، شیراز", "ایران‌ایر", "travel", 14_800_000, "2026-10-26T09:10:00", { name: "سارا محمدی", dept: "فروش", gender: "female" }, "pending", { method: "کارت سازمانی", project: "نمایشگاه شیراز", note: "رفت‌وآمد تیم فروش برای نمایشگاه سالانه.", receipt: RECEIPT, failOnce: true }),
  seed("EXP-1520", "اشتراک سالانهٔ ابزار طراحی", "فیگما", "software", 96_000_000, "2026-10-25T14:30:00", { name: "کیان مرادی", dept: "محصول", gender: "male" }, "pending", { method: "کارت سازمانی", project: "زیرساخت محصول", note: "تمدید ۱۶ صندلی برای تیم طراحی.", policy: OVER_LIMIT, receipt: { name: "invoice.pdf", size: "۱٫۲ مگابایت" } }),
  seed("EXP-1519", "اقامت سه‌شبه در هتل", "هتل پارسیان", "lodging", 21_600_000, "2026-10-24T18:05:00", { name: "نیلوفر احمدی", dept: "فروش", gender: "female" }, "pending", { method: "پرداخت شخصی", project: "نمایشگاه شیراز", note: "اقامت در زمان برگزاری نمایشگاه.", receipt: RECEIPT }),
  seed("EXP-1518", "کمپین تبلیغات جست‌وجو، مهر", "گوگل ادز", "ads", 38_500_000, "2026-10-23T11:20:00", { name: "پرهام نوری", dept: "بازاریابی", gender: "male" }, "pending", { method: "کارت سازمانی", project: "کمپین پاییز", note: "بودجهٔ ماهانهٔ کمپین پاییزه.", receipt: RECEIPT }),
  seed("EXP-1517", "ناهار کاری با مشتری", "رستوران نایب", "hospitality", 3_200_000, "2026-10-22T13:40:00", { name: "مهسا توکلی", dept: "فروش", gender: "female" }, "approved", { method: "پرداخت شخصی", project: "حساب‌های کلیدی", note: "جلسهٔ تمدید قرارداد.", receipt: RECEIPT }),
  seed("EXP-1516", "نمایشگر ۲۷ اینچ برای تیم فنی", "دیجی‌کالا", "equipment", 27_900_000, "2026-10-21T10:00:00", { name: "بهراد صالحی", dept: "مهندسی", gender: "male" }, "approved", { method: "کارت سازمانی", project: "زیرساخت محصول", note: "دو دستگاه برای کارمندان تازه‌وارد.", receipt: RECEIPT }),
  seed("EXP-1515", "دورهٔ آنلاین امنیت وب", "فرادرس", "software", 4_900_000, "2026-10-20T16:15:00", { name: "ترانه شریفی", dept: "مهندسی", gender: "female" }, "approved", { method: "پرداخت شخصی", project: "ارتقای مهارت", note: "طبق برنامهٔ آموزشی سالانه.", receipt: RECEIPT }),
  seed("EXP-1514", "تاکسی اینترنتی، هفتهٔ آخر", "اسنپ", "travel", 1_850_000, "2026-10-19T20:30:00", { name: "امیر رضایی", dept: "فروش", gender: "male" }, "rejected", { method: "پرداخت شخصی", project: "حساب‌های کلیدی", note: "چند سفر درون‌شهری.", rejectReason: "رسید تاکسی‌ها پیوست نشده بود؛ لطفاً رسیدها را اضافه و دوباره ثبت کنید." }),
  seed("EXP-1513", "اشتراک سرور آزمایشی", "لیارا", "software", 12_400_000, "2026-10-18T09:50:00", { name: "کیان مرادی", dept: "محصول", gender: "male" }, "approved", { method: "کارت سازمانی", project: "زیرساخت محصول", note: "سرور آزمایشیِ ماهانه.", receipt: RECEIPT }),
  seed("EXP-1512", "چاپ بروشور نمایشگاه", "چاپ نگار", "ads", 9_300_000, "2026-10-17T12:00:00", { name: "پرهام نوری", dept: "بازاریابی", gender: "male" }, "pending", { method: "پرداخت شخصی", project: "نمایشگاه شیراز", note: "۵۰۰ بروشور رنگی.", receipt: RECEIPT }),
  seed("EXP-1511", "پذیرایی جلسهٔ فصلی", "کافه رست", "hospitality", 2_150_000, "2026-10-16T15:45:00", { name: "نیلوفر احمدی", dept: "فروش", gender: "female" }, "approved", { method: "کارت سازمانی", project: "عملیات", note: "جلسهٔ مرور فصل.", receipt: RECEIPT }),
  seed("EXP-1510", "اقامت یک‌شبهٔ تبریز", "هتل شهریار", "lodging", 6_800_000, "2026-10-15T08:20:00", { name: "مهسا توکلی", dept: "فروش", gender: "female" }, "rejected", { method: "پرداخت شخصی", project: "حساب‌های کلیدی", note: "سفر کاری تبریز.", receipt: RECEIPT, rejectReason: "سفر قبل از ثبت درخواست مجوز انجام شده است." }),
  seed("EXP-1509", "لپ‌تاپ برای استخدام تازه", "آیتی‌بازار", "equipment", 74_000_000, "2026-10-14T11:10:00", { name: "بهراد صالحی", dept: "مهندسی", gender: "male" }, "pending", { method: "کارت سازمانی", project: "زیرساخت محصول", note: "یک دستگاه با پردازندهٔ قوی.", policy: OVER_LIMIT, receipt: { name: "laptop.pdf", size: "۱٫۱ مگابایت" } }),
  seed("EXP-1508", "هدیهٔ مشتریان پایان سال", "گالری آوا", "hospitality", 18_200_000, "2026-10-06T13:15:00", { name: "پرهام نوری", dept: "بازاریابی", gender: "male" }, "rejected", { method: "پرداخت شخصی", project: "کمپین پاییز", note: "۳۰ بسته هدیه.", receipt: RECEIPT, rejectReason: "بودجهٔ هدیه در این فصل بسته شده است؛ در فصل بعد ثبت شود." }),
]

/**
 * هزینه‌های سازمان با نمای دوتایی: فهرستِ جمع‌وجور کنارِ پنلِ جزئیاتِ ثابت (در موبایل کشو).
 * همان صفحهٔ `expense-approval-split` نسخهٔ React. در React منطقِ مشترک در هوکِ useExpenseApproval و چند زیرکامپوننتِ همان فایل
 * (بالای صفحه، خلاصه، فیلترها، اسکلت، خطا، حالتِ خالی، صفحه‌بند، پنلِ جزئیات) بود؛ این‌جا همه یک‌جا در همین
 * اسکریپت و قالب آمده‌اند. حالتِ پنلِ جزئیات (فرمِ رد و فوکوس‌ها) با watch روی هزینهٔ نمایش‌داده‌شده ریست می‌شود.
 */

// ---- منطقِ مشترکِ صفحه: دریافت، فیلتر، مرتب‌سازی، تصمیم با بازگردانی و بازگشتِ فوکوس.
const expenses = ref<Expense[]>(INITIAL_EXPENSES)
const load = ref<Load>("loading")
const query = ref("")
const status = ref<"all" | ExpenseStatus>("all")
const category = ref<"all" | Category>("all")
const sort = ref<SortDescriptor>({ column: "date", direction: "descending" })
const page = ref(1)
const selectedId = ref<string | null>(null)
const open = ref(false)
const busy = ref<"approve" | "reject" | null>(null)
const actionError = ref<string | null>(null)
const failed = new Set<string>()

async function fetchData(mode: "ok" | "error" | "empty" = "ok") {
  load.value = "loading"
  await wait(900)
  if (mode === "error") {
    load.value = "error"
    return
  }
  expenses.value = mode === "empty" ? [] : INITIAL_EXPENSES
  load.value = "ready"
}

// دریافتِ اولیه؛ با API واقعی جایش را بدهید.
onMounted(() => fetchData())

const filtered = computed(() => {
  const key = toSearchKey(query.value)
  return expenses.value
    .filter(
      (e) =>
        (status.value === "all" || e.status === status.value) &&
        (category.value === "all" || e.category === category.value) &&
        toSearchKey(`${e.title} ${e.vendor} ${e.employee.name} ${e.id}`).includes(key),
    )
    .sort((a, b) => {
      const order =
        sort.value.column === "amount"
          ? a.amount - b.amount
          : sort.value.column === "employee"
            ? a.employee.name.localeCompare(b.employee.name, "fa")
            : a.date.localeCompare(b.date)
      return sort.value.direction === "ascending" ? order : -order
    })
})
const pageCount = computed(() => Math.max(1, Math.ceil(filtered.value.length / PAGE_SIZE)))
const currentPage = computed(() => Math.min(page.value, pageCount.value))
const rows = computed(() => filtered.value.slice((currentPage.value - 1) * PAGE_SIZE, currentPage.value * PAGE_SIZE))
const filtersActive = computed(() => !!query.value || status.value !== "all" || category.value !== "all")

function clearFilters() {
  query.value = ""
  status.value = "all"
  category.value = "all"
  page.value = 1
}
function onSearch(value: string) {
  query.value = value
  page.value = 1
}
function onStatusChange(value: string | string[] | undefined) {
  if (!value) return
  status.value = value as "all" | ExpenseStatus
  page.value = 1
}
function onCategoryChange(value: string | string[] | undefined) {
  category.value = value as "all" | Category
  page.value = 1
}

function openExpense(id: string) {
  selectedId.value = id
  actionError.value = null
  open.value = true
}

// بستنِ پنل فوکوس را به دکمهٔ همان ردیف برمی‌گرداند (هر بازکننده data-open-id دارد).
function onOpenChange(next: boolean) {
  open.value = next
  if (next) return
  const id = selectedId.value
  setTimeout(() => document.querySelector<HTMLElement>(`[data-open-id="${id}"]`)?.focus(), 50)
}

async function decide(id: string, next: "approved" | "rejected", reason?: string) {
  const before = expenses.value.find((e) => e.id === id)
  if (!before) return
  busy.value = next === "approved" ? "approve" : "reject"
  actionError.value = null
  await wait(800)
  if (before.failOnce && !failed.has(id)) {
    failed.add(id)
    busy.value = null
    actionError.value = "ارتباط با سرور برقرار نشد. هزینه تغییری نکرد؛ دوباره تلاش کنید."
    toast.error("تصمیم ثبت نشد", { description: "اتصال قطع شد؛ دوباره تلاش کنید." })
    return
  }
  const entry: HistoryItem =
    next === "approved"
      ? { at: new Date().toISOString(), actor: REVIEWER, text: "هزینه را تأیید کرد.", tone: "success" }
      : { at: new Date().toISOString(), actor: REVIEWER, text: "هزینه را رد کرد.", tone: "destructive" }
  expenses.value = expenses.value.map((e) => (e.id === id ? { ...e, status: next, rejectReason: reason, history: [...e.history, entry] } : e))
  busy.value = null
  toast.success(next === "approved" ? "هزینه تأیید شد" : "هزینه رد شد", {
    description: before.title,
    action: {
      label: "بازگردانی",
      onClick: () => {
        expenses.value = expenses.value.map((e) => (e.id === id ? before : e))
        toast("به وضعیت «در انتظار تأیید» برگشت.")
      },
    },
  })
}
const approve = (id: string) => decide(id, "approved")
const reject = (id: string, reason: string) => decide(id, "rejected", reason)

const count = (s: ExpenseStatus) => expenses.value.filter((e) => e.status === s).length
const pending = computed(() => expenses.value.filter((e) => e.status === "pending"))
const selected = computed(() => expenses.value.find((e) => e.id === selectedId.value) ?? null)
const metrics = computed<{ icon: DigIconName; tone: "warning" | "success" | "destructive" | "primary"; label: string; value: string; hint: string }[]>(() => [
  { icon: "clock", tone: "warning", label: "در انتظار تأیید", value: toFaDigits(pending.value.length), hint: `${millions(pending.value.reduce((n, e) => n + e.amount, 0))} تومان` },
  { icon: "check-circle", tone: "success", label: "تأییدشده این ماه", value: millions(expenses.value.filter((e) => e.status === "approved").reduce((n, e) => n + e.amount, 0)), hint: `${toFaDigits(count("approved"))} هزینه` },
  { icon: "circle-x", tone: "destructive", label: "ردشده", value: toFaDigits(count("rejected")), hint: "با دلیل ثبت شده" },
  { icon: "receipt", tone: "primary", label: "کل هزینه‌ها", value: toFaDigits(expenses.value.length), hint: "در این ماه" },
])

// ---- پنلِ جزئیات: «رد» دلیلِ حداقل ۱۰ نویسه می‌خواهد؛ خطای درون‌خطی، فوکوس به فیلد و بازگشتِ فوکوس به دکمهٔ رد.
const isMobileLg = useIsMobile(1024)
const current = computed(() => selected.value ?? pending.value[0] ?? null)
const panelExpense = computed(() => (!isMobileLg.value ? current.value : selected.value))
const rejecting = ref(false)
const reason = ref("")
const touched = ref(false)
const rejectForm = ref<HTMLElement | null>(null)
const resultEl = ref<HTMLElement | null>(null)
let lastStatus: ExpenseStatus | undefined = panelExpense.value?.status

const focusReason = () => rejectForm.value?.querySelector<HTMLElement>("textarea")?.focus()

// با تغییرِ هزینه، فرمِ رد از نو شروع می‌شود.
watch(
  () => panelExpense.value?.id,
  () => {
    rejecting.value = false
    reason.value = ""
    touched.value = false
    lastStatus = panelExpense.value?.status
  },
)
watch(rejecting, async (value) => {
  if (!value) return
  await nextTick()
  focusReason()
})
// بعد از ثبتِ تصمیم دکمه‌ها می‌روند؛ فوکوس به نتیجه می‌رود تا گم نشود.
watch(
  () => panelExpense.value?.status,
  async (next) => {
    if (lastStatus === "pending" && next && next !== "pending") {
      await nextTick()
      resultEl.value?.focus()
    }
    lastStatus = next
  },
)

const trimmed = computed(() => reason.value.trim())
const reasonError = computed(() =>
  !trimmed.value
    ? "نوشتن دلیل برای ردِ هزینه الزامی است."
    : trimmed.value.length < MIN_REASON
      ? `دلیل را کمی کامل‌تر بنویسید؛ دست‌کم ${toFaDigits(MIN_REASON)} نویسه.`
      : undefined,
)
const showError = computed(() => touched.value && !!reasonError.value)

function submitReject() {
  touched.value = true
  if (reasonError.value) return focusReason()
  if (panelExpense.value) reject(panelExpense.value.id, trimmed.value)
}
function cancelReject() {
  rejecting.value = false
  reason.value = ""
  touched.value = false
  requestAnimationFrame(() => document.querySelector<HTMLElement>("[data-reject-trigger]")?.focus())
}

const wide = computed(() => !isMobileLg.value)
</script>

<template>
  <ControlSize size="lg" as-child>
    <div class="mx-auto flex w-full max-w-7xl flex-col gap-6 p-4 sm:p-6 lg:p-8">
        <PageHeader>
          <PageHeading>
            <PageTitle>هزینه‌های سازمان</PageTitle>
            <PageDescription>هزینه‌های ثبت‌شدهٔ تیم‌ها را بررسی و تأیید یا رد کنید.</PageDescription>
          </PageHeading>
          <PageActions>
            <Badge variant="soft" color="warning" class="h-7 px-3 text-sm">{{ toFaDigits(pending.length) }} مورد منتظر شماست</Badge>
            <!-- فقط برای نمایش: حالت‌های بارگذاری، خطا و خالی را شبیه‌سازی می‌کند؛ در محصول حذفش کنید. -->
            <DropdownMenu>
              <DropdownMenuTrigger as-child>
                <Button variant="outline" size="icon" aria-label="شبیه‌سازی وضعیت‌ها">
                  <DigIcon name="settings" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel>شبیه‌سازی وضعیت‌ها</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem @select="fetchData('ok')">بارگذاری دوباره</DropdownMenuItem>
                <DropdownMenuItem @select="fetchData('error')">خطای دریافت</DropdownMenuItem>
                <DropdownMenuItem @select="fetchData('empty')">فهرست خالی</DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </PageActions>
        </PageHeader>

        <Alert v-if="load === 'error'" color="destructive" role="alert">
          <AlertTitle>هزینه‌ها بارگذاری نشد</AlertTitle>
          <AlertDescription>اتصال به سرور قطع شد. داده‌ای از دست نرفته است.</AlertDescription>
          <AlertAction>
            <Button variant="outline" @click="fetchData()">
              <DigIcon name="refresh" />
              تلاش دوباره
            </Button>
          </AlertAction>
        </Alert>
        <template v-else>
          <section aria-label="خلاصهٔ هزینه‌ها" class="grid grid-cols-2 gap-3 lg:grid-cols-4">
            <StatTile v-for="m in metrics" :key="m.label" class="gap-3 p-4">
              <div class="flex items-center gap-3">
                <StatTileIcon :tone="m.tone" class="size-9"><DigIcon :name="m.icon" /></StatTileIcon>
                <StatTileLabel>{{ m.label }}</StatTileLabel>
              </div>
              <Skeleton v-if="load === 'loading'" class="h-8 w-24" />
              <StatTileValue v-else class="text-xl sm:text-3xl">{{ m.value }}</StatTileValue>
              <span class="text-xs text-muted-foreground">{{ load === "loading" ? " " : m.hint }}</span>
            </StatTile>
          </section>
          <div class="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_26rem]">
            <section aria-label="فهرست هزینه‌ها" class="flex min-w-0 flex-col gap-6">
              <div class="flex flex-col gap-4">
              <div class="flex flex-col gap-3 lg:flex-row lg:items-center">
                <SearchField aria-label="جست‌وجوی هزینه" placeholder="جست‌وجوی عنوان، فروشنده یا نام ثبت‌کننده" :model-value="query" class="min-w-0 flex-1 lg:max-w-sm" @update:model-value="onSearch" />
                <div class="min-w-0 overflow-x-auto lg:ms-auto">
                  <ControlSize size="lg" mobile-size="default" as-child>
                    <ToggleGroup type="single" variant="segmented" aria-label="فیلتر وضعیت" :value="status" @update:value="onStatusChange">
                      <ToggleGroupItem value="all">همه</ToggleGroupItem>
                      <ToggleGroupItem value="pending">در انتظار</ToggleGroupItem>
                      <ToggleGroupItem value="approved">تأییدشده</ToggleGroupItem>
                      <ToggleGroupItem value="rejected">ردشده</ToggleGroupItem>
                    </ToggleGroup>
                  </ControlSize>
                </div>
                <Select :value="category" @update:value="onCategoryChange">
                  <SelectTrigger aria-label="فیلتر دسته" class="w-full lg:w-44">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">همهٔ دسته‌ها</SelectItem>
                    <SelectItem v-for="c in CATEGORY_KEYS" :key="c" :value="c">{{ CATEGORIES[c] }}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div class="flex min-h-8 flex-wrap items-center gap-2" aria-live="polite">
                <span class="text-sm text-muted-foreground">{{ load === "loading" ? "در حال دریافت…" : `${toFaDigits(filtered.length)} هزینه` }}</span>
                <Chip v-if="query">
                  «{{ query }}»
                  <ChipCloseButton aria-label="پاک‌کردن جست‌وجو" @click="query = ''">
                    <span aria-hidden="true">×</span>
                  </ChipCloseButton>
                </Chip>
                <Chip v-if="category !== 'all'">
                  {{ CATEGORIES[category] }}
                  <ChipCloseButton aria-label="پاک‌کردن فیلتر دسته" @click="category = 'all'">
                    <span aria-hidden="true">×</span>
                  </ChipCloseButton>
                </Chip>
                <Button v-if="filtersActive" variant="ghost" size="sm" @click="clearFilters">پاک‌کردنِ فیلترها</Button>
              </div>
            </div>
              <SkeletonGroup v-if="load === 'loading'" aria-busy="true" aria-label="در حال بارگذاری هزینه‌ها" class="flex flex-col gap-3 rounded-xl border border-border bg-card p-4">
              <div v-for="i in 6" :key="i" class="flex items-center gap-4">
                <Skeleton class="size-9 rounded-full" />
                <Skeleton class="h-4 flex-1" />
                <Skeleton class="hidden h-4 w-24 sm:block" />
                <Skeleton class="h-6 w-20" />
              </div>
            </SkeletonGroup>
              <EmptyState v-else-if="filtered.length === 0" variant="bordered" class="py-14">
              <DigIcon name="search" aria-hidden="true" class="size-8 text-placeholder" />
              <EmptyStateTitle>{{ expenses.length === 0 ? "هنوز هزینه‌ای ثبت نشده" : "هزینه‌ای با این مشخصات نیست" }}</EmptyStateTitle>
              <EmptyStateDescription>{{ expenses.length === 0 ? "وقتی همکاران هزینه ثبت کنند، برای بررسی همین‌جا می‌آید." : "عبارت دیگری را جست‌وجو کنید یا فیلترها را بردارید." }}</EmptyStateDescription>
              <EmptyStateActions>
                <Button variant="outline" @click="expenses.length === 0 ? fetchData() : clearFilters()">
                  <DigIcon v-if="expenses.length === 0" name="refresh" />
                  {{ expenses.length === 0 ? "بارگذاری دوباره" : "پاک‌کردنِ فیلترها" }}
                </Button>
              </EmptyStateActions>
            </EmptyState>
              <ListGroup v-else>
                <li v-for="e in filtered" :key="e.id" class="flex min-w-0 items-center gap-3 py-3.5" :class="{ 'bg-muted': wide && current?.id === e.id }">
                      <Avatar :alt="e.employee.name" :src="avatarPhoto(e.employee.name, e.employee.gender)" class="ring-1 ring-border">
                  <template #icon><DigIcon :name="e.employee.gender === 'male' ? 'avatar-male' : 'avatar-female'" :class="AVATAR_ICON" /></template>
                </Avatar>
                      <span class="flex min-w-0 flex-1 flex-col gap-0.5">
                        <span class="truncate text-sm font-medium">{{ e.title }}</span>
                        <span class="truncate text-xs text-muted-foreground">{{ e.employee.name }}، {{ formatJalali(e.date) }}</span>
                      </span>
                      <span class="flex shrink-0 flex-col items-end gap-1">
                      <span class="text-sm font-semibold tabular-nums">{{ formatCurrency(e.amount) }}</span>
                      <Badge variant="soft" :color="STATUS[e.status].color" class="gap-1.5">
                        <span aria-hidden="true" class="size-1.5 rounded-full bg-current" />
                        {{ STATUS[e.status].label }}
                      </Badge>
                    </span>
                      <Button variant="ghost" size="icon" :data-open-id="e.id" :aria-current="wide && current?.id === e.id ? true : undefined" :aria-label="`مشاهدهٔ جزئیات ${e.title}`" @click="openExpense(e.id)">
                        <DigIcon name="chevron-left" class="ltr:rotate-180" />
                      </Button>
                    </li>
              </ListGroup>
            </section>
            <Card v-if="wide && load === 'ready'" class="sticky top-6 flex max-h-[calc(100dvh-3rem)] flex-col overflow-hidden p-0" aria-label="جزئیات هزینه">
              <EmptyState v-if="!panelExpense" class="py-14">
                <EmptyStateTitle>هزینه‌ای برای بررسی نیست</EmptyStateTitle>
                <EmptyStateDescription>یک هزینه را از فهرست انتخاب کنید.</EmptyStateDescription>
              </EmptyState>
              <template v-if="panelExpense">
          <div class="flex flex-col gap-2 border-b border-border p-5 pe-14">
            <div class="flex flex-wrap items-center gap-2">
              <Badge variant="soft" :color="STATUS[panelExpense.status].color" class="gap-1.5">
                    <span aria-hidden="true" class="size-1.5 rounded-full bg-current" />
                    {{ STATUS[panelExpense.status].label }}
                  </Badge>
              <bdi dir="ltr" class="text-xs text-muted-foreground">{{ panelExpense.id }}</bdi>
            </div>
            <h2 class="text-xl font-semibold leading-snug">{{ panelExpense.title }}</h2>
            <p class="text-sm text-muted-foreground">{{ panelExpense.vendor }}، {{ CATEGORIES[panelExpense.category] }}</p>
          </div>

          <div class="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto p-5">
            <p class="text-3xl font-semibold tabular-nums">{{ formatCurrency(panelExpense.amount) }}</p>

            <div ref="resultEl" tabindex="-1" class="flex flex-col gap-3 outline-none">
              <Alert v-if="panelExpense.policy && panelExpense.status === 'pending'" color="warning" variant="flat">
                <AlertTitle>نیاز به توجه</AlertTitle>
                <AlertDescription>{{ panelExpense.policy }}</AlertDescription>
              </Alert>
              <Alert v-if="panelExpense.status === 'rejected' && panelExpense.rejectReason" color="destructive" variant="flat">
                <AlertTitle>دلیل رد</AlertTitle>
                <AlertDescription>{{ panelExpense.rejectReason }}</AlertDescription>
              </Alert>
              <Alert v-if="panelExpense.status === 'approved'" color="success" variant="flat">
                <AlertTitle>این هزینه تأیید شده است</AlertTitle>
                <AlertDescription>مبلغ در نوبت پرداخت بعدی تسویه می‌شود.</AlertDescription>
              </Alert>
              <Alert v-if="actionError" color="destructive" role="alert">
                <AlertTitle>ثبت نشد</AlertTitle>
                <AlertDescription>{{ actionError }}</AlertDescription>
              </Alert>
            </div>

            <div class="flex items-center gap-3">
              <Avatar size="default" :alt="panelExpense.employee.name" :src="avatarPhoto(panelExpense.employee.name, panelExpense.employee.gender)" class="ring-1 ring-border">
                  <template #icon><DigIcon :name="panelExpense.employee.gender === 'male' ? 'avatar-male' : 'avatar-female'" :class="AVATAR_ICON" /></template>
                </Avatar>
              <div class="flex min-w-0 flex-col">
                <span class="font-medium">{{ panelExpense.employee.name }}</span>
                <span class="text-sm text-muted-foreground">بخش {{ panelExpense.employee.dept }}</span>
              </div>
            </div>

            <DescriptionList :columns="2">
              <DescriptionListItem>
                <DescriptionListTerm>تاریخ ثبت</DescriptionListTerm>
                <DescriptionListDetails>{{ formatJalaliDateTime(panelExpense.date) }}</DescriptionListDetails>
              </DescriptionListItem>
              <DescriptionListItem>
                <DescriptionListTerm>روش پرداخت</DescriptionListTerm>
                <DescriptionListDetails>{{ panelExpense.method }}</DescriptionListDetails>
              </DescriptionListItem>
              <DescriptionListItem>
                <DescriptionListTerm>پروژه</DescriptionListTerm>
                <DescriptionListDetails>{{ panelExpense.project }}</DescriptionListDetails>
              </DescriptionListItem>
              <DescriptionListItem>
                <DescriptionListTerm>دسته</DescriptionListTerm>
                <DescriptionListDetails>{{ CATEGORIES[panelExpense.category] }}</DescriptionListDetails>
              </DescriptionListItem>
              <DescriptionListItem full>
                <DescriptionListTerm>توضیح</DescriptionListTerm>
                <DescriptionListDetails>{{ panelExpense.note }}</DescriptionListDetails>
              </DescriptionListItem>
            </DescriptionList>

            <section :aria-labelledby="`receipt-${panelExpense.id}`" class="flex flex-col gap-3">
              <h3 :id="`receipt-${panelExpense.id}`" class="font-medium">رسید</h3>
              <ListGroup v-if="panelExpense.receipt">
                <ListRow :subtitle="panelExpense.receipt.size">
                  <template #leading><DigIcon name="file-text" aria-hidden="true" class="size-5" /></template>
                  <template #title><bdi dir="ltr">{{ panelExpense.receipt.name }}</bdi></template>
                </ListRow>
              </ListGroup>
              <p v-else class="text-sm text-muted-foreground">رسیدی پیوست نشده است.</p>
            </section>

            <section :aria-labelledby="`history-${panelExpense.id}`" class="flex flex-col gap-3">
              <h3 :id="`history-${panelExpense.id}`" class="font-medium">تاریخچه</h3>
              <Timeline>
                <TimelineItem v-for="(item, index) in [...panelExpense.history].reverse()" :key="index">
                  <TimelineIndicator :tone="item.tone" />
                  <TimelineContent>
                    <TimelineTitle class="font-normal">
                      <span class="font-semibold">{{ item.actor }}</span> {{ item.text }}
                    </TimelineTitle>
                    <TimelineTime :datetime="item.at">{{ formatJalaliDateTime(item.at) }}</TimelineTime>
                  </TimelineContent>
                </TimelineItem>
              </Timeline>
            </section>
          </div>

          <template v-if="panelExpense.status === 'pending'">
            <form v-if="rejecting" ref="rejectForm" novalidate class="flex flex-col gap-4 border-t border-border bg-subtle p-5" @submit.prevent="submitReject">
              <TextField :invalid="showError" required>
                <TextFieldLabel>دلیل رد هزینه</TextFieldLabel>
                <TextFieldTextarea
                  :rows="3"
                  :maxlength="MAX_REASON"
                  placeholder="مثلاً رسید پیوست نشده است"
                  :model-value="reason"
                  :disabled="busy === 'reject'"
                  @update:model-value="(value: string) => (reason = value)"
                  @blur="touched = true"
                />
                <TextFieldError v-if="showError">{{ reasonError }}</TextFieldError>
                <TextFieldDescription v-else>ثبت‌کننده این متن را می‌بیند. {{ toFaDigits(reason.length) }} از {{ toFaDigits(MAX_REASON) }} نویسه</TextFieldDescription>
              </TextField>
              <div class="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                <Button type="button" variant="outline" :disabled="busy === 'reject'" @click="cancelReject">انصراف</Button>
                <Button type="submit" color="destructive" :disabled="busy === 'reject'">{{ busy === "reject" ? "در حال ثبت…" : "ثبت رد هزینه" }}</Button>
              </div>
            </form>
            <div v-else class="flex flex-col-reverse gap-3 border-t border-border p-5 sm:flex-row sm:justify-end">
              <Button data-reject-trigger variant="outline" color="destructive" :disabled="busy !== null" @click="rejecting = true">
                <DigIcon name="circle-x" />
                رد هزینه
              </Button>
              <Button :disabled="busy !== null" @click="approve(panelExpense.id)">
                <DigIcon name="check-circle" />
                {{ busy === "approve" ? "در حال تأیید…" : "تأیید هزینه" }}
              </Button>
            </div>
          </template>
        </template>
            </Card>
          </div>
        </template>

<Sheet v-if="!wide" :open="open" @update:open="(next) => !busy && onOpenChange(next)">
          <ControlSize size="lg" as-child>
            <SheetContent class="flex w-full flex-col gap-0 p-0 sm:max-w-md">
              <SheetHeader class="sr-only">
                <SheetDescription>جزئیات هزینه و تصمیم‌گیری</SheetDescription>
              </SheetHeader>
              <template v-if="panelExpense">
          <div class="flex flex-col gap-2 border-b border-border p-5 pe-14">
            <div class="flex flex-wrap items-center gap-2">
              <Badge variant="soft" :color="STATUS[panelExpense.status].color" class="gap-1.5">
                    <span aria-hidden="true" class="size-1.5 rounded-full bg-current" />
                    {{ STATUS[panelExpense.status].label }}
                  </Badge>
              <bdi dir="ltr" class="text-xs text-muted-foreground">{{ panelExpense.id }}</bdi>
            </div>
            <SheetTitle class="text-xl leading-snug">{{ panelExpense.title }}</SheetTitle>
            <p class="text-sm text-muted-foreground">{{ panelExpense.vendor }}، {{ CATEGORIES[panelExpense.category] }}</p>
          </div>

          <div class="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto p-5">
            <p class="text-3xl font-semibold tabular-nums">{{ formatCurrency(panelExpense.amount) }}</p>

            <div ref="resultEl" tabindex="-1" class="flex flex-col gap-3 outline-none">
              <Alert v-if="panelExpense.policy && panelExpense.status === 'pending'" color="warning" variant="flat">
                <AlertTitle>نیاز به توجه</AlertTitle>
                <AlertDescription>{{ panelExpense.policy }}</AlertDescription>
              </Alert>
              <Alert v-if="panelExpense.status === 'rejected' && panelExpense.rejectReason" color="destructive" variant="flat">
                <AlertTitle>دلیل رد</AlertTitle>
                <AlertDescription>{{ panelExpense.rejectReason }}</AlertDescription>
              </Alert>
              <Alert v-if="panelExpense.status === 'approved'" color="success" variant="flat">
                <AlertTitle>این هزینه تأیید شده است</AlertTitle>
                <AlertDescription>مبلغ در نوبت پرداخت بعدی تسویه می‌شود.</AlertDescription>
              </Alert>
              <Alert v-if="actionError" color="destructive" role="alert">
                <AlertTitle>ثبت نشد</AlertTitle>
                <AlertDescription>{{ actionError }}</AlertDescription>
              </Alert>
            </div>

            <div class="flex items-center gap-3">
              <Avatar size="default" :alt="panelExpense.employee.name" :src="avatarPhoto(panelExpense.employee.name, panelExpense.employee.gender)" class="ring-1 ring-border">
                  <template #icon><DigIcon :name="panelExpense.employee.gender === 'male' ? 'avatar-male' : 'avatar-female'" :class="AVATAR_ICON" /></template>
                </Avatar>
              <div class="flex min-w-0 flex-col">
                <span class="font-medium">{{ panelExpense.employee.name }}</span>
                <span class="text-sm text-muted-foreground">بخش {{ panelExpense.employee.dept }}</span>
              </div>
            </div>

            <DescriptionList :columns="2">
              <DescriptionListItem>
                <DescriptionListTerm>تاریخ ثبت</DescriptionListTerm>
                <DescriptionListDetails>{{ formatJalaliDateTime(panelExpense.date) }}</DescriptionListDetails>
              </DescriptionListItem>
              <DescriptionListItem>
                <DescriptionListTerm>روش پرداخت</DescriptionListTerm>
                <DescriptionListDetails>{{ panelExpense.method }}</DescriptionListDetails>
              </DescriptionListItem>
              <DescriptionListItem>
                <DescriptionListTerm>پروژه</DescriptionListTerm>
                <DescriptionListDetails>{{ panelExpense.project }}</DescriptionListDetails>
              </DescriptionListItem>
              <DescriptionListItem>
                <DescriptionListTerm>دسته</DescriptionListTerm>
                <DescriptionListDetails>{{ CATEGORIES[panelExpense.category] }}</DescriptionListDetails>
              </DescriptionListItem>
              <DescriptionListItem full>
                <DescriptionListTerm>توضیح</DescriptionListTerm>
                <DescriptionListDetails>{{ panelExpense.note }}</DescriptionListDetails>
              </DescriptionListItem>
            </DescriptionList>

            <section :aria-labelledby="`receipt-${panelExpense.id}`" class="flex flex-col gap-3">
              <h3 :id="`receipt-${panelExpense.id}`" class="font-medium">رسید</h3>
              <ListGroup v-if="panelExpense.receipt">
                <ListRow :subtitle="panelExpense.receipt.size">
                  <template #leading><DigIcon name="file-text" aria-hidden="true" class="size-5" /></template>
                  <template #title><bdi dir="ltr">{{ panelExpense.receipt.name }}</bdi></template>
                </ListRow>
              </ListGroup>
              <p v-else class="text-sm text-muted-foreground">رسیدی پیوست نشده است.</p>
            </section>

            <section :aria-labelledby="`history-${panelExpense.id}`" class="flex flex-col gap-3">
              <h3 :id="`history-${panelExpense.id}`" class="font-medium">تاریخچه</h3>
              <Timeline>
                <TimelineItem v-for="(item, index) in [...panelExpense.history].reverse()" :key="index">
                  <TimelineIndicator :tone="item.tone" />
                  <TimelineContent>
                    <TimelineTitle class="font-normal">
                      <span class="font-semibold">{{ item.actor }}</span> {{ item.text }}
                    </TimelineTitle>
                    <TimelineTime :datetime="item.at">{{ formatJalaliDateTime(item.at) }}</TimelineTime>
                  </TimelineContent>
                </TimelineItem>
              </Timeline>
            </section>
          </div>

          <template v-if="panelExpense.status === 'pending'">
            <form v-if="rejecting" ref="rejectForm" novalidate class="flex flex-col gap-4 border-t border-border bg-subtle p-5" @submit.prevent="submitReject">
              <TextField :invalid="showError" required>
                <TextFieldLabel>دلیل رد هزینه</TextFieldLabel>
                <TextFieldTextarea
                  :rows="3"
                  :maxlength="MAX_REASON"
                  placeholder="مثلاً رسید پیوست نشده است"
                  :model-value="reason"
                  :disabled="busy === 'reject'"
                  @update:model-value="(value: string) => (reason = value)"
                  @blur="touched = true"
                />
                <TextFieldError v-if="showError">{{ reasonError }}</TextFieldError>
                <TextFieldDescription v-else>ثبت‌کننده این متن را می‌بیند. {{ toFaDigits(reason.length) }} از {{ toFaDigits(MAX_REASON) }} نویسه</TextFieldDescription>
              </TextField>
              <div class="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                <Button type="button" variant="outline" :disabled="busy === 'reject'" @click="cancelReject">انصراف</Button>
                <Button type="submit" color="destructive" :disabled="busy === 'reject'">{{ busy === "reject" ? "در حال ثبت…" : "ثبت رد هزینه" }}</Button>
              </div>
            </form>
            <div v-else class="flex flex-col-reverse gap-3 border-t border-border p-5 sm:flex-row sm:justify-end">
              <Button data-reject-trigger variant="outline" color="destructive" :disabled="busy !== null" @click="rejecting = true">
                <DigIcon name="circle-x" />
                رد هزینه
              </Button>
              <Button :disabled="busy !== null" @click="approve(panelExpense.id)">
                <DigIcon name="check-circle" />
                {{ busy === "approve" ? "در حال تأیید…" : "تأیید هزینه" }}
              </Button>
            </div>
          </template>
        </template>
            </SheetContent>
          </ControlSize>
        </Sheet>
    </div>
  </ControlSize>
</template>

کدِ این بلاک هنوز برای Svelte نوشته نشده است.

این موارد هنوز برای Svelte آماده نیستند: alertavatarbadgecardchipcontrol-sizedescription-listdropdown-menuempty-statelist-rowpage-compositionpaginationpersiansearch-fieldselectsheetskeletonstat-tiletabletext-fieldtimelinetoasttoggle-groupآیکون avatar-genderآیکون check-circleآیکون chevron-endآیکون circle-xآیکون clockآیکون file-textآیکون receiptآیکون refreshآیکون searchآیکون settings

کدِ React همین بلاک مرجع است. با MCP دیگ و get_block با framework="svelte" ایجنت آن را با کامپوننت‌های Svelte می‌سازد.

expense-approval-split.ts
import {
  Component,
  ChangeDetectionStrategy,
  signal,
  afterNextRender,
  computed,
  effect,
  untracked,
  ElementRef,
  viewChild,
} from "@angular/core"

import { DigControlSize } from "@/components/ui/control-size"
import {
  DigPageHeader,
  DigPageHeading,
  DigPageTitle,
  DigPageDescription,
  DigPageActions,
} from "@/components/ui/page-composition"
import { DigBadge } from "@/components/ui/badge"
import {
  DigDropdownMenu,
  DigDropdownMenuTrigger,
  DigDropdownMenuContent,
  DigDropdownMenuLabel,
  DigDropdownMenuSeparator,
  DigDropdownMenuItem,
} from "@/components/ui/dropdown-menu"
import { DigButton } from "@/components/ui/button"
import { DigIcon, type DigIconName } from "@/lib/icons"
import { DigAlert, DigAlertTitle, DigAlertDescription, DigAlertAction } from "@/components/ui/alert"
import { DigStatTile, DigStatTileIcon, DigStatTileLabel, DigStatTileValue } from "@/components/ui/stat-tile"
import { DigSkeleton, DigSkeletonGroup } from "@/components/ui/skeleton"
import { DigSearchField } from "@/components/ui/search-field"
import { DigToggleGroup, DigToggleGroupItem } from "@/components/ui/toggle-group"
import { DigSelect, DigSelectTrigger, DigSelectValue, DigSelectContent, DigSelectItem } from "@/components/ui/select"
import { DigChip, DigChipCloseButton } from "@/components/ui/chip"
import {
  DigEmptyState,
  DigEmptyStateTitle,
  DigEmptyStateDescription,
  DigEmptyStateActions,
} from "@/components/ui/empty-state"
import { DigListGroup, DigListRow, DigListRowLeading, DigListRowTitle } from "@/components/ui/list-row"
import { DigAvatar } from "@/components/ui/avatar"
import { DigCard } from "@/components/ui/card"
import {
  DigDescriptionList,
  DigDescriptionListItem,
  DigDescriptionListTerm,
  DigDescriptionListDetails,
} from "@/components/ui/description-list"
import {
  DigTimeline,
  DigTimelineItem,
  DigTimelineIndicator,
  DigTimelineContent,
  DigTimelineTitle,
  DigTimelineTime,
} from "@/components/ui/timeline"
import { DigTextField, DigTextFieldLabel, DigTextFieldError, DigTextFieldDescription } from "@/components/ui/text-field"
import { DigTextarea } from "@/components/ui/textarea"
import { DigSheet, DigSheetContent, DigSheetHeader, DigSheetDescription, DigSheetTitle } from "@/components/ui/sheet"
import { FormsModule } from "@angular/forms"
import { toast } from "@/components/ui/toast"
import {
  formatCurrency,
  formatJalali,
  formatJalaliDateTime,
  formatNumber,
  toFaDigits,
  toSearchKey,
} from "@/lib/persian"
import { useIsMobile } from "@/lib/use-is-mobile"

const stockImages: Record<string, { src: string; alt: string }> = {
  personWoman1: { src: "https://docs.digdesign.ir/images/person-woman-1.webp", alt: "پرترهٔ زنی با روسری" },
  personWoman2: { src: "https://docs.digdesign.ir/images/person-woman-2.webp", alt: "پرترهٔ زنی با کتِ طوسی" },
  personWoman3: { src: "https://docs.digdesign.ir/images/person-woman-3.webp", alt: "پرترهٔ زنی خندان" },
  personMan1: { src: "https://docs.digdesign.ir/images/person-man-1.webp", alt: "پرترهٔ مردی با لبخند" },
  personMan2: { src: "https://docs.digdesign.ir/images/person-man-2.webp", alt: "پرترهٔ مردی با تیشرتِ سفید" },
}

const AVATAR_ICON = "size-[95%] translate-y-1 text-[color-mix(in_oklab,var(--muted-foreground)_55%,var(--muted))]"

function avatarPhoto(name: string, gender: "male" | "female"): string | undefined {
  let hash = 0
  for (const char of name) hash = (hash * 31 + char.charCodeAt(0)) >>> 0
  if (hash % 4 === 3) return undefined
  const pool = gender === "female" ? ["personWoman1", "personWoman2", "personWoman3"] : ["personMan1", "personMan2"]
  return stockImages[pool[hash % pool.length]].src
}

type SortDescriptor = { column: string; direction: "ascending" | "descending" }

type ExpenseStatus = "pending" | "approved" | "rejected"

type Category = "travel" | "lodging" | "equipment" | "software" | "ads" | "hospitality"

type Load = "loading" | "ready" | "error"

const CATEGORIES: Record<Category, string> = {
  travel: "سفر",
  lodging: "اقامت",
  equipment: "تجهیزات",
  software: "نرم‌افزار",
  ads: "تبلیغات",
  hospitality: "پذیرایی",
}

const CATEGORY_KEYS = Object.keys(CATEGORIES) as Category[]

const STATUS: Record<ExpenseStatus, { label: string; color: "warning" | "success" | "destructive" }> = {
  pending: { label: "در انتظار تأیید", color: "warning" },
  approved: { label: "تأییدشده", color: "success" },
  rejected: { label: "ردشده", color: "destructive" },
}

type HistoryItem = { at: string; actor: string; text: string; tone: "default" | "primary" | "success" | "destructive" }

type Expense = {
  id: string
  title: string
  vendor: string
  category: Category
  amount: number
  date: string
  employee: { name: string; dept: string; gender: "male" | "female" }
  status: ExpenseStatus
  method: string
  project: string
  receipt?: { name: string; size: string }
  note: string
  policy?: string
  rejectReason?: string
  history: HistoryItem[]
  /** نخستین ثبتِ تصمیم برای این هزینه با خطای شبکه تمام می‌شود (برای نمایشِ حالتِ خطا). */
  failOnce?: boolean
}

const REVIEWER = "الهام کاظمی"

const MIN_REASON = 10

const MAX_REASON = 300

const PAGE_SIZE = 6

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

const millions = (value: number) => `${formatNumber(value / 1_000_000, { maximumFractionDigits: 1 })} میلیون`

const RECEIPT = { name: "receipt.pdf", size: "۲۴۰ کیلوبایت" }

const OVER_LIMIT = "مبلغ از سقف ۵۰ میلیون تومانی بالاتر است و تأیید مدیر مالی هم لازم دارد."

const failed = new Set<string>()

@Component({
  selector: "dig-block-expense-approval-split",
  imports: [
    DigControlSize,
    DigPageHeader,
    DigPageHeading,
    DigPageTitle,
    DigPageDescription,
    DigPageActions,
    DigBadge,
    DigDropdownMenu,
    DigDropdownMenuTrigger,
    DigDropdownMenuContent,
    DigDropdownMenuLabel,
    DigDropdownMenuSeparator,
    DigDropdownMenuItem,
    DigButton,
    DigIcon,
    DigAlert,
    DigAlertTitle,
    DigAlertDescription,
    DigAlertAction,
    DigStatTile,
    DigStatTileIcon,
    DigStatTileLabel,
    DigStatTileValue,
    DigSkeleton,
    DigSkeletonGroup,
    DigSearchField,
    DigToggleGroup,
    DigToggleGroupItem,
    DigSelect,
    DigSelectTrigger,
    DigSelectValue,
    DigSelectContent,
    DigSelectItem,
    DigChip,
    DigChipCloseButton,
    DigEmptyState,
    DigEmptyStateTitle,
    DigEmptyStateDescription,
    DigEmptyStateActions,
    DigListGroup,
    DigListRow,
    DigListRowLeading,
    DigListRowTitle,
    DigAvatar,
    DigCard,
    DigDescriptionList,
    DigDescriptionListItem,
    DigDescriptionListTerm,
    DigDescriptionListDetails,
    DigTimeline,
    DigTimelineItem,
    DigTimelineIndicator,
    DigTimelineContent,
    DigTimelineTitle,
    DigTimelineTime,
    DigTextField,
    DigTextFieldLabel,
    DigTextFieldError,
    DigTextFieldDescription,
    DigTextarea,
    DigSheet,
    DigSheetContent,
    DigSheetHeader,
    DigSheetDescription,
    DigSheetTitle,
    FormsModule,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div digControlSize="lg" class="mx-auto flex w-full max-w-7xl flex-col gap-6 p-4 sm:p-6 lg:p-8">
      <header digPageHeader>
        <div digPageHeading>
          <h1 digPageTitle>هزینه‌های سازمان</h1>
          <p digPageDescription>هزینه‌های ثبت‌شدهٔ تیم‌ها را بررسی و تأیید یا رد کنید.</p>
        </div>
        <div digPageActions>
          <span digBadge variant="soft" color="warning" class="h-7 px-3 text-sm"
            >{{ toFaDigits(pending().length) }} مورد منتظر شماست</span
          >
          <!-- فقط برای نمایش: حالت‌های بارگذاری، خطا و خالی را شبیه‌سازی می‌کند؛ در محصول حذفش کنید. -->
          <ng-container digDropdownMenu
            ><button
              digDropdownMenuTrigger
              digButton
              type="button"
              variant="outline"
              size="icon"
              aria-label="شبیه‌سازی وضعیت‌ها"
            >
              <svg digIcon="settings"></svg>
            </button>
            <div digDropdownMenuContent align="end">
              <div digDropdownMenuLabel>شبیه‌سازی وضعیت‌ها</div>
              <div digDropdownMenuSeparator></div>
              <div digDropdownMenuItem (select)="fetchData('ok')">بارگذاری دوباره</div>
              <div digDropdownMenuItem (select)="fetchData('error')">خطای دریافت</div>
              <div digDropdownMenuItem (select)="fetchData('empty')">فهرست خالی</div>
            </div></ng-container
          >
        </div>
      </header>

      @if (load() === "error") {
        <div digAlert color="destructive" role="alert">
          <div digAlertTitle>هزینه‌ها بارگذاری نشد</div>
          <div digAlertDescription>اتصال به سرور قطع شد. داده‌ای از دست نرفته است.</div>
          <div digAlertAction>
            <button digButton type="button" variant="outline" (click)="fetchData()">
              <svg digIcon="refresh"></svg>
              تلاش دوباره
            </button>
          </div>
        </div>
      } @else {
        <section aria-label="خلاصهٔ هزینه‌ها" class="grid grid-cols-2 gap-3 lg:grid-cols-4">
          @for (m of metrics(); track m.label) {
            <div digStatTile class="gap-3 p-4">
              <div class="flex items-center gap-3">
                <span digStatTileIcon [tone]="m.tone" class="size-9"><svg [digIcon]="m.icon"></svg></span>
                <div digStatTileLabel>{{ m.label }}</div>
              </div>
              @if (load() === "loading") {
                <div digSkeleton class="h-8 w-24"></div>
              } @else {
                <div digStatTileValue class="text-xl sm:text-3xl">{{ m.value }}</div>
              }
              <span class="text-xs text-muted-foreground">{{ load() === "loading" ? " " : m.hint }}</span>
            </div>
          }
        </section>
        <div class="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_26rem]">
          <section aria-label="فهرست هزینه‌ها" class="flex min-w-0 flex-col gap-6">
            <div class="flex flex-col gap-4">
              <div class="flex flex-col gap-3 lg:flex-row lg:items-center">
                <div
                  digSearchField
                  aria-label="جست‌وجوی هزینه"
                  placeholder="جست‌وجوی عنوان، فروشنده یا نام ثبت‌کننده"
                  [value]="query()"
                  class="min-w-0 flex-1 lg:max-w-sm"
                  (valueChange)="onSearch($event)"
                ></div>
                <div class="min-w-0 overflow-x-auto lg:ms-auto">
                  <div digControlSize="lg" mobileSize="default">
                    <div
                      digToggleGroup
                      type="single"
                      variant="segmented"
                      aria-label="فیلتر وضعیت"
                      [value]="status()"
                      (valueChange)="onStatusChange($event)"
                    >
                      <button digToggleGroupItem value="all">همه</button>
                      <button digToggleGroupItem value="pending">در انتظار</button>
                      <button digToggleGroupItem value="approved">تأییدشده</button>
                      <button digToggleGroupItem value="rejected">ردشده</button>
                    </div>
                  </div>
                </div>
                <ng-container digSelect [value]="category()" (valueChange)="onCategoryChange($event)"
                  ><button digSelectTrigger aria-label="فیلتر دسته" class="w-full lg:w-44">
                    <span digSelectValue></span>
                  </button>
                  <div digSelectContent>
                    <div digSelectItem value="all">همهٔ دسته‌ها</div>
                    @for (c of CATEGORY_KEYS; track c) {
                      <div digSelectItem [value]="c">{{ CATEGORIES[c] }}</div>
                    }
                  </div></ng-container
                >
              </div>
              <div class="flex min-h-8 flex-wrap items-center gap-2" aria-live="polite">
                <span class="text-sm text-muted-foreground">{{
                  load() === "loading" ? "در حال دریافت…" : \`\${toFaDigits(filtered().length)} هزینه\`
                }}</span>
                @if (query()) {
                  <span digChip>
                    «{{ query() }}»
                    <button digChipCloseButton aria-label="پاک‌کردن جست‌وجو" (click)="query.set('')">
                      <span aria-hidden="true">×</span>
                    </button></span
                  >
                }
                @if (category() !== "all") {
                  <span digChip
                    >{{ categoryLabel() }}
                    <button digChipCloseButton aria-label="پاک‌کردن فیلتر دسته" (click)="category.set('all')">
                      <span aria-hidden="true">×</span>
                    </button></span
                  >
                }
                @if (filtersActive()) {
                  <button digButton type="button" variant="ghost" size="sm" (click)="clearFilters()">
                    پاک‌کردنِ فیلترها
                  </button>
                }
              </div>
            </div>
            @if (load() === "loading") {
              <div
                digSkeletonGroup
                aria-busy="true"
                aria-label="در حال بارگذاری هزینه‌ها"
                class="flex flex-col gap-3 rounded-xl border border-border bg-card p-4"
              >
                @for (i of [1, 2, 3, 4, 5, 6]; track i) {
                  <div class="flex items-center gap-4">
                    <div digSkeleton class="size-9 rounded-full"></div>
                    <div digSkeleton class="h-4 flex-1"></div>
                    <div digSkeleton class="hidden h-4 w-24 sm:block"></div>
                    <div digSkeleton class="h-6 w-20"></div>
                  </div>
                }
              </div>
            } @else if (filtered().length === 0) {
              <div digEmptyState variant="bordered" class="py-14">
                <svg digIcon="search" aria-hidden="true" class="size-8 text-placeholder"></svg>
                <h3 digEmptyStateTitle>
                  {{ expenses().length === 0 ? "هنوز هزینه‌ای ثبت نشده" : "هزینه‌ای با این مشخصات نیست" }}
                </h3>
                <p digEmptyStateDescription>
                  {{
                    expenses().length === 0
                      ? "وقتی همکاران هزینه ثبت کنند، برای بررسی همین‌جا می‌آید."
                      : "عبارت دیگری را جست‌وجو کنید یا فیلترها را بردارید."
                  }}
                </p>
                <div digEmptyStateActions>
                  <button
                    digButton
                    type="button"
                    variant="outline"
                    (click)="expenses().length === 0 ? fetchData() : clearFilters()"
                  >
                    @if (expenses().length === 0) {
                      <svg digIcon="refresh"></svg>
                    }
                    {{ expenses().length === 0 ? "بارگذاری دوباره" : "پاک‌کردنِ فیلترها" }}
                  </button>
                </div>
              </div>
            } @else {
              <ul digListGroup>
                @for (e of filtered(); track e.id) {
                  <li
                    class="flex min-w-0 items-center gap-3 py-3.5"
                    [class]="{ 'bg-muted': wide() && current()?.id === e.id }"
                  >
                    <span
                      digAvatar
                      [alt]="e.employee.name"
                      [src]="avatarPhoto(e.employee.name, e.employee.gender)"
                      class="ring-1 ring-border"
                      [iconName]="e.employee.gender === 'male' ? 'avatar-male' : 'avatar-female'"
                    ></span>
                    <span class="flex min-w-0 flex-1 flex-col gap-0.5"
                      ><span class="truncate text-sm font-medium">{{ e.title }}</span>
                      <span class="truncate text-xs text-muted-foreground"
                        >{{ e.employee.name }}، {{ formatJalali(e.date) }}</span
                      ></span
                    >
                    <span class="flex shrink-0 flex-col items-end gap-1"
                      ><span class="text-sm font-semibold tabular-nums">{{ formatCurrency(e.amount) }}</span>
                      <span digBadge variant="soft" [color]="STATUS[e.status].color" class="gap-1.5"
                        ><span aria-hidden="true" class="size-1.5 rounded-full bg-current"></span>
                        {{ STATUS[e.status].label }}</span
                      ></span
                    >
                    <button
                      digButton
                      type="button"
                      variant="ghost"
                      size="icon"
                      [attr.data-open-id]="e.id"
                      [attr.aria-current]="wide() && current()?.id === e.id ? true : undefined"
                      [attr.aria-label]="\`مشاهدهٔ جزئیات \${e.title}\`"
                      (click)="openExpense(e.id)"
                    >
                      <svg digIcon="chevron-left" class="ltr:rotate-180"></svg>
                    </button>
                  </li>
                }
              </ul>
            }
          </section>
          @if (wide() && load() === "ready") {
            <div
              digCard
              class="sticky top-6 flex max-h-[calc(100dvh-3rem)] flex-col overflow-hidden p-0"
              aria-label="جزئیات هزینه"
            >
              @if (!panelExpense()) {
                <div digEmptyState class="py-14">
                  <h3 digEmptyStateTitle>هزینه‌ای برای بررسی نیست</h3>
                  <p digEmptyStateDescription>یک هزینه را از فهرست انتخاب کنید.</p>
                </div>
              }
              @if (panelExpense(); as panelExpense) {
                <div class="flex flex-col gap-2 border-b border-border p-5 pe-14">
                  <div class="flex flex-wrap items-center gap-2">
                    <span digBadge variant="soft" [color]="STATUS[panelExpense.status].color" class="gap-1.5"
                      ><span aria-hidden="true" class="size-1.5 rounded-full bg-current"></span>
                      {{ STATUS[panelExpense.status].label }}</span
                    >
                    <bdi dir="ltr" class="text-xs text-muted-foreground">{{ panelExpense.id }}</bdi>
                  </div>
                  <h2 class="text-xl font-semibold leading-snug">{{ panelExpense.title }}</h2>
                  <p class="text-sm text-muted-foreground">
                    {{ panelExpense.vendor }}، {{ CATEGORIES[panelExpense.category] }}
                  </p>
                </div>

                <div class="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto p-5">
                  <p class="text-3xl font-semibold tabular-nums">{{ formatCurrency(panelExpense.amount) }}</p>

                  <div #resultEl tabindex="-1" class="flex flex-col gap-3 outline-none">
                    @if (panelExpense.policy && panelExpense.status === "pending") {
                      <div digAlert color="warning" variant="flat">
                        <div digAlertTitle>نیاز به توجه</div>
                        <div digAlertDescription>{{ panelExpense.policy }}</div>
                      </div>
                    }
                    @if (panelExpense.status === "rejected" && panelExpense.rejectReason) {
                      <div digAlert color="destructive" variant="flat">
                        <div digAlertTitle>دلیل رد</div>
                        <div digAlertDescription>{{ panelExpense.rejectReason }}</div>
                      </div>
                    }
                    @if (panelExpense.status === "approved") {
                      <div digAlert color="success" variant="flat">
                        <div digAlertTitle>این هزینه تأیید شده است</div>
                        <div digAlertDescription>مبلغ در نوبت پرداخت بعدی تسویه می‌شود.</div>
                      </div>
                    }
                    @if (actionError()) {
                      <div digAlert color="destructive" role="alert">
                        <div digAlertTitle>ثبت نشد</div>
                        <div digAlertDescription>{{ actionError() }}</div>
                      </div>
                    }
                  </div>

                  <div class="flex items-center gap-3">
                    <span
                      digAvatar
                      size="default"
                      [alt]="panelExpense.employee.name"
                      [src]="avatarPhoto(panelExpense.employee.name, panelExpense.employee.gender)"
                      class="ring-1 ring-border"
                      [iconName]="panelExpense.employee.gender === 'male' ? 'avatar-male' : 'avatar-female'"
                    ></span>
                    <div class="flex min-w-0 flex-col">
                      <span class="font-medium">{{ panelExpense.employee.name }}</span>
                      <span class="text-sm text-muted-foreground">بخش {{ panelExpense.employee.dept }}</span>
                    </div>
                  </div>

                  <dl digDescriptionList [columns]="2">
                    <div digDescriptionListItem>
                      <dt digDescriptionListTerm>تاریخ ثبت</dt>
                      <dd digDescriptionListDetails>{{ formatJalaliDateTime(panelExpense.date) }}</dd>
                    </div>
                    <div digDescriptionListItem>
                      <dt digDescriptionListTerm>روش پرداخت</dt>
                      <dd digDescriptionListDetails>{{ panelExpense.method }}</dd>
                    </div>
                    <div digDescriptionListItem>
                      <dt digDescriptionListTerm>پروژه</dt>
                      <dd digDescriptionListDetails>{{ panelExpense.project }}</dd>
                    </div>
                    <div digDescriptionListItem>
                      <dt digDescriptionListTerm>دسته</dt>
                      <dd digDescriptionListDetails>{{ CATEGORIES[panelExpense.category] }}</dd>
                    </div>
                    <div digDescriptionListItem full>
                      <dt digDescriptionListTerm>توضیح</dt>
                      <dd digDescriptionListDetails>{{ panelExpense.note }}</dd>
                    </div>
                  </dl>

                  <section [attr.aria-labelledby]="\`receipt-\${panelExpense.id}\`" class="flex flex-col gap-3">
                    <h3 [id]="\`receipt-\${panelExpense.id}\`" class="font-medium">رسید</h3>
                    @if (panelExpense.receipt) {
                      <ul digListGroup>
                        <li digListRow [subtitle]="panelExpense.receipt.size">
                          <span digListRowLeading
                            ><svg digIcon="file-text" aria-hidden="true" class="size-5"></svg></span
                          ><span digListRowTitle
                            ><bdi dir="ltr">{{ panelExpense.receipt.name }}</bdi></span
                          >
                        </li>
                      </ul>
                    } @else {
                      <p class="text-sm text-muted-foreground">رسیدی پیوست نشده است.</p>
                    }
                  </section>

                  <section [attr.aria-labelledby]="\`history-\${panelExpense.id}\`" class="flex flex-col gap-3">
                    <h3 [id]="\`history-\${panelExpense.id}\`" class="font-medium">تاریخچه</h3>
                    <ol digTimeline>
                      @for (item of [...panelExpense.history].reverse(); track $index; let index = $index) {
                        <li digTimelineItem>
                          <span digTimelineIndicator [tone]="item.tone"></span>
                          <div digTimelineContent>
                            <div digTimelineTitle class="font-normal">
                              <span class="font-semibold">{{ item.actor }}</span> {{ item.text }}
                            </div>
                            <time digTimelineTime [attr.datetime]="item.at">{{ formatJalaliDateTime(item.at) }}</time>
                          </div>
                        </li>
                      }
                    </ol>
                  </section>
                </div>

                @if (panelExpense.status === "pending") {
                  @if (rejecting()) {
                    <form
                      #rejectForm
                      novalidate
                      class="flex flex-col gap-4 border-t border-border bg-subtle p-5"
                      (submit)="$event.preventDefault(); submitReject()"
                    >
                      <div digTextField [invalid]="showError()" required>
                        <label digTextFieldLabel>دلیل رد هزینه</label>
                        <textarea
                          digTextarea
                          [rows]="3"
                          [maxlength]="MAX_REASON"
                          placeholder="مثلاً رسید پیوست نشده است"
                          [ngModel]="reason()"
                          [disabled]="busy() === 'reject'"
                          [ngModelOptions]="{ standalone: true }"
                          (ngModelChange)="reason.set($event)"
                          (blur)="touched.set(true)"
                        ></textarea>
                        @if (showError()) {
                          <p digTextFieldError>{{ reasonError() }}</p>
                        } @else {
                          <p digTextFieldDescription>
                            ثبت‌کننده این متن را می‌بیند. {{ toFaDigits(reason().length) }} از
                            {{ toFaDigits(MAX_REASON) }} نویسه
                          </p>
                        }
                      </div>
                      <div class="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                        <button
                          digButton
                          type="button"
                          variant="outline"
                          [disabled]="busy() === 'reject'"
                          (click)="cancelReject()"
                        >
                          انصراف
                        </button>
                        <button digButton type="submit" color="destructive" [disabled]="busy() === 'reject'">
                          {{ busy() === "reject" ? "در حال ثبت…" : "ثبت رد هزینه" }}
                        </button>
                      </div>
                    </form>
                  } @else {
                    <div class="flex flex-col-reverse gap-3 border-t border-border p-5 sm:flex-row sm:justify-end">
                      <button
                        digButton
                        type="button"
                        data-reject-trigger
                        variant="outline"
                        color="destructive"
                        [disabled]="busy() !== null"
                        (click)="rejecting.set(true)"
                      >
                        <svg digIcon="circle-x"></svg>
                        رد هزینه
                      </button>
                      <button digButton type="button" [disabled]="busy() !== null" (click)="approve(panelExpense.id)">
                        <svg digIcon="check-circle"></svg> {{ busy() === "approve" ? "در حال تأیید…" : "تأیید هزینه" }}
                      </button>
                    </div>
                  }
                }
              }
            </div>
          }
        </div>
      }

      @if (!wide()) {
        <ng-container digSheet [open]="open()" (openChange)="!busy() && onOpenChange($event)"
          ><div digControlSize="lg">
            <div digSheetContent class="flex w-full flex-col gap-0 p-0 sm:max-w-md">
              <div digSheetHeader class="sr-only"><p digSheetDescription>جزئیات هزینه و تصمیم‌گیری</p></div>
              @if (panelExpense(); as panelExpense) {
                <div class="flex flex-col gap-2 border-b border-border p-5 pe-14">
                  <div class="flex flex-wrap items-center gap-2">
                    <span digBadge variant="soft" [color]="STATUS[panelExpense.status].color" class="gap-1.5"
                      ><span aria-hidden="true" class="size-1.5 rounded-full bg-current"></span>
                      {{ STATUS[panelExpense.status].label }}</span
                    >
                    <bdi dir="ltr" class="text-xs text-muted-foreground">{{ panelExpense.id }}</bdi>
                  </div>
                  <h2 digSheetTitle class="text-xl leading-snug">{{ panelExpense.title }}</h2>
                  <p class="text-sm text-muted-foreground">
                    {{ panelExpense.vendor }}، {{ CATEGORIES[panelExpense.category] }}
                  </p>
                </div>

                <div class="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto p-5">
                  <p class="text-3xl font-semibold tabular-nums">{{ formatCurrency(panelExpense.amount) }}</p>

                  <div #resultEl tabindex="-1" class="flex flex-col gap-3 outline-none">
                    @if (panelExpense.policy && panelExpense.status === "pending") {
                      <div digAlert color="warning" variant="flat">
                        <div digAlertTitle>نیاز به توجه</div>
                        <div digAlertDescription>{{ panelExpense.policy }}</div>
                      </div>
                    }
                    @if (panelExpense.status === "rejected" && panelExpense.rejectReason) {
                      <div digAlert color="destructive" variant="flat">
                        <div digAlertTitle>دلیل رد</div>
                        <div digAlertDescription>{{ panelExpense.rejectReason }}</div>
                      </div>
                    }
                    @if (panelExpense.status === "approved") {
                      <div digAlert color="success" variant="flat">
                        <div digAlertTitle>این هزینه تأیید شده است</div>
                        <div digAlertDescription>مبلغ در نوبت پرداخت بعدی تسویه می‌شود.</div>
                      </div>
                    }
                    @if (actionError()) {
                      <div digAlert color="destructive" role="alert">
                        <div digAlertTitle>ثبت نشد</div>
                        <div digAlertDescription>{{ actionError() }}</div>
                      </div>
                    }
                  </div>

                  <div class="flex items-center gap-3">
                    <span
                      digAvatar
                      size="default"
                      [alt]="panelExpense.employee.name"
                      [src]="avatarPhoto(panelExpense.employee.name, panelExpense.employee.gender)"
                      class="ring-1 ring-border"
                      [iconName]="panelExpense.employee.gender === 'male' ? 'avatar-male' : 'avatar-female'"
                    ></span>
                    <div class="flex min-w-0 flex-col">
                      <span class="font-medium">{{ panelExpense.employee.name }}</span>
                      <span class="text-sm text-muted-foreground">بخش {{ panelExpense.employee.dept }}</span>
                    </div>
                  </div>

                  <dl digDescriptionList [columns]="2">
                    <div digDescriptionListItem>
                      <dt digDescriptionListTerm>تاریخ ثبت</dt>
                      <dd digDescriptionListDetails>{{ formatJalaliDateTime(panelExpense.date) }}</dd>
                    </div>
                    <div digDescriptionListItem>
                      <dt digDescriptionListTerm>روش پرداخت</dt>
                      <dd digDescriptionListDetails>{{ panelExpense.method }}</dd>
                    </div>
                    <div digDescriptionListItem>
                      <dt digDescriptionListTerm>پروژه</dt>
                      <dd digDescriptionListDetails>{{ panelExpense.project }}</dd>
                    </div>
                    <div digDescriptionListItem>
                      <dt digDescriptionListTerm>دسته</dt>
                      <dd digDescriptionListDetails>{{ CATEGORIES[panelExpense.category] }}</dd>
                    </div>
                    <div digDescriptionListItem full>
                      <dt digDescriptionListTerm>توضیح</dt>
                      <dd digDescriptionListDetails>{{ panelExpense.note }}</dd>
                    </div>
                  </dl>

                  <section [attr.aria-labelledby]="\`receipt-\${panelExpense.id}\`" class="flex flex-col gap-3">
                    <h3 [id]="\`receipt-\${panelExpense.id}\`" class="font-medium">رسید</h3>
                    @if (panelExpense.receipt) {
                      <ul digListGroup>
                        <li digListRow [subtitle]="panelExpense.receipt.size">
                          <span digListRowLeading
                            ><svg digIcon="file-text" aria-hidden="true" class="size-5"></svg></span
                          ><span digListRowTitle
                            ><bdi dir="ltr">{{ panelExpense.receipt.name }}</bdi></span
                          >
                        </li>
                      </ul>
                    } @else {
                      <p class="text-sm text-muted-foreground">رسیدی پیوست نشده است.</p>
                    }
                  </section>

                  <section [attr.aria-labelledby]="\`history-\${panelExpense.id}\`" class="flex flex-col gap-3">
                    <h3 [id]="\`history-\${panelExpense.id}\`" class="font-medium">تاریخچه</h3>
                    <ol digTimeline>
                      @for (item of [...panelExpense.history].reverse(); track $index; let index = $index) {
                        <li digTimelineItem>
                          <span digTimelineIndicator [tone]="item.tone"></span>
                          <div digTimelineContent>
                            <div digTimelineTitle class="font-normal">
                              <span class="font-semibold">{{ item.actor }}</span> {{ item.text }}
                            </div>
                            <time digTimelineTime [attr.datetime]="item.at">{{ formatJalaliDateTime(item.at) }}</time>
                          </div>
                        </li>
                      }
                    </ol>
                  </section>
                </div>

                @if (panelExpense.status === "pending") {
                  @if (rejecting()) {
                    <form
                      #rejectForm
                      novalidate
                      class="flex flex-col gap-4 border-t border-border bg-subtle p-5"
                      (submit)="$event.preventDefault(); submitReject()"
                    >
                      <div digTextField [invalid]="showError()" required>
                        <label digTextFieldLabel>دلیل رد هزینه</label>
                        <textarea
                          digTextarea
                          [rows]="3"
                          [maxlength]="MAX_REASON"
                          placeholder="مثلاً رسید پیوست نشده است"
                          [ngModel]="reason()"
                          [disabled]="busy() === 'reject'"
                          [ngModelOptions]="{ standalone: true }"
                          (ngModelChange)="reason.set($event)"
                          (blur)="touched.set(true)"
                        ></textarea>
                        @if (showError()) {
                          <p digTextFieldError>{{ reasonError() }}</p>
                        } @else {
                          <p digTextFieldDescription>
                            ثبت‌کننده این متن را می‌بیند. {{ toFaDigits(reason().length) }} از
                            {{ toFaDigits(MAX_REASON) }} نویسه
                          </p>
                        }
                      </div>
                      <div class="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                        <button
                          digButton
                          type="button"
                          variant="outline"
                          [disabled]="busy() === 'reject'"
                          (click)="cancelReject()"
                        >
                          انصراف
                        </button>
                        <button digButton type="submit" color="destructive" [disabled]="busy() === 'reject'">
                          {{ busy() === "reject" ? "در حال ثبت…" : "ثبت رد هزینه" }}
                        </button>
                      </div>
                    </form>
                  } @else {
                    <div class="flex flex-col-reverse gap-3 border-t border-border p-5 sm:flex-row sm:justify-end">
                      <button
                        digButton
                        type="button"
                        data-reject-trigger
                        variant="outline"
                        color="destructive"
                        [disabled]="busy() !== null"
                        (click)="rejecting.set(true)"
                      >
                        <svg digIcon="circle-x"></svg>
                        رد هزینه
                      </button>
                      <button digButton type="button" [disabled]="busy() !== null" (click)="approve(panelExpense.id)">
                        <svg digIcon="check-circle"></svg> {{ busy() === "approve" ? "در حال تأیید…" : "تأیید هزینه" }}
                      </button>
                    </div>
                  }
                }
              }
            </div>
          </div></ng-container
        >
      }
    </div>
  `,
})
export class ExpenseApprovalSplitBlock {
  range(count: number) {
    return Array.from({ length: count }, (_, index) => index + 1)
  }

  readonly toFaDigits = toFaDigits

  readonly formatJalaliDateTime = formatJalaliDateTime

  readonly formatJalali = formatJalali

  readonly formatCurrency = formatCurrency

  readonly MAX_REASON = MAX_REASON

  readonly STATUS = STATUS

  readonly CATEGORY_KEYS = CATEGORY_KEYS

  readonly CATEGORIES = CATEGORIES

  readonly avatarPhoto = avatarPhoto

  seed(
    id: string,
    title: string,
    vendor: string,
    category: Category,
    amount: number,
    date: string,
    employee: Expense["employee"],
    status: ExpenseStatus,
    extra: Partial<Expense> & Pick<Expense, "method" | "project" | "note">
  ): Expense {
    const history: HistoryItem[] = [{ at: date, actor: employee.name, text: "هزینه را ثبت کرد.", tone: "default" }]
    if (extra.receipt) history.push({ at: date, actor: employee.name, text: "رسید را پیوست کرد.", tone: "primary" })
    if (status === "approved") history.push({ at: date, actor: REVIEWER, text: "هزینه را تأیید کرد.", tone: "success" })
    if (status === "rejected")
      history.push({ at: date, actor: REVIEWER, text: "هزینه را رد کرد.", tone: "destructive" })
    return { id, title, vendor, category, amount, date, employee, status, history, ...extra }
  }

  readonly INITIAL_EXPENSES: Expense[] = [
    this.seed(
      "EXP-1521",
      "بلیت هواپیما تهران، شیراز",
      "ایران‌ایر",
      "travel",
      14_800_000,
      "2026-10-26T09:10:00",
      { name: "سارا محمدی", dept: "فروش", gender: "female" },
      "pending",
      {
        method: "کارت سازمانی",
        project: "نمایشگاه شیراز",
        note: "رفت‌وآمد تیم فروش برای نمایشگاه سالانه.",
        receipt: RECEIPT,
        failOnce: true,
      }
    ),
    this.seed(
      "EXP-1520",
      "اشتراک سالانهٔ ابزار طراحی",
      "فیگما",
      "software",
      96_000_000,
      "2026-10-25T14:30:00",
      { name: "کیان مرادی", dept: "محصول", gender: "male" },
      "pending",
      {
        method: "کارت سازمانی",
        project: "زیرساخت محصول",
        note: "تمدید ۱۶ صندلی برای تیم طراحی.",
        policy: OVER_LIMIT,
        receipt: { name: "invoice.pdf", size: "۱٫۲ مگابایت" },
      }
    ),
    this.seed(
      "EXP-1519",
      "اقامت سه‌شبه در هتل",
      "هتل پارسیان",
      "lodging",
      21_600_000,
      "2026-10-24T18:05:00",
      { name: "نیلوفر احمدی", dept: "فروش", gender: "female" },
      "pending",
      { method: "پرداخت شخصی", project: "نمایشگاه شیراز", note: "اقامت در زمان برگزاری نمایشگاه.", receipt: RECEIPT }
    ),
    this.seed(
      "EXP-1518",
      "کمپین تبلیغات جست‌وجو، مهر",
      "گوگل ادز",
      "ads",
      38_500_000,
      "2026-10-23T11:20:00",
      { name: "پرهام نوری", dept: "بازاریابی", gender: "male" },
      "pending",
      { method: "کارت سازمانی", project: "کمپین پاییز", note: "بودجهٔ ماهانهٔ کمپین پاییزه.", receipt: RECEIPT }
    ),
    this.seed(
      "EXP-1517",
      "ناهار کاری با مشتری",
      "رستوران نایب",
      "hospitality",
      3_200_000,
      "2026-10-22T13:40:00",
      { name: "مهسا توکلی", dept: "فروش", gender: "female" },
      "approved",
      { method: "پرداخت شخصی", project: "حساب‌های کلیدی", note: "جلسهٔ تمدید قرارداد.", receipt: RECEIPT }
    ),
    this.seed(
      "EXP-1516",
      "نمایشگر ۲۷ اینچ برای تیم فنی",
      "دیجی‌کالا",
      "equipment",
      27_900_000,
      "2026-10-21T10:00:00",
      { name: "بهراد صالحی", dept: "مهندسی", gender: "male" },
      "approved",
      { method: "کارت سازمانی", project: "زیرساخت محصول", note: "دو دستگاه برای کارمندان تازه‌وارد.", receipt: RECEIPT }
    ),
    this.seed(
      "EXP-1515",
      "دورهٔ آنلاین امنیت وب",
      "فرادرس",
      "software",
      4_900_000,
      "2026-10-20T16:15:00",
      { name: "ترانه شریفی", dept: "مهندسی", gender: "female" },
      "approved",
      { method: "پرداخت شخصی", project: "ارتقای مهارت", note: "طبق برنامهٔ آموزشی سالانه.", receipt: RECEIPT }
    ),
    this.seed(
      "EXP-1514",
      "تاکسی اینترنتی، هفتهٔ آخر",
      "اسنپ",
      "travel",
      1_850_000,
      "2026-10-19T20:30:00",
      { name: "امیر رضایی", dept: "فروش", gender: "male" },
      "rejected",
      {
        method: "پرداخت شخصی",
        project: "حساب‌های کلیدی",
        note: "چند سفر درون‌شهری.",
        rejectReason: "رسید تاکسی‌ها پیوست نشده بود؛ لطفاً رسیدها را اضافه و دوباره ثبت کنید.",
      }
    ),
    this.seed(
      "EXP-1513",
      "اشتراک سرور آزمایشی",
      "لیارا",
      "software",
      12_400_000,
      "2026-10-18T09:50:00",
      { name: "کیان مرادی", dept: "محصول", gender: "male" },
      "approved",
      { method: "کارت سازمانی", project: "زیرساخت محصول", note: "سرور آزمایشیِ ماهانه.", receipt: RECEIPT }
    ),
    this.seed(
      "EXP-1512",
      "چاپ بروشور نمایشگاه",
      "چاپ نگار",
      "ads",
      9_300_000,
      "2026-10-17T12:00:00",
      { name: "پرهام نوری", dept: "بازاریابی", gender: "male" },
      "pending",
      { method: "پرداخت شخصی", project: "نمایشگاه شیراز", note: "۵۰۰ بروشور رنگی.", receipt: RECEIPT }
    ),
    this.seed(
      "EXP-1511",
      "پذیرایی جلسهٔ فصلی",
      "کافه رست",
      "hospitality",
      2_150_000,
      "2026-10-16T15:45:00",
      { name: "نیلوفر احمدی", dept: "فروش", gender: "female" },
      "approved",
      { method: "کارت سازمانی", project: "عملیات", note: "جلسهٔ مرور فصل.", receipt: RECEIPT }
    ),
    this.seed(
      "EXP-1510",
      "اقامت یک‌شبهٔ تبریز",
      "هتل شهریار",
      "lodging",
      6_800_000,
      "2026-10-15T08:20:00",
      { name: "مهسا توکلی", dept: "فروش", gender: "female" },
      "rejected",
      {
        method: "پرداخت شخصی",
        project: "حساب‌های کلیدی",
        note: "سفر کاری تبریز.",
        receipt: RECEIPT,
        rejectReason: "سفر قبل از ثبت درخواست مجوز انجام شده است.",
      }
    ),
    this.seed(
      "EXP-1509",
      "لپ‌تاپ برای استخدام تازه",
      "آیتی‌بازار",
      "equipment",
      74_000_000,
      "2026-10-14T11:10:00",
      { name: "بهراد صالحی", dept: "مهندسی", gender: "male" },
      "pending",
      {
        method: "کارت سازمانی",
        project: "زیرساخت محصول",
        note: "یک دستگاه با پردازندهٔ قوی.",
        policy: OVER_LIMIT,
        receipt: { name: "laptop.pdf", size: "۱٫۱ مگابایت" },
      }
    ),
    this.seed(
      "EXP-1508",
      "هدیهٔ مشتریان پایان سال",
      "گالری آوا",
      "hospitality",
      18_200_000,
      "2026-10-06T13:15:00",
      { name: "پرهام نوری", dept: "بازاریابی", gender: "male" },
      "rejected",
      {
        method: "پرداخت شخصی",
        project: "کمپین پاییز",
        note: "۳۰ بسته هدیه.",
        receipt: RECEIPT,
        rejectReason: "بودجهٔ هدیه در این فصل بسته شده است؛ در فصل بعد ثبت شود.",
      }
    ),
  ]

  readonly expenses = signal<Expense[]>(this.INITIAL_EXPENSES)

  readonly load = signal<Load>("loading")

  readonly query = signal("")

  readonly status = signal<"all" | ExpenseStatus>("all")

  readonly category = signal<"all" | Category>("all")

  readonly sort = signal<SortDescriptor>({ column: "date", direction: "descending" })

  readonly page = signal(1)

  readonly selectedId = signal<string | null>(null)

  readonly open = signal(false)

  readonly busy = signal<"approve" | "reject" | null>(null)

  readonly actionError = signal<string | null>(null)

  async fetchData(mode: "ok" | "error" | "empty" = "ok") {
    this.load.set("loading")
    await wait(900)
    if (mode === "error") {
      this.load.set("error")
      return
    }
    this.expenses.set(mode === "empty" ? [] : this.INITIAL_EXPENSES)
    this.load.set("ready")
  }

  readonly filtered = computed(() => {
    const key = toSearchKey(this.query())
    return this.expenses()
      .filter(
        (e) =>
          (this.status() === "all" || e.status === this.status()) &&
          (this.category() === "all" || e.category === this.category()) &&
          toSearchKey(`${e.title} ${e.vendor} ${e.employee.name} ${e.id}`).includes(key)
      )
      .sort((a, b) => {
        const order =
          this.sort().column === "amount"
            ? a.amount - b.amount
            : this.sort().column === "employee"
              ? a.employee.name.localeCompare(b.employee.name, "fa")
              : a.date.localeCompare(b.date)
        return this.sort().direction === "ascending" ? order : -order
      })
  })

  readonly pageCount = computed(() => Math.max(1, Math.ceil(this.filtered().length / PAGE_SIZE)))

  readonly currentPage = computed(() => Math.min(this.page(), this.pageCount()))

  readonly rows = computed(() =>
    this.filtered().slice((this.currentPage() - 1) * PAGE_SIZE, this.currentPage() * PAGE_SIZE)
  )

  readonly filtersActive = computed(() => !!this.query() || this.status() !== "all" || this.category() !== "all")

  clearFilters() {
    this.query.set("")
    this.status.set("all")
    this.category.set("all")
    this.page.set(1)
  }

  onSearch(value: string) {
    this.query.set(value)
    this.page.set(1)
  }

  onStatusChange(value: string | string[] | undefined) {
    if (!value) return
    this.status.set(value as "all" | ExpenseStatus)
    this.page.set(1)
  }

  onCategoryChange(value: string | string[] | undefined) {
    this.category.set(value as "all" | Category)
    this.page.set(1)
  }

  openExpense(id: string) {
    this.selectedId.set(id)
    this.actionError.set(null)
    this.open.set(true)
  }

  onOpenChange(next: boolean) {
    this.open.set(next)
    if (next) return
    const id = this.selectedId()
    setTimeout(() => document.querySelector<HTMLElement>(`[data-open-id="${id}"]`)?.focus(), 50)
  }

  async decide(id: string, next: "approved" | "rejected", reason?: string) {
    const before = this.expenses().find((e) => e.id === id)
    if (!before) return
    this.busy.set(next === "approved" ? "approve" : "reject")
    this.actionError.set(null)
    await wait(800)
    if (before.failOnce && !failed.has(id)) {
      failed.add(id)
      this.busy.set(null)
      this.actionError.set("ارتباط با سرور برقرار نشد. هزینه تغییری نکرد؛ دوباره تلاش کنید.")
      toast.error("تصمیم ثبت نشد", { description: "اتصال قطع شد؛ دوباره تلاش کنید." })
      return
    }
    const entry: HistoryItem =
      next === "approved"
        ? { at: new Date().toISOString(), actor: REVIEWER, text: "هزینه را تأیید کرد.", tone: "success" }
        : { at: new Date().toISOString(), actor: REVIEWER, text: "هزینه را رد کرد.", tone: "destructive" }
    this.expenses.set(
      this.expenses().map((e) =>
        e.id === id ? { ...e, status: next, rejectReason: reason, history: [...e.history, entry] } : e
      )
    )
    this.busy.set(null)
    toast.success(next === "approved" ? "هزینه تأیید شد" : "هزینه رد شد", {
      description: before.title,
      action: {
        label: "بازگردانی",
        onClick: () => {
          this.expenses.set(this.expenses().map((e) => (e.id === id ? before : e)))
          toast("به وضعیت «در انتظار تأیید» برگشت.")
        },
      },
    })
  }

  readonly approve = (id: string) => this.decide(id, "approved")

  readonly reject = (id: string, reason: string) => this.decide(id, "rejected", reason)

  readonly count = (s: ExpenseStatus) => this.expenses().filter((e) => e.status === s).length

  readonly pending = computed(() => this.expenses().filter((e) => e.status === "pending"))

  readonly selected = computed(() => this.expenses().find((e) => e.id === this.selectedId()) ?? null)

  readonly metrics = computed<
    {
      icon: DigIconName
      tone: "warning" | "success" | "destructive" | "primary"
      label: string
      value: string
      hint: string
    }[]
  >(() => [
    {
      icon: "clock" as const,
      tone: "warning",
      label: "در انتظار تأیید",
      value: toFaDigits(this.pending().length),
      hint: `${millions(this.pending().reduce((n, e) => n + e.amount, 0))} تومان`,
    },
    {
      icon: "check-circle" as const,
      tone: "success",
      label: "تأییدشده این ماه",
      value: millions(
        this.expenses()
          .filter((e) => e.status === "approved")
          .reduce((n, e) => n + e.amount, 0)
      ),
      hint: `${toFaDigits(this.count("approved"))} هزینه`,
    },
    {
      icon: "circle-x" as const,
      tone: "destructive",
      label: "ردشده",
      value: toFaDigits(this.count("rejected")),
      hint: "با دلیل ثبت شده",
    },
    {
      icon: "receipt" as const,
      tone: "primary",
      label: "کل هزینه‌ها",
      value: toFaDigits(this.expenses().length),
      hint: "در این ماه",
    },
  ])

  readonly isMobileLg = useIsMobile(1024)

  readonly current = computed<Expense | null>(() => this.selected() ?? this.pending()[0] ?? null)

  readonly panelExpense = computed(() => (!this.isMobileLg() ? this.current() : this.selected()))

  readonly rejecting = signal(false)

  readonly reason = signal("")

  readonly touched = signal(false)

  readonly rejectForm = viewChild<ElementRef<HTMLElement>>("rejectForm")

  readonly resultEl = viewChild<ElementRef<HTMLElement>>("resultEl")

  lastStatus: ExpenseStatus | undefined = this.panelExpense()?.status

  readonly focusReason = () => this.rejectForm()?.nativeElement?.querySelector<HTMLElement>("textarea")?.focus()

  readonly trimmed = computed(() => this.reason().trim())

  readonly reasonError = computed(() =>
    !this.trimmed()
      ? "نوشتن دلیل برای ردِ هزینه الزامی است."
      : this.trimmed().length < MIN_REASON
        ? `دلیل را کمی کامل‌تر بنویسید؛ دست‌کم ${toFaDigits(MIN_REASON)} نویسه.`
        : undefined
  )

  readonly showError = computed(() => this.touched() && !!this.reasonError())

  submitReject() {
    this.touched.set(true)
    if (this.reasonError()) return this.focusReason()
    const expense = this.panelExpense()
    if (expense) this.reject(expense.id, this.trimmed())
  }

  cancelReject() {
    this.rejecting.set(false)
    this.reason.set("")
    this.touched.set(false)
    requestAnimationFrame(() => document.querySelector<HTMLElement>("[data-reject-trigger]")?.focus())
  }

  readonly wide = computed(() => !this.isMobileLg())

  constructor() {
    afterNextRender(() => this.fetchData())
    {
      let previous: readonly unknown[] | undefined
      effect(() => {
        const snapshot = [this.panelExpense()?.id] as const
        const changed = previous ? snapshot.some((value, index) => !Object.is(value, previous?.[index])) : false
        previous = snapshot
        if (!changed) return
        untracked(() => {
          this.rejecting.set(false)
          this.reason.set("")
          this.touched.set(false)
          this.lastStatus = this.panelExpense()?.status
        })
      })
    }
    {
      let previous: readonly unknown[] | undefined
      effect(() => {
        const snapshot = [this.rejecting()] as const
        const changed = previous ? snapshot.some((value, index) => !Object.is(value, previous?.[index])) : false
        previous = snapshot
        if (!changed) return
        untracked(async () => {
          const value = snapshot[0]

          if (!value) return
          await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
          this.focusReason()
        })
      })
    }
    {
      let previous: readonly unknown[] | undefined
      effect(() => {
        const snapshot = [this.panelExpense()?.status] as const
        const changed = previous ? snapshot.some((value, index) => !Object.is(value, previous?.[index])) : false
        previous = snapshot
        if (!changed) return
        untracked(async () => {
          const next = snapshot[0]

          if (this.lastStatus === "pending" && next && next !== "pending") {
            await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
            this.resultEl()?.nativeElement?.focus()
          }
          this.lastStatus = next
        })
      })
    }
  }

  readonly categoryLabel = computed(() => {
    const category = this.category()
    return category === "all" ? undefined : CATEGORIES[category]
  })
}

کدِ این بلاک هنوز برای Android نوشته نشده است.

همهٔ کامپوننت‌های لازم برای Android آماده‌اند؛ با MCP می‌توانید همین صفحه را از روی نسخهٔ React بسازید.

کدِ React همین بلاک مرجع است. با MCP دیگ و get_block با framework="android" ایجنت آن را با کامپوننت‌های Android می‌سازد.