"use client";

import { useState } from "react";
import Link from "next/link";
import { useLang } from "@/context/LanguageContext";
import { AttendanceDonut, CHART_TOKENS, RateTrendChart, rateBarColor } from "@/components/charts";
import {
  Alert,
  Button,
  Card,
  DatePicker,
  EmptyState,
  PageLoader,
  StatusBadge,
} from "@/components/ui";
import { useApi } from "@/lib/client";
import { ACADEMIC_CATEGORIES } from "@/lib/constants";
import { formatBDT, formatDate } from "@/lib/utils";
import {
  IconAcademic,
  IconBell,
  IconBriefcase,
  IconCalendar,
  IconCard,
  IconCheckCircle,
  IconClock,
  IconLifeBuoy,
  IconMail,
  IconMap,
  IconPackage,
  IconPhone,
  IconUserCheck,
  IconUsers,
} from "@/components/icons";

interface NoticeItem {
  id: number;
  title: string;
  titleBn: string | null;
  publishDate: string;
  isPinned: boolean;
}

interface EventItem {
  id: number;
  title: string;
  titleBn: string | null;
  startDate: string;
  endDate: string | null;
  venue: string | null;
}

interface FeeRow {
  id: number;
  invoiceNo: string;
  amount: number;
  method: string;
  paidAt: string;
  studentName: string;
  studentRoll: string;
}

interface AttGroup {
  name: string;
  nameBn: string | null;
  total: number;
  present: number;
  absent: number;
  leave: number;
  unmarked: number;
}

interface AttSubjectRow {
  name: string;
  nameBn: string | null;
  records: number;
  present: number;
  absent: number;
  leave: number;
}

interface AttActivityRow {
  id: number;
  title: string;
  description: string | null;
  isForAll: boolean;
  recipientCount: number | null;
}

interface AttStudentRow {
  roll: string;
  name: string;
  nameBn: string | null;
  className: string | null;
}

interface AttStaffRow {
  employeeCode: string;
  name: string;
  nameBn: string | null;
  designation: string;
}

interface AttCounts {
  total: number;
  marked: number;
  present: number;
  absent: number;
  leave: number;
  unmarked: number;
  rate: number;
}

interface TodayAttendance {
  date: string;
  students: AttCounts & {
    byClass: AttGroup[];
    bySection: AttGroup[];
    byShift: AttGroup[];
    bySubject: AttSubjectRow[];
    absentStudents: AttStudentRow[];
    leaveStudents: AttStudentRow[];
  };
  teachers: AttCounts;
  staff: AttCounts & {
    absentStaff: AttStaffRow[];
    onLeaveStaff: AttStaffRow[];
  };
  trend: { date: string; rate: number }[];
  activities: AttActivityRow[];
}

type AttListBlock =
  | { title: string; kind: "student"; rows: AttStudentRow[] }
  | { title: string; kind: "staff"; rows: AttStaffRow[] };

/** attendance chart palette — the application's own design tokens */
const ATT_COLORS = {
  present: CHART_TOKENS.teal,
  absent: CHART_TOKENS.red,
  leave: CHART_TOKENS.amber,
  unmarked: CHART_TOKENS.unmarked,
};
const APP_BORDER = CHART_TOKENS.border;

/** app-native badge classes for an attendance rate */
const rateCls = (r: number) =>
  r >= 75 ? "badge badge-success" : r >= 50 ? "badge badge-warning" : "badge badge-danger";

/** legend row of an attendance donut panel */
function AttLegendRow({ color, label, value }: { color: string; label: string; value: number }) {
  return (
    <div className="d-flex align-items-center justify-content-between gap-2 ems-fs-12">
      <span className="d-inline-flex align-items-center gap-2 text-muted">
        <span className="rounded-circle d-inline-block" style={{ width: 9, height: 9, background: color }} />
        {label}
      </span>
      <span className="f-w-800">{value}</span>
    </div>
  );
}

interface Overview {
  institution: {
    name: string;
    type: string;
    status: string;
    email: string;
    phone: string;
    address: string;
    createdAt: string;
  };
  subscription: {
    id: number;
    planName: string;
    planNameBn: string;
    durationMonths: number;
    startDate: string;
    endDate: string;
    totalAmount: number;
    paid: number;
    due: number;
    daysLeft: number;
  } | null;
  academicCounts: Record<string, number>;
  totalSelected: number;
  counts: {
    students: number;
    staff: number;
    pendingAdmissions: number;
    notices: number;
    events: number;
  };
  fees: {
    collectedTotal: number;
    collectedThisMonth: number;
    recent: FeeRow[];
  };
  recentNotices: NoticeItem[];
  upcomingEvents: EventItem[];
  /** present only when this institution is a granted demo environment */
  demoAccess: {
    expiresAt: string;
    validDays: number;
    daysLeft: number;
  } | null;
  support: {
    counts: { OPEN: number; IN_PROGRESS: number; RESOLVED: number; CLOSED: number };
    recent: { id: number; subject: string; status: string; updatedAt: string }[];
  };
}

/** "07 / Aug" mini date chip for the notice/event feed. */
function FeedDate({ iso, locale }: { iso: string; locale: string }) {
  const loc = locale === "bn" ? "bn-BD" : "en-GB";
  const d = new Date(iso);
  const day = new Intl.DateTimeFormat(loc, { day: "numeric" }).format(d);
  const month = new Intl.DateTimeFormat(loc, { month: "short" }).format(d);
  return (
    <span className="ems-feed-date">
      <span>{day}</span>
      {month}
    </span>
  );
}

export default function PortalDashboard() {
  const { t, locale } = useLang();
  const { data, loading } = useApi<Overview>("/api/portal/overview");
  const [attendanceDate, setAttendanceDate] = useState(
    new Date().toISOString().slice(0, 10)
  );
  const todayISO = new Date().toISOString().slice(0, 10);
  const attendance = useApi<TodayAttendance>(
    `/api/portal/attendance/today?date=${attendanceDate}`
  );

  if (loading) return <PageLoader text={t.common.loading} />;
  if (!data) return <EmptyState title={t.common.tryAgain} />;

  const progress =
    data.subscription && data.subscription.totalAmount > 0
      ? (data.subscription.paid / data.subscription.totalAmount) * 100
      : 0;

  return (
    <div>
      {/* ---------------- Welcome hero ---------------- */}
      <div className="ems-dash-hero p-4 p-xl-5 mb-4">
        <div className="row align-items-center g-4">
          <div className="col-lg-7">
            <p className="mb-1 ems-fs-13 f-w-600" style={{ color: "rgba(255,255,255,0.85)" }}>
              {t.portal.dashboard.welcome} 👋
            </p>
            <h3 className="f-w-800 mb-3 text-white">{data.institution.name}</h3>
            <div className="d-flex flex-wrap align-items-center gap-2 mb-3">
              <span className="ems-hero-chip">
                {t.types[data.institution.type as keyof typeof t.types]}
              </span>
              <StatusBadge
                status={data.institution.status}
                label={t.status[data.institution.status as keyof typeof t.status]}
              />
              <span className="ems-hero-chip">
                <IconMail className="svg-14" />
                {data.institution.email}
              </span>
              <span className="ems-hero-chip">
                <IconPhone className="svg-14" />
                {data.institution.phone}
              </span>
            </div>
            <span className="ems-hero-chip">
              <IconCalendar className="svg-14" />
              {t.portal.dashboard.memberSince}: {formatDate(data.institution.createdAt, locale)}
            </span>
          </div>
          <div className="col-lg-5">
            <div className="ems-hero-side p-4">
              {data.subscription ? (
                <div>
                  <div className="d-flex align-items-center justify-content-between mb-3">
                    <h6 className="mb-0 f-w-800">
                      {locale === "bn" ? data.subscription.planNameBn : data.subscription.planName}
                    </h6>
                    <span className="badge badge-success">{t.portal.dashboard.activeLabel}</span>
                  </div>
                  <div className="d-flex align-items-baseline gap-2 mb-2">
                    <h3 className="f-w-800 mb-0 ems-text-teal">{data.subscription.daysLeft}</h3>
                    <span className="ems-fs-12 f-w-600 text-muted">
                      {t.portal.dashboard.daysRemaining}
                    </span>
                  </div>
                  <div className="progress ems-progress-thin mb-2">
                    <div
                      className="progress-bar bg-success"
                      role="progressbar"
                      style={{ width: `${progress}%` }}
                    />
                  </div>
                  <div className="d-flex justify-content-between ems-fs-12 f-w-700 mb-3">
                    <span className="text-success">
                      {formatBDT(data.subscription.paid, locale)} {t.portal.dashboard.totalPaid}
                    </span>
                    <span className={data.subscription.due > 0 ? "text-danger" : "text-success"}>
                      {data.subscription.due > 0
                        ? `${formatBDT(data.subscription.due, locale)} ${t.portal.dashboard.outstandingDue}`
                        : t.central.paymentsPage.fullyPaid}
                    </span>
                  </div>
                  <div className="d-flex flex-wrap justify-content-between gap-2 ems-fs-12 f-w-600 text-muted">
                    <span className="d-inline-flex align-items-center gap-1">
                      <IconClock className="svg-14" />
                      {t.portal.dashboard.expiresOn}: {formatDate(data.subscription.endDate, locale)}
                    </span>
                    <span>
                      {t.portal.dashboard.planDuration}: {data.subscription.durationMonths}{" "}
                      {t.portal.dashboard.months}
                    </span>
                  </div>
                </div>
              ) : (
                <div className="text-center py-2">
                  <IconPackage className="svg-24 text-muted mb-2" />
                  <p className="f-w-700 mb-1 ems-fs-13">{t.portal.dashboard.noPackage}</p>
                  <p className="ems-fs-12 text-muted mb-3">{t.portal.dashboard.noPackageNote}</p>
                  <Link href="/portal/packages">
                    <Button className="w-100">{t.portal.dashboard.browsePackages}</Button>
                  </Link>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Demo-window notice — the audience can operate a granted demo only
          for the limited validity the central team set */}
      {data.demoAccess && (
        <div className="mb-4">
          <Alert type="warning">
            <span className="f-w-700">{t.portal.dashboard.demoBannerTitle}: </span>
            {t.portal.dashboard.demoBannerBody
              .replace("{n}", String(data.demoAccess.validDays))
              .replace("{date}", formatDate(data.demoAccess.expiresAt, locale))
              .replace(
                "{left}",
                data.demoAccess.daysLeft > 0
                  ? `${data.demoAccess.daysLeft} ${t.portal.dashboard.daysRemaining}`
                  : t.portal.dashboard.demoBannerLastDay
              )}
          </Alert>
        </div>
      )}

      {/* Status notices */}
      {data.institution.status === "PENDING" && (
        <div className="mb-4">
          <Alert type="warning">{t.portal.dashboard.statusPendingNote}</Alert>
        </div>
      )}
      {data.institution.status === "SUSPENDED" && (
        <div className="mb-4">
          <Alert type="error">{t.portal.dashboard.statusSuspendedNote}</Alert>
        </div>
      )}

      {/* ---------------- Today Attendance (before Latest Notices) ---------------- */}
      <div className="row g-4 mb-2">
        <div className="col-12">
          <Card
            title={t.portal.dashboard.todayAttendance}
            icon={<IconCheckCircle className="svg-20" />}
            action={
              <div className="d-flex flex-wrap align-items-center gap-2">
                <DatePicker
                  wrapperClassName="form-group mb-0"
                  style={{ maxWidth: 158 }}
                  value={attendanceDate}
                  max={todayISO}
                  onChange={(e) => setAttendanceDate(e.target.value || todayISO)}
                />
                {attendanceDate !== todayISO && (
                  <Button
                    size="sm"
                    variant="secondary"
                    onClick={() => setAttendanceDate(todayISO)}
                  >
                    {t.portal.dashboard.todayLabel}
                  </Button>
                )}
                <Link
                  href="/portal/students"
                  className="ems-text-teal f-w-700 text-decoration-none ems-fs-13"
                >
                  {t.portal.dashboard.recordAttendance} →
                </Link>
              </div>
            }
          >
            {attendance.loading && !attendance.data ? (
              <div className="text-center py-4">
                <span className="spinner-border text-primary" role="status" />
              </div>
            ) : !attendance.data ? null : (
              <>
                {/* Today at a glance — students / teachers / staff donut panels */}
                <div className="row g-3 mb-3">
                  {([
                    {
                      label: t.portal.dashboard.studentsLabel,
                      icon: <IconUsers className="svg-16" />,
                      cls: "teal",
                      counts: attendance.data.students,
                    },
                    {
                      label: t.portal.dashboard.teachersLabel,
                      icon: <IconUserCheck className="svg-16" />,
                      cls: "blue",
                      counts: attendance.data.teachers,
                    },
                    {
                      label: t.portal.dashboard.staffLabel,
                      icon: <IconBriefcase className="svg-16" />,
                      cls: "orange",
                      counts: attendance.data.staff,
                    },
                  ] as const).map((panel) => (
                    <div className="col-lg-4 col-md-6" key={panel.label}>
                      <div className="p-3 h-100" style={{ background: "#fff", border: `1px solid ${APP_BORDER}` }}>
                        <div className="d-flex align-items-center justify-content-between mb-2">
                          <div className="d-flex align-items-center gap-2">
                            <span className={`ems-stat-icon ${panel.cls}`} style={{ width: 34, height: 34, borderRadius: 8 }}>
                              {panel.icon}
                            </span>
                            <p className="mb-0 f-w-700 ems-fs-13">{panel.label}</p>
                          </div>
                          <span className={`badge ${rateCls(panel.counts.rate)}`}>
                            {panel.counts.rate}% {t.portal.dashboard.rate}
                          </span>
                        </div>
                        <div className="d-flex align-items-center gap-3">
                          <div style={{ width: 148, flex: "0 0 auto" }}>
                            <AttendanceDonut
                              height={158}
                              total={panel.counts.total}
                              segments={[
                                { label: t.portal.dashboard.present, value: panel.counts.present, color: ATT_COLORS.present },
                                { label: t.portal.dashboard.absent, value: panel.counts.absent, color: ATT_COLORS.absent },
                                { label: t.portal.dashboard.onLeave, value: panel.counts.leave, color: ATT_COLORS.leave },
                                { label: t.portal.dashboard.unmarked, value: panel.counts.unmarked, color: ATT_COLORS.unmarked },
                              ]}
                            />
                          </div>
                          <div className="flex-fill d-flex flex-column gap-1">
                            <AttLegendRow color={ATT_COLORS.present} label={t.portal.dashboard.present} value={panel.counts.present} />
                            <AttLegendRow color={ATT_COLORS.absent} label={t.portal.dashboard.absent} value={panel.counts.absent} />
                            <AttLegendRow color={ATT_COLORS.leave} label={t.portal.dashboard.onLeave} value={panel.counts.leave} />
                            <AttLegendRow color={ATT_COLORS.unmarked} label={t.portal.dashboard.unmarked} value={panel.counts.unmarked} />
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                {/* 7-day student attendance trend (ending on the selected date) */}
                <div className="p-3 mb-3" style={{ background: "#fff", border: `1px solid ${APP_BORDER}` }}>
                  <p className="mb-0 f-w-700 ems-fs-13">{t.portal.dashboard.last7Days}</p>
                  <RateTrendChart
                    height={200}
                    labels={attendance.data.trend.map((d) =>
                      new Date(d.date).toLocaleDateString(locale === "bn" ? "bn-BD" : "en-GB", {
                        weekday: "short",
                      })
                    )}
                    titles={attendance.data.trend.map((d) => formatDate(d.date, locale))}
                    values={attendance.data.trend.map((d) => d.rate)}
                    colors={attendance.data.trend.map((d) => rateBarColor(d.rate))}
                    seriesName={t.portal.dashboard.rate}
                    target={75}
                    targetLabel={t.portal.dashboard.attTarget.replace("{pct}", "75")}
                  />
                </div>

                {attendance.data.students.marked === 0 && (
                  <div className="alert alert-warning py-2 ems-fs-12">{t.portal.dashboard.noStudentAttendanceToday}</div>
                )}

                {/* Class-wise + section-wise / shift-wise + subject-wise tables */}
                <div className="row g-3 mb-3">
                  {([
                    { title: t.portal.dashboard.classWise, label: t.categories.CLASS, rows: attendance.data.students.byClass },
                    { title: t.portal.dashboard.sectionWise, label: t.categories.SECTION, rows: attendance.data.students.bySection },
                    { title: t.portal.dashboard.shiftWise, label: t.categories.SHIFT, rows: attendance.data.students.byShift },
                  ] as const).map((block) => (
                    <div className="col-lg-6" key={block.title}>
                      <h6 className="f-w-700 ems-fs-13 mb-2">{block.title}</h6>
                      <div className="table-responsive">
                        <table className="table table-hover align-middle mb-0">
                          <thead className="ems-table-head">
                            <tr>
                              <th>{block.label}</th>
                              <th className="text-center">{t.common.total}</th>
                              <th className="text-center">P</th>
                              <th className="text-center">A</th>
                              <th className="text-center">L</th>
                              <th className="text-center">{t.portal.dashboard.rate}</th>
                            </tr>
                          </thead>
                          <tbody>
                            {block.rows.map((g) => {
                              const marked = g.total - g.unmarked;
                              const rate = marked > 0 ? Math.round((g.present / marked) * 100) : null;
                              return (
                                <tr key={g.name}>
                                  <td className="f-w-600 ems-fs-12">{locale === "bn" && g.nameBn ? g.nameBn : g.name}</td>
                                  <td className="text-center ems-fs-12">{g.total}</td>
                                  <td className="text-center ems-fs-12 ems-text-teal f-w-700">{g.present}</td>
                                  <td className="text-center ems-fs-12 text-danger f-w-700">{g.absent}</td>
                                  <td className="text-center ems-fs-12 text-warning f-w-700">{g.leave}</td>
                                  <td className="text-center ems-fs-12 f-w-700">{rate === null ? "—" : `${rate}%`}</td>
                                </tr>
                              );
                            })}
                            {block.rows.length === 0 && (
                              <tr>
                                <td colSpan={6} className="text-center text-muted ems-fs-12">—</td>
                              </tr>
                            )}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  ))}

                  {/* Subject-wise (today's subject attendance records) */}
                  <div className="col-lg-6">
                    <h6 className="f-w-700 ems-fs-13 mb-2">{t.portal.dashboard.subjectWise}</h6>
                    <div className="table-responsive">
                      <table className="table table-hover align-middle mb-0">
                        <thead className="ems-table-head">
                          <tr>
                            <th>{t.categories.SUBJECT}</th>
                            <th className="text-center">{t.portal.dashboard.records}</th>
                            <th className="text-center">P</th>
                            <th className="text-center">A</th>
                            <th className="text-center">L</th>
                            <th className="text-center">{t.portal.dashboard.rate}</th>
                          </tr>
                        </thead>
                        <tbody>
                          {attendance.data.students.bySubject.map((g) => {
                            const rate = g.records > 0 ? Math.round((g.present / g.records) * 100) : null;
                            return (
                              <tr key={g.name}>
                                <td className="f-w-600 ems-fs-12">{locale === "bn" && g.nameBn ? g.nameBn : g.name}</td>
                                <td className="text-center ems-fs-12">{g.records}</td>
                                <td className="text-center ems-fs-12 ems-text-teal f-w-700">{g.present}</td>
                                <td className="text-center ems-fs-12 text-danger f-w-700">{g.absent}</td>
                                <td className="text-center ems-fs-12 text-warning f-w-700">{g.leave}</td>
                                <td className="text-center ems-fs-12 f-w-700">{rate === null ? "—" : `${rate}%`}</td>
                              </tr>
                            );
                          })}
                          {attendance.data.students.bySubject.length === 0 && (
                            <tr>
                              <td colSpan={6} className="text-center text-muted ems-fs-12">—</td>
                            </tr>
                          )}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>

                {/* Absent / leave name lists */}
                <div className="row g-3">
                  {([
                    { title: t.portal.dashboard.absentStudents, rows: attendance.data.students.absentStudents, kind: "student" },
                    { title: t.portal.dashboard.onLeaveStudents, rows: attendance.data.students.leaveStudents, kind: "student" },
                    { title: t.portal.dashboard.absentStaff, rows: attendance.data.staff.absentStaff, kind: "staff" },
                    { title: t.portal.dashboard.onLeaveStaff, rows: attendance.data.staff.onLeaveStaff, kind: "staff" },
                  ] as AttListBlock[]).map((block) => (
                    <div className="col-md-3 col-6" key={block.title}>
                      <h6 className="f-w-700 ems-fs-12 mb-2 text-muted text-uppercase">{block.title}</h6>
                      {block.rows.length === 0 ? (
                        <p className="ems-fs-12 text-muted mb-0">{t.portal.dashboard.listEmpty}</p>
                      ) : block.kind === "student" ? (
                        block.rows.map((r, i) => (
                          <div className="mb-2" key={i}>
                            <p className="mb-0 ems-fs-12 f-w-600">
                              {locale === "bn" && r.nameBn ? r.nameBn : r.name}{" "}
                              <span className="text-muted">({r.roll})</span>
                            </p>
                            <p className="mb-0 ems-fs-11 text-muted">{r.className ?? "—"}</p>
                          </div>
                        ))
                      ) : (
                        block.rows.map((r, i) => (
                          <div className="mb-2" key={i}>
                            <p className="mb-0 ems-fs-12 f-w-600">
                              {locale === "bn" && r.nameBn ? r.nameBn : r.name}{" "}
                              <span className="text-muted">({r.employeeCode})</span>
                            </p>
                            <p className="mb-0 ems-fs-11 text-muted">{r.designation}</p>
                          </div>
                        ))
                      )}
                    </div>
                  ))}
                </div>

                {/* Today's activities */}
                <div className="pt-1">
                  <h6 className="f-w-700 ems-fs-12 mb-2 text-muted text-uppercase">{t.portal.dashboard.todaysActivities}</h6>
                  {attendance.data.activities.length === 0 ? (
                    <p className="ems-fs-12 text-muted mb-0">{t.portal.dashboard.listEmpty}</p>
                  ) : (
                    <div className="d-flex flex-wrap gap-2">
                      {attendance.data.activities.map((a) => (
                        <span key={a.id} className="badge badge-secondary d-inline-flex align-items-center gap-1 ems-fs-12">
                          {a.title}
                          <span className="badge badge-primary ms-1">
                            {a.isForAll
                              ? t.portal.studentsPage.audienceAll
                              : `${a.recipientCount ?? 0} ${t.portal.studentsPage.recipientsLabel}`}
                          </span>
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              </>
            )}
          </Card>
        </div>
      </div>

      {/* ---------------- Notices + Events ---------------- */}
      <div className="row g-4 mb-2">
        <div className="col-xl-6">
          <Card
            title={t.portal.dashboard.latestNotices}
            icon={<IconBell className="svg-20" />}
            action={
              <Link
                href="/portal/notices"
                className="ems-text-teal f-w-700 text-decoration-none ems-fs-13"
              >
                {t.common.viewAll} →
              </Link>
            }
          >
            {data.recentNotices.length === 0 ? (
              <EmptyState icon={<IconBell />} title={t.portal.dashboard.noNotices} />
            ) : (
              data.recentNotices.map((n) => (
                <Link href="/portal/notices" className="ems-feed-item" key={n.id}>
                  <FeedDate iso={n.publishDate} locale={locale} />
                  <p className="mb-0 f-w-700 ems-fs-13 text-dark text-truncate">
                    {locale === "bn" && n.titleBn ? n.titleBn : n.title}
                  </p>
                </Link>
              ))
            )}
          </Card>
        </div>
        <div className="col-xl-6">
          <Card
            title={t.portal.dashboard.upcomingEvents}
            icon={<IconCalendar className="svg-20" />}
            action={
              <Link
                href="/portal/events"
                className="ems-text-teal f-w-700 text-decoration-none ems-fs-13"
              >
                {t.common.viewAll} →
              </Link>
            }
          >
            {data.upcomingEvents.length === 0 ? (
              <EmptyState icon={<IconCalendar />} title={t.portal.dashboard.noEvents} />
            ) : (
              data.upcomingEvents.map((e) => (
                <Link href="/portal/events" className="ems-feed-item" key={e.id}>
                  <FeedDate iso={e.startDate} locale={locale} />
                  <div className="min-w-0">
                    <p className="mb-0 f-w-700 ems-fs-13 text-dark text-truncate">
                      {locale === "bn" && e.titleBn ? e.titleBn : e.title}
                    </p>
                    {e.venue && (
                      <p className="mb-0 ems-fs-12 text-muted d-flex align-items-center gap-1">
                        <IconMap className="svg-14 flex-shrink-0" />
                        <span className="text-truncate">{e.venue}</span>
                      </p>
                    )}
                  </div>
                </Link>
              ))
            )}
          </Card>
        </div>
      </div>

      {/* ---------------- Support status & monitoring ---------------- */}
      <div className="row g-4 mb-2">
        <div className="col-12">
          <Card
            title={t.portal.dashboard.supportStatus}
            icon={<IconLifeBuoy className="svg-20" />}
            action={
              <Link
                href="/portal/support"
                className="ems-text-teal f-w-700 text-decoration-none ems-fs-13"
              >
                {t.common.viewAll} →
              </Link>
            }
          >
            <div className="d-flex flex-wrap gap-2 mb-3">
              {(["OPEN", "IN_PROGRESS", "RESOLVED", "CLOSED"] as const).map((s) => (
                <span key={s} className="ems-fs-13">
                  <StatusBadge status={s} label={t.status[s]} />
                  <b className="ms-2">{data.support.counts[s]}</b>
                </span>
              ))}
            </div>
            {data.support.recent.length === 0 ? (
              <EmptyState icon={<IconLifeBuoy />} title={t.portal.supportPage.noTickets} />
            ) : (
              data.support.recent.map((x) => (
                <Link href="/portal/support" className="ems-feed-item" key={x.id}>
                  <FeedDate iso={x.updatedAt} locale={locale} />
                  <p className="mb-0 f-w-700 ems-fs-13 text-dark text-truncate">
                    #{x.id} — {x.subject}
                  </p>
                  <span className="ms-auto">
                    <StatusBadge status={x.status} label={t.status[x.status as keyof typeof t.status]} />
                  </span>
                </Link>
              ))
            )}
          </Card>
        </div>
      </div>

      {/* ---------------- Recent fee collections ---------------- */}
      <div className="row g-4 mb-2">
        <div className="col-12">
          <Card
            title={t.portal.dashboard.recentCollections}
            icon={<IconCard className="svg-20" />}
            action={
              <Link
                href="/portal/fees"
                className="ems-text-teal f-w-700 text-decoration-none ems-fs-13"
              >
                {t.common.viewAll} →
              </Link>
            }
          >
            {data.fees.recent.length === 0 ? (
              <EmptyState icon={<IconCard />} title={t.portal.dashboard.noCollections} />
            ) : (
              <div className="table-responsive">
                <table className="table table-hover align-middle mb-0">
                  <thead className="ems-table-head">
                    <tr>
                      <th>{t.portal.dashboard.invoiceNo}</th>
                      <th>{t.common.students}</th>
                      <th>{t.common.method}</th>
                      <th>{t.common.date}</th>
                      <th className="text-end">{t.common.amount}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.fees.recent.map((f) => (
                      <tr key={f.id}>
                        <td>
                          <span className="ems-invoice-badge">{f.invoiceNo}</span>
                        </td>
                        <td className="f-w-600">
                          {f.studentName}
                          <span className="ems-fs-11 text-muted f-w-500"> ({f.studentRoll})</span>
                        </td>
                        <td>
                          <span className="badge badge-secondary">
                            {t.methods[f.method as keyof typeof t.methods]}
                          </span>
                        </td>
                        <td className="ems-fs-12 text-muted">{formatDate(f.paidAt, locale)}</td>
                        <td className="text-end f-w-800 text-success">{formatBDT(f.amount, locale)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </Card>
        </div>
      </div>

      {/* ---------------- Academic setup + Quick actions ---------------- */}
      <div className="row g-4">
        <div className="col-xl-8">
          <Card
            title={t.portal.dashboard.academicSetup}
            icon={<IconAcademic className="svg-20" />}
            action={
              <span className="ems-fs-12 f-w-600 text-muted">
                {data.totalSelected} {t.portal.dashboard.selectedItems}
              </span>
            }
          >
            <div className="row g-3">
              {ACADEMIC_CATEGORIES.map((cat) => (
                <div className="col-6 col-md-3 col-xl" key={cat}>
                  <Link
                    href="/portal/academic"
                    className="d-block text-center p-3 rounded ems-bg-soft text-decoration-none"
                  >
                    <h4 className="f-w-800 mb-0">{data.academicCounts[cat] ?? 0}</h4>
                    <p className="mb-0 ems-fs-12 f-w-600 text-muted">
                      {t.categories[cat as keyof typeof t.categories]}
                    </p>
                  </Link>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <div className="col-xl-4">
          <Card title={t.portal.dashboard.quickActions}>
            <div className="d-flex flex-column gap-2">
              <Link
                href="/portal/students"
                className="media align-items-center gap-3 p-3 rounded"
                style={{ background: "rgba(36,105,92,0.08)" }}
              >
                <span className="ems-stat-icon teal"><IconUsers /></span>
                <div className="media-body">
                  <h6 className="mb-0 f-w-700 ems-fs-13">{t.portal.dashboard.manageStudents}</h6>
                  <p className="mb-0 ems-fs-11 text-muted">
                    {data.counts.students} {t.common.students}
                  </p>
                </div>
              </Link>
              <Link
                href="/portal/admissions"
                className="media align-items-center gap-3 p-3 rounded"
                style={{ background: "rgba(64,169,118,0.09)" }}
              >
                <span className="ems-stat-icon sky"><IconUserCheck /></span>
                <div className="media-body">
                  <h6 className="mb-0 f-w-700 ems-fs-13">{t.portal.dashboard.viewAdmissions}</h6>
                  <p className="mb-0 ems-fs-11 text-muted">
                    {data.counts.pendingAdmissions} {t.portal.dashboard.pendingAdmissions}
                  </p>
                </div>
              </Link>
              <Link
                href="/portal/packages"
                className="media align-items-center gap-3 p-3 rounded"
                style={{ background: "rgba(34,126,230,0.08)" }}
              >
                <span className="ems-stat-icon blue"><IconPackage /></span>
                <h6 className="mb-0 f-w-700 ems-fs-13">{t.portal.dashboard.browsePackages}</h6>
              </Link>
              <Link
                href="/portal/academic"
                className="media align-items-center gap-3 p-3 rounded"
                style={{ background: "rgba(122,96,214,0.09)" }}
              >
                <span className="ems-stat-icon purple"><IconAcademic /></span>
                <div className="media-body">
                  <h6 className="mb-0 f-w-700 ems-fs-13">{t.portal.dashboard.manageAcademic}</h6>
                  <p className="mb-0 ems-fs-11 text-muted">
                    {data.totalSelected} {t.portal.dashboard.selectedItems}
                  </p>
                </div>
              </Link>
              <Link
                href="/portal/billing"
                className="media align-items-center gap-3 p-3 rounded"
                style={{ background: "rgba(247,154,27,0.1)" }}
              >
                <span className="ems-stat-icon orange"><IconCard /></span>
                <h6 className="mb-0 f-w-700 ems-fs-13">{t.portal.dashboard.viewInvoices}</h6>
              </Link>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}
