"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { ApiError } from "@/lib/api";
import { hasPermission } from "@/lib/permissions";
import {
  fetchAttendanceAlerts,
  fetchAttendanceOverview,
  type AlertRowsPayload,
  type BranchRow,
  type DeliveryRow,
  type Overview,
  type PeriodRow,
} from "@/lib/attendance-report";
import {
  CardTitle,
  DeliveryChip,
  EmptyState,
  GlassCard,
  GroupedBarChart,
  LegendDot,
  LoadingRows,
  MiniStat,
  MultiLineChart,
  RankBar,
  RingGauge,
  STATUS_META,
  fa,
  faPct,
  severitySurface,
} from "./AttendancePrimitives";
import {
  AlertsList,
  MessageModal,
  SendMsgBtn,
  SmsStat,
  STUDENT_FILTER_OPTIONS,
  type MessageTarget,
} from "./AttendanceShared";
import { AttendanceFilterBar } from "./AttendanceFilterBar";
import { AttendanceDeliveryPanel } from "./AttendanceDeliveryPanel";
import { AttendanceExportMenu } from "./AttendanceExportMenu";
import { AttendancePolicyDrawer } from "./AttendancePolicyDrawer";
import { faDayMonth } from "./dateRange";
import { useAttendanceFilters } from "./useAttendanceFilters";

export function AttendanceDashboard() {
  const filters = useAttendanceFilters();
  const { scopeQuery, scopeKey, branchLabel, dateLabel, hrefFor, optionsError } = filters;

  const [overview, setOverview] = useState<Overview | null>(null);
  const [alerts, setAlerts] = useState<AlertRowsPayload | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [reloadToken, setReloadToken] = useState(0);

  const [opsTab, setOpsTab] = useState<"branches" | "periods" | "alerts">("branches");
  const [exportOpen, setExportOpen] = useState(false);
  const [policyOpen, setPolicyOpen] = useState(false);
  const [insightsOpen, setInsightsOpen] = useState(true);
  const [messageTarget, setMessageTarget] = useState<MessageTarget | null>(null);

  const canManagePolicy = hasPermission("academic.attendance.policy.manage");

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    Promise.all([fetchAttendanceOverview(scopeQuery), fetchAttendanceAlerts(scopeQuery)])
      .then(([overviewData, alertData]) => {
        if (cancelled) return;
        setOverview(overviewData);
        setAlerts(alertData);
        setError(null);
      })
      .catch((err: unknown) => {
        if (cancelled) return;
        setError(err instanceof ApiError ? err.message : "خطا در دریافت گزارش حضور و غیاب");
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [scopeKey, reloadToken]);

  const reload = useCallback(() => setReloadToken((token) => token + 1), []);

  const multiBranch = (overview?.branches.length ?? 0) > 1;
  const students = overview?.students;
  const lists = overview?.lists;

  const deliveryHref = useCallback(
    (row: DeliveryRow) => hrefFor({ dataset: "students", deliveryMode: row.mode }),
    [hrefFor],
  );

  return (
    <div className="relative -mx-4 -mt-2 min-h-[70vh] bg-[radial-gradient(1200px_500px_at_100%_-10%,rgba(13,148,136,0.16),transparent),radial-gradient(900px_400px_at_0%_0%,rgba(14,165,233,0.12),transparent)] px-4 pb-10 pt-3 lg:-mx-6 lg:px-6">
      <header className="relative z-30 mb-4 rounded-[1.7rem] border border-white/80 bg-white/75 p-4 shadow-card backdrop-blur-md lg:p-5">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <p className="text-[11px] font-bold text-teal-700">حضور و غیاب · گزارش مدیریتی</p>
            <h2 className="mt-0.5 text-lg font-black text-slate-900">
              {multiBranch ? "نمای کلان هلدینگ" : "نمای تفصیلی شعبه"}
            </h2>
            <p className="mt-1 text-xs text-slate-500">
              {dateLabel} · محدوده: {branchLabel}
              {overview ? ` · ${fa(overview.range.working_days)} روز کاری` : ""}
            </p>
            {overview ? (
              <p className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-slate-500">
                <span>{overview.presence_source}</span>
                {overview.sessions.by_mode.map((mode) => (
                  <DeliveryChip
                    key={mode.mode}
                    mode={mode.mode}
                    label={`${mode.label}: ${fa(mode.sessions)}`}
                    compact
                  />
                ))}
              </p>
            ) : null}
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <Button variant="secondary" onClick={() => setPolicyOpen(true)}>
              سیاست گزارشگیری
            </Button>
            <div className="relative">
              <Button onClick={() => setExportOpen((open) => !open)}>
                ایجاد خروجی
                <span aria-hidden className="ms-2 text-[10px]">
                  ▾
                </span>
              </Button>
              {exportOpen ? (
                <AttendanceExportMenu
                  query={scopeQuery}
                  scopeLabel={branchLabel}
                  dateLabel={dateLabel}
                  onClose={() => setExportOpen(false)}
                />
              ) : null}
            </div>
          </div>
        </div>

        <div className="mt-4">
          <AttendanceFilterBar filters={filters} />
        </div>
      </header>

      {optionsError ? (
        <div className="mb-4">
          <Alert tone="warning">{optionsError}</Alert>
        </div>
      ) : null}
      {error ? (
        <div className="mb-4">
          <Alert tone="error">{error}</Alert>
        </div>
      ) : null}

      {loading && !overview ? (
        <GlassCard>
          <LoadingRows rows={6} />
        </GlassCard>
      ) : !overview || !students || !lists ? (
        <GlassCard>
          <EmptyState>داده‌ای برای این محدوده نیست.</EmptyState>
        </GlassCard>
      ) : (
        <>
          <div className="grid gap-4 xl:grid-cols-2">
            <StatusOverviewCard
              overview={overview}
              multiBranch={multiBranch}
              hrefFor={hrefFor}
            />
            <div className="space-y-4">
              <AttendanceDeliveryPanel
                rows={overview.delivery}
                sessions={overview.sessions}
                hrefFor={deliveryHref}
              />
              <TrendCard overview={overview} />
            </div>
          </div>

          <div className="mt-4 grid gap-4 xl:grid-cols-[minmax(0,1fr)_19rem]">
            <div className="space-y-4">
              <GlassCard>
                <CardTitle
                  kicker="تأخیر ارسال لیست"
                  title="تکمیل و به‌موقع بودن لیست‌های حضور"
                  action={
                    <Link
                      href={hrefFor({ dataset: "classes", lists: "delayed" })}
                      className="text-xs font-bold text-teal-700"
                    >
                      فهرست جلسات دیرارسال
                    </Link>
                  }
                />
                <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
                  <MiniStat
                    label="لیست تکمیل"
                    value={fa(lists.complete)}
                    hint={faPct(lists.on_time_pct) + " به‌موقع"}
                    tone="emerald"
                    href={hrefFor({ dataset: "classes", lists: "complete" })}
                  />
                  <MiniStat
                    label="ناقص"
                    value={fa(lists.partial)}
                    tone="amber"
                    href={hrefFor({ dataset: "classes", lists: "partial" })}
                  />
                  <MiniStat
                    label="پرنشده"
                    value={fa(lists.empty)}
                    tone="rose"
                    href={hrefFor({ dataset: "classes", lists: "empty" })}
                  />
                  <MiniStat
                    label="ارسال دیر"
                    value={fa(lists.delayed)}
                    hint={`میانگین ${fa(lists.avg_delay_minutes)} دقیقه`}
                    tone="slate"
                    href={hrefFor({ dataset: "classes", lists: "delayed" })}
                  />
                </div>
                <p className="mt-3 text-xs text-slate-500">
                  آستانه ارسال فرم:{" "}
                  <span className="font-bold text-slate-800">
                    {fa(overview.policy.form_delay_minutes)} دقیقه
                  </span>
                  {" · "}
                  سقف غیبت:{" "}
                  <span className="font-bold text-slate-800">
                    {fa(overview.policy.absence_cap_days)} روز
                  </span>
                  {" · "}
                  آستانه تأخیر ورود:{" "}
                  <span className="font-bold text-slate-800">
                    {fa(overview.policy.late_threshold_minutes)} دقیقه
                  </span>
                </p>
              </GlassCard>

              <GlassCard>
                <CardTitle
                  kicker="عملیات زنده"
                  title="تفکیک محدوده"
                  action={
                    <Link
                      href={hrefFor({ dataset: "students" })}
                      className="rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-bold text-teal-700 transition hover:bg-teal-50"
                    >
                      فهرست نفرات
                    </Link>
                  }
                />

                <div className="mb-3 grid gap-2 sm:grid-cols-4">
                  <SmsStat
                    label="تحویل‌شده"
                    value={overview.messages.delivered}
                    tone="emerald"
                    time={shortTime(overview.messages.last_at)}
                    href={hrefFor({ dataset: "students", sms: "delivered" })}
                  />
                  <SmsStat
                    label="در صف ارسال"
                    value={overview.messages.queued}
                    tone="amber"
                    time={shortTime(overview.messages.last_at)}
                    href={hrefFor({ dataset: "students", sms: "queued" })}
                  />
                  <SmsStat
                    label="ناموفق"
                    value={overview.messages.failed}
                    tone="rose"
                    time={shortTime(overview.messages.last_at)}
                    href={hrefFor({ dataset: "students", sms: "failed" })}
                  />
                  <SmsStat
                    label="در معرض خطر"
                    value={overview.at_risk_students}
                    tone="slate"
                    time={`سقف ${fa(overview.policy.absence_cap_days)} روز`}
                    href={hrefFor({ dataset: "students", status: "atrisk" })}
                  />
                </div>

                <div className="mb-3 flex flex-wrap gap-1.5">
                  {STUDENT_FILTER_OPTIONS.filter(([key]) => key !== "all").map(([key, label]) => (
                    <Link
                      key={key}
                      href={hrefFor({ dataset: "students", status: key })}
                      className="rounded-full bg-white px-3 py-1.5 text-[11px] font-bold text-slate-600 ring-1 ring-slate-200 transition hover:bg-slate-50"
                    >
                      {label}
                    </Link>
                  ))}
                </div>

                <div className="mb-3 flex gap-2">
                  <TabBtn active={opsTab === "branches"} onClick={() => setOpsTab("branches")}>
                    آمار شعب
                  </TabBtn>
                  <TabBtn active={opsTab === "periods"} onClick={() => setOpsTab("periods")}>
                    تفکیک زنگ
                  </TabBtn>
                  <TabBtn active={opsTab === "alerts"} onClick={() => setOpsTab("alerts")}>
                    هشدارها · {fa(overview.alerts.open)}
                  </TabBtn>
                </div>

                {opsTab === "branches" ? (
                  <BranchStatsTable
                    rows={overview.branches}
                    totals={students}
                    lists={lists}
                    hrefFor={hrefFor}
                  />
                ) : opsTab === "periods" ? (
                  <PeriodBreakdown rows={overview.periods} hrefFor={hrefFor} />
                ) : (
                  <AlertsList
                    rows={alerts?.rows ?? []}
                    loading={loading}
                    onMessage={setMessageTarget}
                    picking={false}
                    selectedIds={[]}
                    onToggle={() => undefined}
                  />
                )}
              </GlassCard>
            </div>

            <aside className="space-y-4">
              <GlassCard>
                <CardTitle kicker="هشدارهای باز" title="وضعیت هشدار حضور" />
                <div className="grid grid-cols-3 gap-2">
                  <MiniStat
                    label="بحرانی"
                    value={fa(overview.alerts.critical)}
                    tone="rose"
                    href={hrefFor({ dataset: "alerts" })}
                  />
                  <MiniStat
                    label="اخطار"
                    value={fa(overview.alerts.warning)}
                    tone="amber"
                    href={hrefFor({ dataset: "alerts" })}
                  />
                  <MiniStat
                    label="اطلاعی"
                    value={fa(overview.alerts.info)}
                    tone="slate"
                    href={hrefFor({ dataset: "alerts" })}
                  />
                </div>
                <p className="mt-3 text-[11px] leading-6 text-slate-500">
                  هشدارها از موتور قواعد حضور می‌آید و با پیگیری مدیر شعبه بسته می‌شود.
                </p>
              </GlassCard>

              <GlassCard>
                <CardTitle kicker="کیفیت داده" title="غیبت بدون توجیه" />
                <p className="text-3xl font-black tabular-nums text-rose-700">
                  {fa(overview.unjustified_absent)}
                </p>
                <p className="mt-1 text-xs text-slate-500">
                  از {fa(students.absent)} غیبت این محدوده، این تعداد هیچ توضیح یا گواهی ثبت‌شده‌ای
                  ندارد.
                </p>
                <Link
                  href={hrefFor({ dataset: "students", status: "unjustified" })}
                  className="mt-3 inline-block text-xs font-bold text-rose-700 hover:underline"
                >
                  مشاهده فهرست
                </Link>
              </GlassCard>
            </aside>
          </div>

          <div className="mt-4 rounded-[1.6rem] border border-rose-100 bg-white/85 p-4 shadow-card">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <p className="text-[11px] font-bold text-rose-700">تحلیل سیستمی گزارش</p>
                <h3 className="text-sm font-black text-slate-900">پیام‌ها و راهکارهای مدیریتی</h3>
              </div>
              <Button
                variant={insightsOpen ? "secondary" : "primary"}
                onClick={() => setInsightsOpen((open) => !open)}
              >
                {insightsOpen ? "بستن تحلیل" : "مشاهده تحلیل"}
              </Button>
            </div>
            {insightsOpen ? (
              <ul className="mt-4 space-y-2">
                {overview.insights.map((item) => (
                  <li key={item.id} className={`rounded-2xl px-3 py-3 ${severitySurface(item.severity)}`}>
                    <div className="flex items-start justify-between gap-2">
                      <div>
                        <p className="text-sm font-bold text-slate-900">{item.title}</p>
                        <p className="mt-1 text-xs leading-6 text-slate-600">{item.message}</p>
                        <p className="mt-1 text-[11px] font-bold text-teal-800">
                          راهکار: {item.action}
                        </p>
                      </div>
                      <SendMsgBtn
                        onClick={() =>
                          setMessageTarget({
                            name: `مدیر ${item.branch_name ?? "مجموعه"}`,
                            role: "manager",
                            hint: item.title,
                          })
                        }
                      />
                    </div>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="mt-3 text-xs text-slate-500">
                برای دیدن پیام‌ها و راهکارهای پیشنهادی سیستم، مشاهده تحلیل را بزنید.
              </p>
            )}
          </div>
        </>
      )}

      {policyOpen ? (
        <AttendancePolicyDrawer
          query={scopeQuery}
          canManage={canManagePolicy}
          onClose={() => setPolicyOpen(false)}
          onSaved={reload}
        />
      ) : null}
      {messageTarget ? (
        <MessageModal target={messageTarget} onClose={() => setMessageTarget(null)} />
      ) : null}
    </div>
  );
}

function shortTime(value: string | null): string {
  if (!value) return "—";
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) return "—";
  return parsed.toLocaleTimeString("fa-IR", { hour: "2-digit", minute: "2-digit" });
}

type HrefFor = ReturnType<typeof useAttendanceFilters>["hrefFor"];

function StatusOverviewCard({
  overview,
  multiBranch,
  hrefFor,
}: {
  overview: Overview;
  multiBranch: boolean;
  hrefFor: HrefFor;
}) {
  const totals = overview.students;
  const pct = (value: number) => (totals.total ? Math.round((value / totals.total) * 100) : 0);
  const ranked = [...overview.branches].sort((a, b) => b.unchecked_pct - a.unchecked_pct);
  const worst = ranked[0]?.unchecked_pct ?? 0;

  return (
    <GlassCard>
      <CardTitle
        kicker={multiBranch ? "داشبورد مدیریتی کل" : "داشبورد مدیریتی شعبه"}
        title="وضعیت حضور در یک نگاه"
        action={
          <span className="text-[11px] font-bold text-slate-400">
            روی هر عدد بزنید تا فهرست همان گروه باز شود
          </span>
        }
      />
      <div className="grid grid-cols-2 gap-1 sm:grid-cols-4">
        <RingGauge
          percent={pct(totals.unchecked)}
          label="ثبت‌نشده"
          value={`${fa(totals.unchecked)} نفر-جلسه`}
          color={STATUS_META.unchecked.color}
          href={hrefFor({ dataset: "students", status: "unchecked" })}
        />
        <RingGauge
          percent={pct(totals.present)}
          label="حاضر"
          value={`${fa(totals.present)} نفر-جلسه`}
          color={STATUS_META.present.color}
          href={hrefFor({ dataset: "students", status: "present" })}
        />
        <RingGauge
          percent={pct(totals.late)}
          label="تأخیر"
          value={`${fa(totals.late)} نفر-جلسه`}
          color={STATUS_META.late.color}
          href={hrefFor({ dataset: "students", status: "late" })}
        />
        <RingGauge
          percent={pct(totals.absent)}
          label="غایب"
          value={`${fa(totals.absent)} نفر-جلسه`}
          color={STATUS_META.absent.color}
          href={hrefFor({ dataset: "students", status: "absent" })}
        />
      </div>
      <p className="mt-2 text-center text-[11px] text-slate-500">
        مبنای درصدها: {fa(totals.total)} نفر-جلسه · نرخ حضور {faPct(totals.presence_rate)}
        {totals.temporary_exit > 0 ? ` · خروج موقت ${fa(totals.temporary_exit)}` : ""}
      </p>

      <div className="mt-4">
        <p className="mb-2 text-xs font-bold text-slate-500">
          {multiBranch ? "شعب با بیشترین ثبت‌نشده" : "سهم ثبت‌نشده این شعبه"}
        </p>
        {ranked.length === 0 ? (
          <EmptyState>شعبه‌ای در این محدوده داده ندارد.</EmptyState>
        ) : (
          <ul className="space-y-2">
            {ranked.map((row, index) => (
              <li key={row.branch_id}>
                <RankBar
                  index={index}
                  title={row.branch_name ?? "شعبه"}
                  meta={`${fa(row.unchecked)} نفر · ${faPct(row.unchecked_pct)}`}
                  percent={worst > 0 ? (row.unchecked_pct / worst) * 100 : 0}
                  barClassName={
                    row.unchecked_pct >= 12
                      ? "bg-slate-700"
                      : row.unchecked_pct >= 8
                        ? "bg-slate-500"
                        : "bg-slate-400"
                  }
                  href={hrefFor({
                    dataset: "students",
                    status: "unchecked",
                    branchIds: [row.branch_id],
                  })}
                />
              </li>
            ))}
          </ul>
        )}
      </div>
    </GlassCard>
  );
}

function TrendCard({ overview }: { overview: Overview }) {
  const singleDay = overview.trend.length <= 1;

  const branchSeries = useMemo(
    () => [
      {
        key: "present",
        color: STATUS_META.present.color,
        values: overview.branches.map((row) =>
          row.total ? Math.round((row.present / row.total) * 100) : 0,
        ),
      },
      {
        key: "late",
        color: STATUS_META.late.color,
        values: overview.branches.map((row) =>
          row.total ? Math.round((row.late / row.total) * 100) : 0,
        ),
      },
      {
        key: "absent",
        color: STATUS_META.absent.color,
        values: overview.branches.map((row) =>
          row.total ? Math.round((row.absent / row.total) * 100) : 0,
        ),
      },
      {
        key: "unchecked",
        color: STATUS_META.unchecked.color,
        values: overview.branches.map((row) => row.unchecked_pct),
      },
    ],
    [overview.branches],
  );

  const trendSeries = useMemo(
    () => [
      {
        key: "presence",
        color: STATUS_META.present.color,
        values: overview.trend.map((row) => row.presence_rate),
      },
      {
        key: "unchecked",
        color: STATUS_META.unchecked.color,
        values: overview.trend.map((row) => row.unchecked_pct),
      },
    ],
    [overview.trend],
  );

  return (
    <GlassCard>
      <CardTitle
        kicker={singleDay ? "تحلیل مقایسه‌ای شعب" : "روند بازه"}
        title={singleDay ? "نرخ وضعیت‌ها به تفکیک شعبه" : "نرخ حضور و ثبت‌نشده در طول بازه"}
      />
      {singleDay ? (
        overview.branches.length === 0 ? (
          <EmptyState>داده‌ای برای نمودار نیست.</EmptyState>
        ) : (
          <GroupedBarChart
            labels={overview.branches.map((row) => (row.branch_name ?? "شعبه").replace("شعبه ", ""))}
            series={branchSeries}
          />
        )
      ) : (
        <MultiLineChart
          labels={overview.trend.map((row) => faDayMonth(row.date))}
          series={trendSeries}
        />
      )}
      <div className="mt-2 flex flex-wrap gap-3 text-[11px] text-slate-500">
        <LegendDot color={STATUS_META.present.color} label="حضور" />
        {singleDay ? <LegendDot color={STATUS_META.late.color} label="تأخیر" /> : null}
        {singleDay ? <LegendDot color={STATUS_META.absent.color} label="غیبت" /> : null}
        <LegendDot color={STATUS_META.unchecked.color} label="ثبت‌نشده" />
      </div>
    </GlassCard>
  );
}

function BranchStatsTable({
  rows,
  totals,
  lists,
  hrefFor,
}: {
  rows: BranchRow[];
  totals: Overview["students"];
  lists: Overview["lists"];
  hrefFor: HrefFor;
}) {
  if (rows.length === 0) {
    return <EmptyState>شعبه‌ای در این محدوده داده ندارد.</EmptyState>;
  }

  return (
    <div className="overflow-x-auto rounded-2xl border border-slate-100">
      <table className="min-w-full text-sm">
        <thead className="bg-slate-50 text-xs text-slate-500">
          <tr>
            <th className="px-3 py-2.5 text-right font-bold">شعبه</th>
            <th className="px-3 py-2.5 text-right font-bold">جلسات</th>
            <th className="px-3 py-2.5 text-right font-bold">حاضر</th>
            <th className="px-3 py-2.5 text-right font-bold">تأخیر</th>
            <th className="px-3 py-2.5 text-right font-bold">غایب</th>
            <th className="px-3 py-2.5 text-right font-bold">ثبت‌نشده</th>
            <th className="px-3 py-2.5 text-right font-bold">لیست ناقص و پرنشده</th>
            <th className="px-3 py-2.5 text-right font-bold">تأخیر ارسال لیست</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => (
            <tr key={row.branch_id} className="border-t border-slate-100 hover:bg-slate-50/80">
              <td className="px-3 py-2.5">
                <span className="block font-bold text-slate-800">
                  {row.branch_name ?? "شعبه"}
                </span>
                <span className="text-[11px] text-slate-400">
                  نرخ حضور {faPct(row.presence_rate)}
                </span>
              </td>
              <td className="px-3 py-2.5">
                <span className="block text-xs font-bold tabular-nums text-slate-700">
                  {fa(row.sessions)}
                </span>
                <span className="mt-1 flex flex-wrap gap-1">
                  {row.sessions_by_mode.map((mode) => (
                    <DeliveryChip
                      key={mode.mode}
                      mode={mode.mode}
                      label={`${mode.label}: ${fa(mode.sessions)}`}
                      compact
                    />
                  ))}
                </span>
              </td>
              <td className="px-3 py-2.5">
                <StatCell
                  value={row.present}
                  tone="text-emerald-700"
                  href={hrefFor({
                    dataset: "students",
                    status: "present",
                    branchIds: [row.branch_id],
                  })}
                />
              </td>
              <td className="px-3 py-2.5">
                <StatCell
                  value={row.late}
                  tone="text-amber-700"
                  href={hrefFor({
                    dataset: "students",
                    status: "late",
                    branchIds: [row.branch_id],
                  })}
                />
              </td>
              <td className="px-3 py-2.5">
                <StatCell
                  value={row.absent}
                  tone="text-rose-700"
                  href={hrefFor({
                    dataset: "students",
                    status: "absent",
                    branchIds: [row.branch_id],
                  })}
                />
              </td>
              <td className="px-3 py-2.5">
                <StatCell
                  value={row.unchecked}
                  tone="text-slate-700"
                  href={hrefFor({
                    dataset: "students",
                    status: "unchecked",
                    branchIds: [row.branch_id],
                  })}
                />
              </td>
              <td className="px-3 py-2.5">
                <StatCell
                  value={row.lists.pending}
                  tone="text-orange-700"
                  href={hrefFor({
                    dataset: "classes",
                    lists: "pending",
                    branchIds: [row.branch_id],
                  })}
                />
              </td>
              <td className="px-3 py-2.5">
                <Link
                  href={hrefFor({
                    dataset: "classes",
                    lists: "delayed",
                    branchIds: [row.branch_id],
                  })}
                  className="text-xs font-bold text-slate-600 hover:text-teal-700"
                >
                  {faPct(row.lists.late_pct)} دیر · میانگین {fa(row.lists.avg_delay_minutes)} دقیقه
                </Link>
              </td>
            </tr>
          ))}
        </tbody>
        <tfoot>
          <tr className="border-t-2 border-slate-200 bg-slate-50/70 text-xs">
            <td className="px-3 py-2.5 font-black text-slate-800">جمع محدوده</td>
            <td className="px-3 py-2.5 font-black tabular-nums text-slate-700">
              {fa(rows.reduce((sum, row) => sum + row.sessions, 0))}
            </td>
            <td className="px-3 py-2.5 font-black tabular-nums text-emerald-700">
              {fa(totals.present)}
            </td>
            <td className="px-3 py-2.5 font-black tabular-nums text-amber-700">
              {fa(totals.late)}
            </td>
            <td className="px-3 py-2.5 font-black tabular-nums text-rose-700">
              {fa(totals.absent)}
            </td>
            <td className="px-3 py-2.5 font-black tabular-nums text-slate-700">
              {fa(totals.unchecked)}
            </td>
            <td className="px-3 py-2.5 font-black tabular-nums text-orange-700">
              {fa(lists.pending)}
            </td>
            <td className="px-3 py-2.5 text-slate-500">لیست تکمیل: {fa(lists.complete)}</td>
          </tr>
        </tfoot>
      </table>
    </div>
  );
}

function PeriodBreakdown({ rows, hrefFor }: { rows: PeriodRow[]; hrefFor: HrefFor }) {
  if (rows.length === 0) {
    return <EmptyState>زنگی در این محدوده داده ندارد.</EmptyState>;
  }
  const max = Math.max(...rows.map((row) => row.total), 1);

  return (
    <ul className="space-y-2">
      {rows.map((row) => (
        <li key={row.period_id ?? row.period_title} className="rounded-2xl bg-slate-50 px-3 py-2">
          <div className="mb-1.5 flex flex-wrap items-center justify-between gap-2 text-xs">
            <Link
              href={hrefFor({ dataset: "students", periodId: row.period_id })}
              className="font-bold text-slate-700 hover:text-teal-700"
            >
              {row.period_title}
            </Link>
            <span className="tabular-nums text-slate-500">
              {fa(row.sessions)} جلسه · {fa(row.total)} نفر-جلسه
            </span>
          </div>
          <div className="flex h-2.5 overflow-hidden rounded-full bg-slate-200" dir="ltr">
            <span
              style={{ width: `${(row.present / max) * 100}%`, background: STATUS_META.present.color }}
            />
            <span
              style={{ width: `${(row.late / max) * 100}%`, background: STATUS_META.late.color }}
            />
            <span
              style={{ width: `${(row.absent / max) * 100}%`, background: STATUS_META.absent.color }}
            />
            <span
              style={{
                width: `${(row.temporary_exit / max) * 100}%`,
                background: STATUS_META.temporary_exit.color,
              }}
            />
            <span
              style={{
                width: `${(row.unchecked / max) * 100}%`,
                background: STATUS_META.unchecked.color,
              }}
            />
          </div>
          <p className="mt-1 flex flex-wrap gap-x-3 text-[10px] text-slate-500">
            <span>حاضر {fa(row.present)}</span>
            <span>تأخیر {fa(row.late)}</span>
            <span>غایب {fa(row.absent)}</span>
            <span>خروج موقت {fa(row.temporary_exit)}</span>
            <span>ثبت‌نشده {fa(row.unchecked)}</span>
          </p>
        </li>
      ))}
    </ul>
  );
}

function StatCell({ value, href, tone }: { value: number; href: string; tone: string }) {
  return (
    <Link
      href={href}
      className={`inline-flex min-w-[2.5rem] justify-center rounded-lg bg-white px-2 py-1 text-sm font-black tabular-nums ring-1 ring-slate-200 transition hover:ring-teal-300 ${tone}`}
    >
      {fa(value)}
    </Link>
  );
}

function TabBtn({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`rounded-xl px-3 py-1.5 text-xs font-bold ${
        active ? "bg-teal-700 text-white" : "bg-slate-100 text-slate-600"
      }`}
    >
      {children}
    </button>
  );
}
