"use client";

import { useEffect, useRef, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Button,
  Card,
  EmptyState,
  PageHeader,
  PageLoader,
  Select,
  StatCard,
  StatusBadge,
} from "@/components/ui";
import { useApi } from "@/lib/client";
import { downloadCsv, formatBDT, formatDate, formatNumber, type Locale } from "@/lib/utils";
import { CHART_TOKENS, MoneyBarsChart, RateTrendChart, rateBarColor } from "@/components/charts";
import {
  IconActivity,
  IconAlertTriangle,
  IconAward,
  IconBarChart,
  IconBell,
  IconBuilding,
  IconCalendar,
  IconChevronDown,
  IconClipboard,
  IconDollar,
  IconMapPin,
  IconPieChart,
  IconSparkle,
  IconUserCheck,
  IconUsers,
} from "@/components/icons";

type Period = "daily" | "weekly" | "monthly";
type Tab = "exams" | "fees" | "attendance" | "communication";

interface RateTrend {
  label: string;
  rate: number | null;
}

interface MonitoringData {
  period: Period;
  from: string;
  to: string;
  district: string;
  subDistrict: string;
  scope: { institutions: number; students: number; teachers: number; districts: number; subDistricts: number };
  rowLevel: "DISTRICT" | "SUB_DISTRICT" | "INSTITUTION";
  rows: {
    key: string;
    label: string;
    institutions: number;
    students: number;
    teachers: number;
    exams: number;
    feesCollected: number;
    openComplaints: number;
    studentRate: number | null;
    teacherRate: number | null;
  }[];
  exams: {
    counts: { total: number; upcoming: number; running: number; finished: number };
    publishedResults: number;
    recent: {
      id: number;
      name: string;
      institutionName: string;
      className: string | null;
      status: string;
      startDate: string;
      endDate: string | null;
      papers: number;
      schedulePublished: boolean;
      resultPublished: boolean;
    }[];
  };
  results: {
    examId: number;
    name: string;
    institutionName: string;
    className: string | null;
    status: string;
    resultPublished: boolean;
    marksEntered: number;
    avgPercent: number | null;
    highestPercent: number | null;
    lowestPercent: number | null;
  }[];
  fees: {
    periodCollected: number;
    periodCount: number;
    byMethod: { method: string; amount: number; count: number }[];
    monthly: { key: string; label: string; total: number }[];
    byInstitution: { institutionName: string; amount: number; count: number }[];
  };
  attendance: {
    student: { present: number; absent: number; leave: number; rate: number | null; trend: RateTrend[] };
    teacher: { present: number; absent: number; leave: number; rate: number | null; trend: RateTrend[] };
    byInstitution: { institutionName: string; studentRate: number | null; teacherRate: number | null }[];
  };
  notices: {
    activeCount: number;
    recent: { id: number; title: string; audience: string; publishDate: string; isPinned: boolean; institution: { name: string } }[];
  };
  events: {
    upcomingCount: number;
    recent: { id: number; title: string; venue: string | null; category: string; startDate: string; endDate: string | null; institution: { name: string } }[];
  };
  complaints: {
    counts: { PENDING: number; IN_REVIEW: number; RESOLVED: number; REJECTED: number };
    openCount: number;
    recent: { id: number; subject: string; category: string; status: string; complainantType: string; createdAt: string; institution: { name: string } }[];
  };
  options: {
    districts: { district: string; count: number }[];
    subDistricts: { subDistrict: string; count: number }[];
  };
}

function RateText({ rate, locale }: { rate: number | null; locale: Locale }) {
  if (rate == null) return <span className="text-muted">—</span>;
  const color = rate >= 90 ? "text-success" : rate >= 75 ? "text-warning" : "text-danger";
  return <span className={`f-w-700 ${color}`}>{formatNumber(rate, locale)}%</span>;
}

/** Count-up numeral — tweens between values (550ms, ease-out) with stable width. */
function AnimatedNumber({ value, format }: { value: number; format: (v: number) => string }) {
  const [display, setDisplay] = useState(0);
  const fromRef = useRef(0);

  useEffect(() => {
    const from = fromRef.current;
    const to = value;
    if (from === to) {
      setDisplay(to);
      return;
    }
    fromRef.current = to;
    const duration = 550;
    const start = performance.now();
    let raf = 0;
    const tick = (now: number) => {
      const p = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setDisplay(from + (to - from) * eased);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [value]);

  return <span className="ems-num">{format(display)}</span>;
}

export default function CentralMonitoringPage() {
  const { t, locale } = useLang();
  const [district, setDistrict] = useState("");
  const [subDistrict, setSubDistrict] = useState("");
  const [period, setPeriod] = useState<Period>("monthly");
  const [tab, setTab] = useState<Tab>("exams");

  const params = new URLSearchParams();
  if (district) params.set("district", district);
  if (subDistrict) params.set("subDistrict", subDistrict);
  params.set("period", period);
  const { data, loading } = useApi<MonitoringData>(`/api/central/monitoring?${params.toString()}`);

  const periodLabel = period === "daily" ? t.common.daily : period === "weekly" ? t.common.weekly : t.common.monthly;
  const rowHint =
    data?.rowLevel === "DISTRICT"
      ? t.central.monitoringPage.drillHintDistrict
      : data?.rowLevel === "SUB_DISTRICT"
        ? t.central.monitoringPage.drillHintSubDistrict
        : t.central.monitoringPage.drillHintInstitution;

  function drillRow(label: string) {
    // district rows drill into sub-districts; sub-district rows into institutions
    if (!district) setDistrict(label || "");
    else if (!subDistrict) setSubDistrict(label || "");
  }

  function exportSummaryCsv() {
    if (!data) return;
    const header = [
      data.rowLevel === "INSTITUTION" ? t.common.institution : data.rowLevel === "SUB_DISTRICT" ? t.common.subDistrict : t.common.district,
      t.common.institutions, t.common.students, t.common.teachers,
      t.central.monitoringPage.recentExams, t.central.monitoringPage.collectedInPeriod,
      t.central.monitoringPage.openComplaints, `${t.common.attendance} (%) — ${t.common.students}`,
      `${t.common.attendance} (%) — ${t.common.teachers}`,
    ];
    const rows = data.rows.map((r) => [
      r.label || t.common.unassigned,
      r.institutions, r.students, r.teachers, r.exams, r.feesCollected, r.openComplaints,
      r.studentRate ?? "", r.teacherRate ?? "",
    ]);
    downloadCsv(`central-monitoring-${district || "all"}-${period}.csv`, [header, ...rows]);
  }

  const tabs: { key: Tab; label: string; icon: React.ReactNode; badge?: number }[] = [
    { key: "exams", label: t.central.monitoringPage.tabExams, icon: <IconClipboard className="svg-16" />, badge: data?.exams.counts.total },
    { key: "fees", label: t.central.monitoringPage.tabFees, icon: <IconDollar className="svg-16" /> },
    { key: "attendance", label: t.central.monitoringPage.tabAttendance, icon: <IconUserCheck className="svg-16" /> },
    { key: "communication", label: t.central.monitoringPage.tabCommunication, icon: <IconBell className="svg-16" />, badge: data?.complaints.openCount },
  ];

  const int = (v: number) => formatNumber(Math.round(v), locale);

  return (
    <div>
      <PageHeader title={t.central.monitoringPage.title} subtitle={t.central.monitoringPage.subtitle} />

      {/* Filters — always visible and interactive, even while results refresh */}
      <div className="card mb-4">
        <div className="card-body">
          <div className="row align-items-end g-3">
            <div className="col-md-4">
              <Select
                label={t.common.district}
                value={district}
                onChange={(e) => {
                  setDistrict(e.target.value);
                  setSubDistrict("");
                }}
              >
                <option value="">{t.central.monitoringPage.allDistricts}</option>
                {(data?.options.districts ?? []).map((d) => (
                  <option key={d.district || "none"} value={d.district}>
                    {d.district || t.common.unassigned} ({d.count})
                  </option>
                ))}
              </Select>
            </div>
            <div className="col-md-4">
              <Select
                label={t.common.subDistrict}
                value={subDistrict}
                onChange={(e) => setSubDistrict(e.target.value)}
                disabled={!district}
              >
                <option value="">{t.central.monitoringPage.allSubDistricts}</option>
                {(data?.options.subDistricts ?? []).map((s) => (
                  <option key={s.subDistrict} value={s.subDistrict}>
                    {s.subDistrict} ({s.count})
                  </option>
                ))}
              </Select>
            </div>
            <div className="col-md-4">
              <label className="col-form-label pt-0 f-w-600 d-block">{t.central.monitoringPage.period}</label>
              <div className="btn-group w-100" role="group">
                {(["daily", "weekly", "monthly"] as Period[]).map((p) => (
                  <button
                    key={p}
                    type="button"
                    aria-pressed={period === p}
                    className={`btn btn-sm ${period === p ? "btn-primary" : "btn-outline-secondary"}`}
                    onClick={() => setPeriod(p)}
                  >
                    {p === "daily" ? t.common.daily : p === "weekly" ? t.common.weekly : t.common.monthly}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Location breadcrumb: All districts › District › Sub-district */}
          {(district || subDistrict) && (
            <nav aria-label="location" className="ems-crumb mt-3 ems-fade-in" key={`${district}|${subDistrict}`}>
              <button
                type="button"
                className="ems-crumb-link"
                onClick={() => {
                  setDistrict("");
                  setSubDistrict("");
                }}
              >
                {t.central.monitoringPage.allDistricts}
              </button>
              {district && (
                <>
                  <span className="ems-crumb-sep">›</span>
                  {subDistrict ? (
                    <button type="button" className="ems-crumb-link" onClick={() => setSubDistrict("")}>
                      {district}
                    </button>
                  ) : (
                    <span className="ems-crumb-current">{district}</span>
                  )}
                </>
              )}
              {district && subDistrict && (
                <>
                  <span className="ems-crumb-sep">›</span>
                  <span className="ems-crumb-current">{subDistrict}</span>
                </>
              )}
            </nav>
          )}
        </div>
      </div>

      {loading && !data ? (
        <PageLoader text={t.common.loading} />
      ) : !data ? (
        <EmptyState title={t.common.tryAgain} />
      ) : (
        /* Previous results stay mounted under a soft veil while a filter refetches */
        <div className="ems-mon-veil-host">
          {loading && (
            <div className="ems-mon-veil">
              <div className="text-center">
                <span className="spinner-border spinner-border-sm text-primary" role="status" />
                <p className="mb-0 ems-fs-12 text-muted mt-2">{t.common.processing}</p>
              </div>
            </div>
          )}
          <div className={`ems-mon-content ${loading ? "is-loading" : ""}`}>
          {/* Scope summary */}
          <div className="row g-4 mb-2">
            {[
              {
                node: (
                  <StatCard
                    label={t.common.institutions}
                    value={<AnimatedNumber value={data.scope.institutions} format={int} />}
                    icon={<IconBuilding />}
                    accent="teal"
                    hint={`${data.scope.districts} ${t.central.monitoringPage.districtsCovered} · ${data.scope.subDistricts} ${t.central.monitoringPage.subDistrictsCovered}`}
                  />
                ),
              },
              {
                node: (
                  <StatCard
                    label={t.common.students}
                    value={<AnimatedNumber value={data.scope.students} format={int} />}
                    icon={<IconUsers />}
                    accent="blue"
                  />
                ),
              },
              {
                node: (
                  <StatCard
                    label={t.common.teachers}
                    value={<AnimatedNumber value={data.scope.teachers} format={int} />}
                    icon={<IconUserCheck />}
                    accent="purple"
                  />
                ),
              },
              {
                node: (
                  <StatCard
                    label={t.central.monitoringPage.openComplaints}
                    value={<AnimatedNumber value={data.complaints.openCount} format={int} />}
                    icon={<IconAlertTriangle />}
                    accent={data.complaints.openCount > 0 ? "orange" : "sky"}
                    hint={periodLabel}
                  />
                ),
              },
            ].map((card, i) => (
              <div className="col-xl-3 col-md-6 ems-fade-in" style={{ animationDelay: `${i * 60}ms` }} key={i}>
                {card.node}
              </div>
            ))}
          </div>

          {/* Area-wise drill-down */}
          <div className="row mb-2">
            <div className="col-12 ems-fade-in" style={{ animationDelay: "220ms" }}>
              <Card
                title={t.central.monitoringPage.drillTitle}
                icon={<IconMapPin className="svg-20" />}
                action={
                  <Button size="sm" variant="secondary" onClick={exportSummaryCsv} disabled={data.rows.length === 0}>
                    CSV
                  </Button>
                }
              >
                <p className="ems-fs-12 text-muted mb-3">
                  {rowHint} · {periodLabel}: {formatDate(data.from, locale)} → {formatDate(new Date(new Date(data.to).getTime() - 86400000), locale)}
                </p>
                {data.rows.length === 0 ? (
                  <EmptyState icon={<IconMapPin />} title={t.central.monitoringPage.noInstitutionsInScope} />
                ) : (
                  <div className="table-responsive">
                    <table className="table table-hover align-middle mb-0">
                      <thead className="ems-table-head">
                        <tr>
                          <th>
                            {data.rowLevel === "INSTITUTION"
                              ? t.common.institution
                              : data.rowLevel === "SUB_DISTRICT"
                                ? t.common.subDistrict
                                : t.common.district}
                          </th>
                          <th className="text-center">{t.common.institutions}</th>
                          <th className="text-center">{t.common.students}</th>
                          <th className="text-center">{t.common.teachers}</th>
                          <th className="text-center">{t.central.monitoringPage.recentExams}</th>
                          <th className="text-end">{t.central.monitoringPage.collectedInPeriod}</th>
                          <th className="text-center">{t.central.monitoringPage.openComplaints}</th>
                          <th className="text-center">{t.common.students} %</th>
                          <th className="text-center">{t.common.teachers} %</th>
                        </tr>
                      </thead>
                      <tbody>
                        {data.rows.map((r, idx) => {
                          const clickable = data.rowLevel !== "INSTITUTION";
                          return (
                            <tr
                              key={r.key}
                              className={`ems-row-in ${clickable ? "ems-clickable" : ""}`}
                              style={{ animationDelay: `${Math.min(idx * 45, 360)}ms` }}
                              tabIndex={clickable ? 0 : undefined}
                              onClick={() => clickable && drillRow(r.label)}
                              onKeyDown={(e) => {
                                if (clickable && e.key === "Enter") drillRow(r.label);
                              }}
                            >
                              <td className="f-w-600">
                                <span className="d-flex align-items-center gap-2">
                                  <IconMapPin className="svg-16 text-muted" />
                                  {r.label || t.common.unassigned}
                                  {clickable && (
                                    <span className="ms-auto text-muted d-inline-flex" style={{ transform: "rotate(-90deg)" }}>
                                      <IconChevronDown className="svg-16" />
                                    </span>
                                  )}
                                </span>
                              </td>
                              <td className="text-center">{r.institutions}</td>
                              <td className="text-center">{formatNumber(r.students, locale)}</td>
                              <td className="text-center">{formatNumber(r.teachers, locale)}</td>
                              <td className="text-center">{r.exams}</td>
                              <td className="text-end f-w-700 text-success">{r.feesCollected > 0 ? formatBDT(r.feesCollected, locale) : "—"}</td>
                              <td className="text-center">{r.openComplaints > 0 ? <span className="badge badge-pill badge-warning">{r.openComplaints}</span> : "—"}</td>
                              <td className="text-center"><RateText rate={r.studentRate} locale={locale} /></td>
                              <td className="text-center"><RateText rate={r.teacherRate} locale={locale} /></td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                )}
              </Card>
            </div>
          </div>

          {/* Section tabs */}
          <ul className="nav nav-tabs mb-4" role="tablist">
            {tabs.map((tb) => (
              <li className="nav-item" role="presentation" key={tb.key}>
                <button
                  className={`nav-link d-flex align-items-center gap-2 ${tab === tb.key ? "active" : ""}`}
                  role="tab"
                  aria-selected={tab === tb.key}
                  onClick={() => setTab(tb.key)}
                  type="button"
                >
                  {tb.icon}
                  {tb.label}
                  {tb.badge != null && (
                    <span className={`badge ${tab === tb.key ? "badge-light text-dark" : "badge-secondary"}`}>{tb.badge}</span>
                  )}
                </button>
              </li>
            ))}
          </ul>

          {/* key={tab} replays the slide-in on every tab switch */}
          <div key={tab} className="ems-tab-panel">
            {/* ------------------------- EXAMS & RESULTS ------------------------- */}
            {tab === "exams" && (
              <div className="row g-4">
                <div className="col-12">
                  <div className="row g-4">
                    <div className="col-xl-3 col-md-6">
                      <StatCard label={t.central.monitoringPage.recentExams} value={<AnimatedNumber value={data.exams.counts.total} format={int} />} icon={<IconClipboard />} accent="teal" hint={`${data.exams.publishedResults} ${t.central.monitoringPage.resultsPublished}`} />
                    </div>
                    <div className="col-xl-3 col-md-6">
                      <StatCard label={t.common.upcoming} value={<AnimatedNumber value={data.exams.counts.upcoming} format={int} />} icon={<IconCalendar />} accent="sky" />
                    </div>
                    <div className="col-xl-3 col-md-6">
                      <StatCard label={t.common.running} value={<AnimatedNumber value={data.exams.counts.running} format={int} />} icon={<IconActivity />} accent="orange" />
                    </div>
                    <div className="col-xl-3 col-md-6">
                      <StatCard label={t.common.finished} value={<AnimatedNumber value={data.exams.counts.finished} format={int} />} icon={<IconAward />} accent="purple" />
                    </div>
                  </div>
                </div>

                <div className="col-12">
                  <Card title={t.central.monitoringPage.recentExams} icon={<IconClipboard className="svg-20" />}>
                    {data.exams.recent.length === 0 ? (
                      <EmptyState icon={<IconClipboard />} title={t.central.monitoringPage.noExams} />
                    ) : (
                      <div className="table-responsive">
                        <table className="table table-hover align-middle mb-0">
                          <thead className="ems-table-head">
                            <tr>
                              <th>{t.common.institution}</th>
                              <th>{t.central.monitoringPage.recentExams}</th>
                              <th>{t.common.status}</th>
                              <th>{t.common.date}</th>
                              <th className="text-center">{t.common.papers}</th>
                              <th className="text-center">{t.central.monitoringPage.publishedSchedules}</th>
                              <th className="text-center">{t.central.monitoringPage.resultsPublished}</th>
                            </tr>
                          </thead>
                          <tbody>
                            {data.exams.recent.map((e) => (
                              <tr key={e.id}>
                                <td className="f-w-600 ems-fs-13">{e.institutionName}</td>
                                <td>
                                  <span className="f-w-600">{e.name}</span>
                                  {e.className && <span className="d-block ems-fs-11 text-muted">{e.className}</span>}
                                </td>
                                <td><StatusBadge status={e.status} label={t.status[e.status as keyof typeof t.status]} /></td>
                                <td className="ems-fs-12 text-muted">
                                  {formatDate(e.startDate, locale)}
                                  {e.endDate ? ` → ${formatDate(e.endDate, locale)}` : ""}
                                </td>
                                <td className="text-center">{e.papers}</td>
                                <td className="text-center">{e.schedulePublished ? <IconAward className="svg-16 text-success" /> : <span className="text-muted">—</span>}</td>
                                <td className="text-center">{e.resultPublished ? <IconAward className="svg-16 text-success" /> : <span className="text-muted">—</span>}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </Card>
                </div>

                <div className="col-12">
                  <Card title={t.central.monitoringPage.examResultsStats} icon={<IconAward className="svg-20" />}>
                    <p className="ems-fs-12 text-muted mb-3">{t.central.monitoringPage.resultsHint}</p>
                    {data.results.length === 0 ? (
                      <EmptyState icon={<IconAward />} title={t.central.monitoringPage.noResults} />
                    ) : (
                      <div className="table-responsive">
                        <table className="table table-hover align-middle mb-0">
                          <thead className="ems-table-head">
                            <tr>
                              <th>{t.central.monitoringPage.recentExams}</th>
                              <th>{t.common.institution}</th>
                              <th className="text-center">{t.central.monitoringPage.marksEntered}</th>
                              <th className="text-center">{t.common.average} %</th>
                              <th className="text-center">{t.common.highest} %</th>
                              <th className="text-center">{t.common.lowest} %</th>
                              <th className="text-center">{t.central.monitoringPage.resultsPublished}</th>
                            </tr>
                          </thead>
                          <tbody>
                            {data.results.map((r) => (
                              <tr key={r.examId}>
                                <td className="f-w-600">{r.name}{r.className ? <span className="d-block ems-fs-11 text-muted">{r.className}</span> : null}</td>
                                <td className="ems-fs-13">{r.institutionName}</td>
                                <td className="text-center f-w-700">{formatNumber(r.marksEntered, locale)}</td>
                                <td className="text-center"><RateText rate={r.avgPercent} locale={locale} /></td>
                                <td className="text-center f-w-700 text-success">{r.highestPercent != null ? `${formatNumber(r.highestPercent, locale)}%` : "—"}</td>
                                <td className="text-center f-w-700 text-danger">{r.lowestPercent != null ? `${formatNumber(r.lowestPercent, locale)}%` : "—"}</td>
                                <td className="text-center">{r.resultPublished ? <IconAward className="svg-16 text-success" /> : <span className="text-muted">—</span>}</td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </Card>
                </div>
              </div>
            )}

            {/* --------------------------- FEE COLLECTION --------------------------- */}
            {tab === "fees" && (
              <div className="row g-4">
                <div className="col-xl-3 col-md-6">
                  <StatCard
                    label={`${t.central.monitoringPage.collectedInPeriod} (${periodLabel})`}
                    value={<AnimatedNumber value={data.fees.periodCollected} format={(v) => formatBDT(Math.round(v), locale)} />}
                    icon={<IconDollar />}
                    accent="teal"
                  />
                </div>
                <div className="col-xl-3 col-md-6">
                  <StatCard
                    label={t.central.monitoringPage.collectionsInPeriod}
                    value={<AnimatedNumber value={data.fees.periodCount} format={int} />}
                    icon={<IconPieChart />}
                    accent="blue"
                    hint={`${data.fees.byMethod.length} ${t.common.method}`}
                  />
                </div>

                {/* Method split */}
                <div className="col-xl-4">
                  <Card title={t.central.monitoringPage.byMethod} icon={<IconPieChart className="svg-20" />}>
                    {data.fees.byMethod.length === 0 ? (
                      <EmptyState icon={<IconDollar />} title={t.central.monitoringPage.noFees} />
                    ) : (
                      <div className="d-flex flex-column gap-3">
                        {(() => {
                          const max = Math.max(1, ...data.fees.byMethod.map((m) => m.amount));
                          return data.fees.byMethod.map((m) => (
                            <div key={m.method}>
                              <div className="d-flex justify-content-between mb-1">
                                <span className="ems-fs-12 f-w-600">
                                  {t.methods[m.method as keyof typeof t.methods]}
                                  <span className="text-muted f-w-500 ms-1">({m.count} {t.central.monitoringPage.transactions})</span>
                                </span>
                                <span className="ems-fs-12 f-w-700 text-success">{formatBDT(m.amount, locale)}</span>
                              </div>
                              <div className="progress" style={{ height: 8 }}>
                                <div
                                  className="progress-bar bg-success"
                                  role="progressbar"
                                  style={{ width: `${Math.max(2, (m.amount / max) * 100)}%` }}
                                />
                              </div>
                            </div>
                          ));
                        })()}
                      </div>
                    )}
                  </Card>
                </div>

                {/* Monthly trend */}
                <div className="col-xl-5">
                  <Card title={t.central.monitoringPage.monthlyTrend} icon={<IconBarChart className="svg-20" />}>
                    <MoneyBarsChart
                      height={190}
                      valueLabels
                      labels={data.fees.monthly.map((m) => m.label)}
                      series={[
                        {
                          name: t.central.monitoringPage.collectedInPeriod,
                          data: data.fees.monthly.map((m) => m.total),
                          colors: [CHART_TOKENS.tealSoft, CHART_TOKENS.teal],
                        },
                      ]}
                      formatValue={(n) => formatBDT(n, locale)}
                    />
                  </Card>
                </div>

                {/* Top institutions */}
                <div className="col-xl-3">
                  <Card title={t.central.monitoringPage.topInstitutions} icon={<IconBuilding className="svg-20" />}>
                    {data.fees.byInstitution.length === 0 ? (
                      <EmptyState icon={<IconDollar />} title={t.central.monitoringPage.noFees} />
                    ) : (
                      <div className="d-flex flex-column gap-3">
                        {data.fees.byInstitution.map((i, idx) => (
                          <div className="media align-items-center gap-3" key={i.institutionName + idx}>
                            <span className="ems-fs-12 f-w-800 text-muted">#{idx + 1}</span>
                            <div className="media-body">
                              <p className="mb-0 f-w-600 ems-fs-13 text-truncate">{i.institutionName}</p>
                              <p className="mb-0 ems-fs-11 text-muted">{i.count} {t.central.monitoringPage.transactions}</p>
                            </div>
                            <span className="f-w-700 text-success ems-fs-13">{formatBDT(i.amount, locale)}</span>
                          </div>
                        ))}
                      </div>
                    )}
                  </Card>
                </div>
              </div>
            )}

            {/* ----------------------------- ATTENDANCE ----------------------------- */}
            {tab === "attendance" && (
              <div className="row g-4">
                {(
                  [
                    { key: "student", title: t.central.monitoringPage.studentAttendance, agg: data.attendance.student, icon: <IconUsers />, accent: "teal" },
                    { key: "teacher", title: t.central.monitoringPage.teacherAttendance, agg: data.attendance.teacher, icon: <IconUserCheck />, accent: "blue" },
                  ] as const
                ).map((block) => (
                  <div className="col-xl-3 col-md-6" key={block.key}>
                    <div className="card h-100">
                      <div className="card-body">
                        <div className="d-flex align-items-center gap-3 mb-3">
                          <span className={`ems-stat-icon ${block.accent}`}>{block.icon}</span>
                          <h6 className="mb-0 f-w-700">{block.title}</h6>
                        </div>
                        <div className="text-center mb-3">
                          <span className="f-w-800" style={{ fontSize: 34 }}>
                            {block.agg.rate == null ? (
                              <span className="text-muted">—</span>
                            ) : (
                              <span className={block.agg.rate >= 90 ? "text-success" : block.agg.rate >= 75 ? "text-warning" : "text-danger"}>
                                <AnimatedNumber value={block.agg.rate} format={(v) => `${formatNumber(Math.round(v * 10) / 10, locale)}%`} />
                              </span>
                            )}
                          </span>
                          <p className="mb-0 ems-fs-11 text-muted">{periodLabel}</p>
                        </div>
                        <div className="d-flex justify-content-between ems-fs-12">
                          <span className="text-success f-w-600">{t.common.present}: {formatNumber(block.agg.present, locale)}</span>
                          <span className="text-danger f-w-600">{t.common.absent}: {formatNumber(block.agg.absent, locale)}</span>
                          <span className="text-warning f-w-600">{t.common.leave}: {formatNumber(block.agg.leave, locale)}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}

                {/* Trend */}
                <div className="col-xl-6">
                  <Card title={t.central.monitoringPage.attendanceTrend} icon={<IconBarChart className="svg-20" />}>
                    {data.attendance.student.trend.every((b) => b.rate == null) ? (
                      <EmptyState icon={<IconBarChart />} title={t.central.monitoringPage.noAttendance} />
                    ) : (
                      <div className="row g-3">
                        {(
                          [
                            { label: t.central.monitoringPage.studentAttendance, trend: data.attendance.student.trend, dot: "bg-success" },
                            { label: t.central.monitoringPage.teacherAttendance, trend: data.attendance.teacher.trend, dot: "bg-primary" },
                          ] as const
                        ).map((series) => (
                          <div className="col-md-6" key={series.label}>
                            <p className="ems-fs-12 f-w-700 mb-2 d-flex align-items-center gap-2">
                              <span className={`d-inline-block rounded-circle ${series.dot}`} style={{ width: 8, height: 8 }} />
                              {series.label}
                            </p>
                            <RateTrendChart
                              height={150}
                              labels={series.trend.map((b) => b.label)}
                              values={series.trend.map((b) => b.rate)}
                              colors={series.trend.map((b) =>
                                rateBarColor(b.rate, 75, series.dot === "bg-primary" ? CHART_TOKENS.blue : CHART_TOKENS.teal)
                              )}
                              suffix="%"
                            />
                          </div>
                        ))}
                      </div>
                    )}
                  </Card>
                </div>

                {/* By institution */}
                <div className="col-xl-6">
                  <Card title={t.central.monitoringPage.attendanceByInstitution} icon={<IconBuilding className="svg-20" />}>
                    {data.attendance.byInstitution.length === 0 || data.attendance.byInstitution.every((i) => i.studentRate == null && i.teacherRate == null) ? (
                      <EmptyState icon={<IconBuilding />} title={t.central.monitoringPage.noAttendance} />
                    ) : (
                      <div className="table-responsive">
                        <table className="table table-hover align-middle mb-0">
                          <thead className="ems-table-head">
                            <tr>
                              <th>{t.common.institution}</th>
                              <th className="text-center">{t.common.students} %</th>
                              <th className="text-center">{t.common.teachers} %</th>
                            </tr>
                          </thead>
                          <tbody>
                            {data.attendance.byInstitution.map((i, idx) => (
                              <tr key={i.institutionName + idx}>
                                <td className="f-w-600 ems-fs-13">{i.institutionName}</td>
                                <td className="text-center"><RateText rate={i.studentRate} locale={locale} /></td>
                                <td className="text-center"><RateText rate={i.teacherRate} locale={locale} /></td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </Card>
                </div>
              </div>
            )}

            {/* -------------------- NOTICES / EVENTS / COMPLAINTS -------------------- */}
            {tab === "communication" && (
              <div className="row g-4">
                {/* Notices */}
                <div className="col-xl-4">
                  <Card title={`${t.central.monitoringPage.activeNotices} (${data.notices.activeCount})`} icon={<IconBell className="svg-20" />} className="h-100">
                    {data.notices.recent.length === 0 ? (
                      <EmptyState icon={<IconBell />} title={t.central.monitoringPage.noNotices} />
                    ) : (
                      <div className="d-flex flex-column gap-3">
                        {data.notices.recent.map((n) => (
                          <div key={n.id}>
                            <p className="mb-1 f-w-600 ems-fs-13">
                              {n.isPinned && <IconSparkle className="svg-16 text-warning me-1" />}
                              {n.title}
                            </p>
                            <p className="mb-0 ems-fs-11 text-muted">
                              {n.institution.name} · {formatDate(n.publishDate, locale)} · {n.audience}
                            </p>
                          </div>
                        ))}
                      </div>
                    )}
                  </Card>
                </div>

                {/* Events */}
                <div className="col-xl-4">
                  <Card title={`${t.central.monitoringPage.upcomingEvents} (${data.events.upcomingCount})`} icon={<IconCalendar className="svg-20" />} className="h-100">
                    {data.events.recent.length === 0 ? (
                      <EmptyState icon={<IconCalendar />} title={t.central.monitoringPage.noEvents} />
                    ) : (
                      <div className="d-flex flex-column gap-3">
                        {data.events.recent.map((e) => (
                          <div key={e.id}>
                            <p className="mb-1 f-w-600 ems-fs-13">{e.title}</p>
                            <p className="mb-0 ems-fs-11 text-muted">
                              {e.institution.name} · {formatDate(e.startDate, locale)}
                              {e.venue ? ` · ${e.venue}` : ""}
                            </p>
                          </div>
                        ))}
                      </div>
                    )}
                  </Card>
                </div>

                {/* Complaints */}
                <div className="col-xl-4">
                  <Card title={t.central.monitoringPage.complaintStatusSummary} icon={<IconAlertTriangle className="svg-20" />} className="h-100">
                    <div className="d-flex flex-wrap gap-2 mb-3">
                      {(["PENDING", "IN_REVIEW", "RESOLVED", "REJECTED"] as const).map((s) => (
                        <StatusBadge key={s} status={s} label={`${t.status[s]}: ${data.complaints.counts[s]}`} />
                      ))}
                    </div>
                    {data.complaints.recent.length === 0 ? (
                      <EmptyState icon={<IconAlertTriangle />} title={t.central.monitoringPage.noComplaints} />
                    ) : (
                      <div className="d-flex flex-column gap-3">
                        {data.complaints.recent.map((c) => (
                          <div key={c.id} className="d-flex justify-content-between align-items-start gap-2">
                            <div>
                              <p className="mb-1 f-w-600 ems-fs-13">{c.subject}</p>
                              <p className="mb-0 ems-fs-11 text-muted">
                                {c.institution.name} · {c.category} · {formatDate(c.createdAt, locale)}
                              </p>
                            </div>
                            <StatusBadge status={c.status} label={t.status[c.status as keyof typeof t.status]} />
                          </div>
                        ))}
                      </div>
                    )}
                  </Card>
                </div>
              </div>
            )}
          </div>
          </div>
        </div>
      )}
    </div>
  );
}
