import type { ReactNode } from "react"; import { useTranslation } from "react-i18next"; import type { TFunction } from "i18next"; import { Info } from "lucide-react"; import { Cell, Pie, PieChart } from "recharts"; import { getEducationLabel, getMarriageLabel } from "@/constants/formOptions"; import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { cn } from "@/lib/utils"; import type { ApprovalCount, CountItem, CustomersData, ProductsData } from "../api/analyticsApi"; import { BarList, EmptyState, RegisterPanel, SectionCard, type BarListRow } from "./analyticsShared"; import { formatNumber, formatPercent, useLocalizedName } from "./analyticsFormat"; interface QueryProps { data?: T; isLoading: boolean; isError: boolean; onRetry: () => void; } // One meaning per colour across the dashboard: teal = loans / approved, // mid teal = cards, light teal = secondary share, sand = waiting, clay = rejected. const LOAN_COLOR = "var(--chart-1)"; const CARD_COLOR = "var(--chart-2)"; const SHARE_COLOR = "var(--chart-3)"; const GOOD_COLOR = "var(--chart-1)"; const WAIT_COLOR = "var(--chart-4)"; const BAD_COLOR = "var(--chart-5)"; /** Below this many decided orders an approval rate is shown but flagged as unreliable. */ const MIN_DECIDED = 5; /** Shared 2×2 cell dividers: vertical rule + row rule, collapsing to stacked rows on mobile. */ const CELL_BORDERS = [ "border-b border-border md:border-r", "border-b border-border", "border-b border-border md:border-b-0 md:border-r", "border-b-0", ]; /** Donut geometry — the empty remainder is drawn as a static ring behind the chart. */ const DONUT_SIZE = 164; const DONUT_INNER = 56; const DONUT_OUTER = 72; /** "3 sargyt · 60%" — count first, share muted. */ function CountShare({ count, percent }: { count: number; percent: number }) { const { t } = useTranslation(); return ( <> {formatNumber(count)} {t("analytics.kpi.orders", "sargyt")} · {formatNumber(percent, 1)}% ); } function InfoHint({ children, className }: { children: ReactNode; className?: string }) { return ( {children} ); } // ─── Donut with the total in the middle ────────────────────────────────────── interface DonutRow { key: string; label: string; color: string; } function TotalDonut({ items, rows: rowDefs }: { items: CountItem[]; rows: DonutRow[] }) { const { t } = useTranslation(); const byKey = new Map(items.map((it) => [it.key, it])); // Fixed row order and colors, so "unpaid" is always sand and never swaps with "paid". const known = new Set(rowDefs.map((r) => r.key)); const extra = items.filter((it) => !known.has(it.key)).map((it) => ({ key: it.key, label: it.key, color: "var(--muted-foreground)" })); const rows = [...rowDefs, ...extra].map((r) => ({ ...r, count: byKey.get(r.key)?.count ?? 0, percent: byKey.get(r.key)?.percent ?? 0, })); const total = rows.reduce((s, r) => s + r.count, 0); if (total === 0) return ; const config = Object.fromEntries(rows.map((r) => [r.label, { label: r.label, color: r.color }])); // Recharts derives its own slice angles; a pre-computed `percent` on the datum // would be read as geometry, so the chart rows carry the count only. const chartRows = rows.map(({ key, label, color, count }) => ({ key, label, color, count })); const ringRadius = (DONUT_INNER + DONUT_OUTER) / 2; return (
{chartRows.map((r) => ( ))} } />
{formatNumber(total)} {t("analytics.kpi.orders", "sargyt")}
{rows.map((r) => (

{formatNumber(r.count)} {formatNumber(r.percent, 1)}%

))}
); } // ─── Products ───────────────────────────────────────────────────────────────── export function ProductsSection({ data, isLoading, isError, onRetry }: QueryProps) { const { t } = useTranslation(); const localized = useLocalizedName(); const common = { isLoading, isError, onRetry, skeletonHeight: 170 }; const toRows = (items: ProductsData["loanTypes"]): BarListRow[] => items.map((it) => ({ key: String(it.id), label: localized(it.name), value: it.count, share: it.percent, valueText: , })); return (
); } // ─── Customers ──────────────────────────────────────────────────────────────── /** Approved / rejected / waiting counts as marked dots, then the approval rate. */ function Outcome({ item, t }: { item: ApprovalCount; t: TFunction }) { const decided = item.approved + item.rejected; const parts = [ { n: item.approved, color: GOOD_COLOR, label: t("analytics.outcome.approved", "tassyklandy") }, { n: item.rejected, color: BAD_COLOR, label: t("analytics.outcome.rejected", "ret edildi") }, { n: item.open, color: WAIT_COLOR, label: t("analytics.outcome.open", "garaşýar"), pending: true }, ].filter((p) => p.n > 0); const fewData = decided > 0 && decided < MIN_DECIDED; // Two fixed columns: counts on the left, approval rate pinned right — so every row lines up the same way. return (
{parts.map((p) => ( ))} {decided === 0 ? ( {t("analytics.outcome.noDecision", "Karar entek ýok")} ) : ( {formatPercent(item.approvalRate)} {formatNumber(item.approved)}/{formatNumber(decided)} {fewData ? t("analytics.outcome.fewDataHint", "Az maglumat: diňe {{count}} karar bar, göterim takyk däl", { count: decided }) : t("analytics.outcome.rateHint", "Tassyklama derejesi: tassyklanan / karar berlen")} )}
); } function approvalRows(items: ApprovalCount[], labelFor: (key: string) => string, t: TFunction): BarListRow[] { return items.map((it) => ({ key: it.key, label: labelFor(it.key), value: it.count, share: it.percent, valueText: , sub: , })); } // ─── Anchor band: the five headline customer metrics on one dark surface ──── function BandStat({ label, value, color, pending }: { label: string; value: string; color?: string; pending?: boolean }) { return (

{color && (

{value}

); } function CustomersSummary({ data, isLoading }: { data?: CustomersData; isLoading: boolean }) { const { t } = useTranslation(); // The endpoint reports totals per dimension but may omit the headline counts. // When they are absent, ages are the one dimension that covers every applicant, // so they are the honest source for the band. const fromGroups = data?.ageGroups?.length ? data.ageGroups.reduce( (acc, g) => ({ approved: acc.approved + (g.approved ?? 0), rejected: acc.rejected + (g.rejected ?? 0), open: acc.open + (g.open ?? 0), }), { approved: 0, rejected: 0, open: 0 }, ) : undefined; const approved = data?.approved ?? fromGroups?.approved; const rejected = data?.rejected ?? fromGroups?.rejected; const open = data?.open ?? fromGroups?.open; const decided = (approved ?? 0) + (rejected ?? 0); const approvalRate = data?.approvalRate ?? (decided > 0 ? ((approved ?? 0) / decided) * 100 : null); const rateValue = formatPercent(approvalRate); const width = typeof approvalRate === "number" ? `${Math.min(100, Math.max(0, approvalRate))}%` : "0%"; const rateHint = t( "analytics.customers.approvalHint", "Tassyklama derejesi = tassyklanan ÷ (tasyklanan + ret edilen). Garaşýan sargytlar hasaba alynmaýar.", ); return (
{isLoading ? (
{Array.from({ length: 5 }, (_, i) => (
))}
) : (

{t("analytics.customers.approvalRate", "Tassyklama derejesi")} {rateHint}

{rateValue}

)}
); } interface CustomersSectionProps extends QueryProps { /** Product breakdown is a sibling query, passed in so both blocks refresh together. */ products: QueryProps; } export function CustomersSection({ data, isLoading, isError, onRetry, products }: CustomersSectionProps) { const { t } = useTranslation(); // One error card instead of four identical ones. if (isError) { return ( ); } const unknown = t("analytics.unknown", "Näbelli"); const ageLabel = (k: string) => k === "under25" ? t("analytics.age.under25", "25 ýaşdan kiçi") : k === "unknown" ? unknown : `${k} ${t("analytics.age.years", "ýaş")}`; const educationLabel = (k: string) => (k === "unknown" ? unknown : getEducationLabel(k, t)); const marriageLabel = (k: string) => (k === "unknown" ? unknown : getMarriageLabel(k, t)); const guarantorLabel = (k: string) => ({ none: t("analytics.guarantors.none", "Zamunsyz"), one: t("analytics.guarantors.one", "1 zamun"), two: t("analytics.guarantors.two", "2 zamun"), })[k] ?? k; const cards: { title: string; items?: ApprovalCount[]; label: (k: string) => string }[] = [ { title: t("analytics.customers.age", "Ýaş toparlary"), items: data?.ageGroups, label: ageLabel }, { title: t("analytics.customers.education", "Bilimi"), items: data?.education, label: educationLabel }, { title: t("analytics.customers.marriage", "Maşgala ýagdaýy"), items: data?.marriageStatus, label: marriageLabel }, { title: t("analytics.customers.guarantors", "Zamunlar"), items: data?.guarantors, label: guarantorLabel }, ]; return (

{t("analytics.customers.desc", "Saýlanan döwürde karz sargydyny berenleriň profili")}

{t("analytics.customers.approvalRate", "Tassyklama derejesi")} {t( "analytics.customers.approvalHint", "Tassyklama derejesi = tassyklanan ÷ (tasyklanan + ret edilen). Garaşýan sargytlar hasaba alynmaýar.", )}
{cards.map((c, i) => ( ))}
); }