"use client";

import { useState, type ComponentType, type ReactNode, type SVGProps } from "react";
import { cn, timeAgo } from "@/lib/utils";
import {
  Panel,
  Badge,
  IconChip,
  KpiCard,
  ProgressBar,
  TONE_BAR,
  type Tone,
} from "./parts";
import { AreaChart, BarChart, Donut, Heatmap, QrCode } from "./charts";
import type {
  Kpi,
  Trend,
  Vehicle,
  ContactRequest,
  RequestStatus,
  ActivityEvent,
  ActivityType,
  VehiclePerf,
  QrPerformance,
  AreaInsight,
  EmergencyStats,
  NotificationItem,
  NotificationCategory,
  Subscription,
  Gamification,
  ScanCard,
  LiveAlert,
  AccountStatus,
  QuickAction,
} from "@/lib/dashboard-data";
import { quotaLabel, usagePercent } from "@/types/subscription";
import {
  QrIcon,
  PhoneIcon,
  CarIcon,
  MotorcycleIcon,
  MessageIcon,
  AlertIcon,
  TrendingUpIcon,
  MapPinIcon,
  UsersIcon,
  CrownIcon,
  BellIcon,
  CreditCardIcon,
  ShieldCheckIcon,
  ShieldIcon,
  CheckIcon,
  ScanIcon,
  SparklesIcon,
  UserCircleIcon,
  ActivityIcon,
  PlusIcon,
  StarIcon,
  CloseIcon,
  ShareIcon,
  DownloadIcon,
} from "@/app/components/icons";
import type { EmergencyContactListItem } from "@/services/fetch-emergency-contacts";

type IconType = ComponentType<SVGProps<SVGSVGElement>>;
type ActionFn = (action: string) => void;

/* ---------- shared maps / helpers ---------- */

const vehicleIcon = (type: string): IconType =>
  type.toLowerCase() === "bike" ? MotorcycleIcon : CarIcon;

const REQ_TONE: Record<RequestStatus, Tone> = {
  resolved: "success",
  pending: "warning",
  missed: "danger",
};
const REQ_LABEL: Record<RequestStatus, string> = {
  resolved: "Resolved",
  pending: "Pending",
  missed: "Missed",
};

const ACT_META: Record<ActivityType, { icon: IconType; tone: Tone }> = {
  scan: { icon: QrIcon, tone: "success" },
  request: { icon: PhoneIcon, tone: "brand" },
  call: { icon: PhoneIcon, tone: "success" },
  message: { icon: MessageIcon, tone: "brand" },
  emergency: { icon: AlertIcon, tone: "danger" },
  vehicle: { icon: CarIcon, tone: "warning" },
};

const NOTIF_META: Record<NotificationCategory, { icon: IconType; tone: Tone }> = {
  vehicle: { icon: CarIcon, tone: "warning" },
  request: { icon: PhoneIcon, tone: "brand" },
  system: { icon: BellIcon, tone: "neutral" },
  billing: { icon: CreditCardIcon, tone: "success" },
};

const ICON_BY_NAME: Record<string, IconType> = {
  user: UserCircleIcon,
  owner: UserCircleIcon,
  scan: ScanIcon,
  qr: QrIcon,
  phone: PhoneIcon,
  call: PhoneIcon,
  message: MessageIcon,
  chat: MessageIcon,
  alert: AlertIcon,
  warning: AlertIcon,
  car: CarIcon,
  vehicle: CarIcon,
  bell: BellIcon,
  shield: ShieldIcon,
  map: MapPinIcon,
  location: MapPinIcon,
};
const iconFromName = (name?: string): IconType =>
  (name && ICON_BY_NAME[name]) || ActivityIcon;

const priorityTone = (p: string): Tone =>
  p === "high" ? "danger" : p === "medium" ? "warning" : "brand";

const ALERT_BG: Record<Tone, string> = {
  danger: "border-danger/30 bg-danger/10",
  warning: "border-warning/30 bg-warning/10",
  brand: "border-brand/30 bg-brand/10",
  success: "border-success/30 bg-success/10",
  neutral: "border-white/10 bg-white/5",
};

/* ---------- small controls ---------- */

function Segmented({
  value,
  onChange,
  options,
}: {
  value: string;
  onChange: (v: string) => void;
  options: { v: string; l: string }[];
}) {
  return (
    <div className="flex rounded-lg border border-white/10 bg-white/5 p-0.5">
      {options.map((o) => (
        <button
          key={o.v}
          type="button"
          onClick={() => onChange(o.v)}
          className={cn(
            "rounded-md px-2.5 py-1 text-xs font-medium transition",
            value === o.v ? "bg-brand text-white" : "text-white/55 hover:text-white",
          )}
        >
          {o.l}
        </button>
      ))}
    </div>
  );
}

/* ---------- live-API panels ---------- */

export function WelcomeBanner({
  gamification,
  scanCard,
  isPro,
  onAction,
}: {
  gamification: Gamification;
  scanCard: ScanCard;
  isPro: boolean;
  onAction: ActionFn;
}) {
  const xpPct = gamification.nextLevelXp
    ? Math.min(100, Math.round((gamification.xp / gamification.nextLevelXp) * 100))
    : 0;

  return (
    <div
      className="relative overflow-hidden rounded-2xl p-6 sm:p-7"
      style={{ background: "linear-gradient(120deg,#15203f,#1f2a52 55%,#2f3f7a)" }}
    >
      <span className="pointer-events-none absolute -right-10 -top-12 h-48 w-48 rounded-full bg-brand/25 blur-3xl" />
      <span className="pointer-events-none absolute -bottom-16 left-1/3 h-44 w-44 rounded-full bg-electric/20 blur-3xl" />
      <div className="relative flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
        <div className="min-w-0">
          <p className="text-sm text-white/70">{gamification.greeting}</p>
          <h1 className="mt-0.5 text-2xl font-bold text-white">
            {gamification.welcomeText}
          </h1>
          <div className="mt-3 flex flex-wrap items-center gap-2">
            <Badge tone="brand">
              <SparklesIcon className="h-3 w-3" />
              Level {gamification.level} · {gamification.title}
            </Badge>
            {isPro && (
              <Badge tone="warning">
                <CrownIcon className="h-3 w-3" />
                Premium
              </Badge>
            )}
          </div>
          <div className="mt-3 max-w-xs">
            <div className="mb-1 flex justify-between text-[11px] text-white/55">
              <span>XP</span>
              <span>
                {gamification.xp} / {gamification.nextLevelXp}
              </span>
            </div>
            <ProgressBar value={xpPct} />
          </div>
        </div>

        <button
          type="button"
          onClick={() => onAction(scanCard.action)}
          className="flex items-center gap-4 rounded-2xl bg-white/12 p-4 text-left backdrop-blur transition hover:bg-white/20"
        >
          <span className="grid h-12 w-12 shrink-0 place-items-center rounded-xl bg-white/15 text-white">
            <ScanIcon className="h-6 w-6" />
          </span>
          <span>
            <span className="block font-semibold text-white">{scanCard.title}</span>
            <span className="block text-xs text-white/70">{scanCard.subtitle}</span>
          </span>
        </button>
      </div>
    </div>
  );
}

export function LiveAlertBanner({
  alert,
  onAction,
}: {
  alert: LiveAlert | null;
  onAction: ActionFn;
}) {
  if (!alert) return null;
  const tone = priorityTone(alert.priority);
  return (
    <div className={cn("flex items-center gap-3 rounded-2xl border p-4", ALERT_BG[tone])}>
      <span className="relative grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-danger/15 text-danger">
        <AlertIcon className="h-5 w-5" />
        {alert.isLive && (
          <span className="absolute -right-0.5 -top-0.5 h-2.5 w-2.5 animate-pulse rounded-full bg-danger ring-2 ring-bg" />
        )}
      </span>
      <div className="min-w-0 flex-1">
        <p className="text-sm font-semibold text-white">{alert.message}</p>
        <p className="text-xs text-white/45">
          {alert.isLive ? "Live • " : ""}
          {timeAgo(alert.createdAt)} · {alert.priority} priority
        </p>
      </div>
      <button
        type="button"
        onClick={() => onAction("view-notifications")}
        className="shrink-0 rounded-full bg-white/10 px-3.5 py-2 text-xs font-semibold text-white transition hover:bg-white/20"
      >
        View
      </button>
    </div>
  );
}

export function AccountStatusPanel({ status }: { status: AccountStatus }) {
  const ok = status.state === "ok";
  const warn = status.state === "warning";
  return (
    <Panel title="Account Status">
      <div className="flex items-center gap-4">
        <span
          className={cn(
            "grid h-12 w-12 shrink-0 place-items-center rounded-full text-white",
            ok ? "bg-success" : warn ? "bg-warning" : "bg-danger",
          )}
        >
          {ok ? <CheckIcon className="h-6 w-6" /> : <AlertIcon className="h-6 w-6" />}
        </span>
        <div className="min-w-0 flex-1">
          <h3 className="font-semibold text-white">{status.title}</h3>
          <p className="text-sm text-white/55">{status.subtitle}</p>
        </div>
        <ShieldCheckIcon
          className={cn("h-7 w-7 shrink-0", ok ? "text-success/70" : "text-warning/70")}
        />
      </div>
    </Panel>
  );
}

export function QuickActionsPanel({
  actions,
  onAction,
}: {
  actions: QuickAction[];
  onAction: ActionFn;
}) {
  return (
    <Panel title="Quick Actions">
      {actions.length > 0 ? (
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
          {actions.map((a) => (
            <button
              key={a.id}
              type="button"
              onClick={() => onAction(a.action)}
              className="card-hover flex flex-col items-center gap-2 rounded-2xl border border-white/8 bg-white/[0.03] px-2 py-4"
            >
              <IconChip icon={iconFromName(a.icon)} tone="brand" />
              <span className="text-center text-[11px] font-medium text-white/75">
                {a.label}
              </span>
            </button>
          ))}
        </div>
      ) : (
        <p className="text-sm text-white/45">No quick actions available.</p>
      )}
    </Panel>
  );
}

/* ---------- KPI row ---------- */

const KPI_ICON: Record<string, IconType> = {
  alerts: AlertIcon,
  scans: QrIcon,
  trust: ShieldCheckIcon,
  level: SparklesIcon,
  requests: PhoneIcon,
  vehicles: CarIcon,
  response: TrendingUpIcon,
};
const KPI_TONE: Record<string, Tone> = {
  alerts: "danger",
  scans: "brand",
  trust: "success",
  level: "warning",
  requests: "success",
  vehicles: "warning",
  response: "brand",
};

export function KpiCards({ kpis }: { kpis: Kpi[] }) {
  return (
    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
      {kpis.map((k) => (
        <KpiCard
          key={k.key}
          label={k.label}
          value={k.value}
          delta={k.delta}
          deltaPositive={k.deltaPositive}
          numericDelta={k.numericDelta}
          icon={KPI_ICON[k.key] ?? QrIcon}
          tone={KPI_TONE[k.key] ?? "brand"}
        />
      ))}
    </div>
  );
}

/* ---------- analytics / lists ---------- */

export function ScanAnalyticsPanel({ trend }: { trend: Trend[] }) {
  const [range, setRange] = useState("month");
  const [type, setType] = useState("area");
  const data = range === "week" ? trend.slice(-7) : trend;

  const today = trend[trend.length - 1]?.value ?? 0;
  const week = trend.slice(-7).reduce((a, b) => a + b.value, 0);
  const month = trend.reduce((a, b) => a + b.value, 0);
  const year = month * 12;
  const fmt = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
  const metrics = [
    { label: "Today", value: fmt(today) },
    { label: "Week", value: fmt(week) },
    { label: "Month", value: fmt(month) },
    { label: "Year", value: fmt(year) },
  ];

  return (
    <Panel
      title="QR Scan Trend"
      subtitle={range === "week" ? "Last 7 days" : "Last 30 days"}
      action={
        <div className="flex flex-wrap items-center gap-2">
          <Segmented
            value={range}
            onChange={setRange}
            options={[
              { v: "week", l: "Week" },
              { v: "month", l: "Month" },
            ]}
          />
          <Segmented
            value={type}
            onChange={setType}
            options={[
              { v: "area", l: "Area" },
              { v: "bar", l: "Bar" },
            ]}
          />
        </div>
      }
    >
      <div className="h-52">
        {type === "area" ? (
          <AreaChart data={data} gradientId="scan-trend" className="h-full" />
        ) : (
          <BarChart data={data} className="h-full" />
        )}
      </div>
      <div className="mt-4 grid grid-cols-4 gap-3 border-t border-white/5 pt-4">
        {metrics.map((m) => (
          <div key={m.label} className="text-center">
            <p className="text-lg font-bold text-white">{m.value}</p>
            <p className="text-[11px] text-white/45">{m.label}</p>
          </div>
        ))}
      </div>
    </Panel>
  );
}

export function VehicleOverviewPanel({
  vehicles,
  onAction,
  action,
}: {
  vehicles: Vehicle[];
  onAction: ActionFn;
  action?: ReactNode;
}) {
  const [qrVehicle, setQrVehicle] = useState<Vehicle | null>(null);

  return (
    <Panel title="Vehicle Overview" subtitle={`${vehicles.length} registered`} action={action}>
      <ul className="space-y-2.5">
        {vehicles.map((v) => (
          <li
            key={v.id}
            className="flex items-center gap-3 rounded-xl border border-white/5 bg-white/[0.02] p-3"
          >
            <IconChip icon={vehicleIcon(v.type)} tone={v.plan === "premium" ? "brand" : "neutral"} />
            <div className="min-w-0 flex-1">
              <div className="flex items-center gap-2">
                <p className="truncate text-sm font-semibold text-white">{v.number}</p>
                <span className="text-[11px] uppercase text-white/40">{v.type}</span>
              </div>
              <div className="mt-1 flex items-center gap-2 text-xs text-white/45">
                <span className="inline-flex items-center gap-1">
                  <span
                    className={cn("h-1.5 w-1.5 rounded-full", v.qrActive ? "bg-success" : "bg-white/30")}
                  />
                  {v.qrActive ? "QR Active" : "QR Off"}
                </span>
                <span>•</span>
                <span>{v.scans} scans</span>
                <span className="hidden sm:inline">•</span>
                <span className="hidden sm:inline">{v.lastActivity}</span>
              </div>
            </div>
            <button
              type="button"
              onClick={() => setQrVehicle(v)}
              className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-white/12 bg-white/5 px-3.5 py-1.5 text-xs font-semibold text-white/80 transition hover:border-brand/40 hover:text-white"
            >
              <QrIcon className="h-4 w-4" />
              Show QR
            </button>
          </li>
        ))}
      </ul>

      {qrVehicle && (
        <VehicleQrModal
          vehicle={qrVehicle}
          onAction={onAction}
          onClose={() => setQrVehicle(null)}
        />
      )}
    </Panel>
  );
}

// Renders the QR for a vehicle. The image is fetched from the backend via the
// same-origin proxy (GET /api/vehicle/qr-image/:qrCodeId) — the browser sends
// the httpOnly auth cookie automatically and the route forwards it. While the
// bytes load we show a spinner; if the fetch fails (or there's no qrCodeId, e.g.
// placeholder data) we fall back to the locally-drawn QR so the modal is never
// empty.
function VehicleQrImage({ vehicle }: { vehicle: Vehicle }) {
  const [status, setStatus] = useState<"loading" | "loaded" | "error">(
    vehicle.qrCodeId ? "loading" : "error",
  );

  if (!vehicle.qrCodeId || status === "error") {
    return <QrCode value={vehicle.number} className="h-44 w-44" />;
  }

  const src = `/api/vehicle/qr-image/${encodeURIComponent(vehicle.qrCodeId)}`;

  return (
    <div className="relative grid h-44 w-44 place-items-center">
      {status === "loading" && (
        <span className="absolute h-7 w-7 animate-spin rounded-full border-2 border-black/15 border-t-brand" />
      )}
      {/* eslint-disable-next-line @next/next/no-img-element -- backend-served QR
          image with a dynamic, non-optimizable URL; next/image adds no value. */}
      <img
        src={src}
        alt={`QR code for ${vehicle.number}`}
        className={cn(
          "h-44 w-44 object-contain transition-opacity",
          status === "loaded" ? "opacity-100" : "opacity-0",
        )}
        onLoad={() => setStatus("loaded")}
        onError={() => setStatus("error")}
      />
    </div>
  );
}

function VehicleQrModal({
  vehicle,
  onAction,
  onClose,
}: {
  vehicle: Vehicle;
  onAction: ActionFn;
  onClose: () => void;
}) {
  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="vehicle-qr-title"
      className="fixed inset-0 z-50 flex items-end justify-center p-4 sm:items-center"
    >
      <button
        type="button"
        aria-label="Close"
        onClick={onClose}
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
      />

      <div className="glass animate-toast-in relative w-full max-w-sm rounded-3xl">
        <div className="flex items-center justify-between gap-3 border-b border-white/8 px-6 py-5">
          <div className="flex items-center gap-3">
            <span className="grid h-10 w-10 place-items-center rounded-xl bg-brand/12 text-brand">
              <QrIcon className="h-5 w-5" />
            </span>
            <div>
              <h2 id="vehicle-qr-title" className="text-base font-bold text-white">
                {vehicle.number}
              </h2>
              <p className="text-xs text-white/50">QR code for this vehicle</p>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            aria-label="Close"
            className="grid h-9 w-9 place-items-center rounded-lg text-white/50 transition hover:bg-white/5 hover:text-white"
          >
            <CloseIcon className="h-5 w-5" />
          </button>
        </div>

        <div className="flex flex-col items-center p-6">
          <div className="rounded-2xl bg-white p-4 shadow-lg">
            <VehicleQrImage vehicle={vehicle} />
          </div>
          <div className="mt-4">
            <Badge tone={vehicle.qrActive ? "success" : "neutral"}>
              {vehicle.qrActive ? "QR Active" : "Inactive"}
            </Badge>
          </div>
          <div className="mt-5 flex w-full gap-2">
            <button
              type="button"
              onClick={() => onAction("share")}
              className="btn-primary flex-1 text-xs"
            >
              <ShareIcon className="h-4 w-4" />
              Share
            </button>
            <button
              type="button"
              onClick={() => onAction("download")}
              className="btn-ghost flex-1 text-xs"
            >
              <DownloadIcon className="h-4 w-4" />
              Download
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export function RecentRequestsPanel({
  requests,
  action,
}: {
  requests: ContactRequest[];
  action?: ReactNode;
}) {
  return (
    <Panel title="Recent Requests" subtitle="Contact attempts" action={action} bodyClassName="p-0">
      <div className="overflow-x-auto">
        <table className="w-full min-w-[460px] text-sm">
          <thead>
            <tr className="text-left text-[11px] uppercase tracking-wide text-white/35">
              <th className="px-5 py-2.5 font-medium">Request</th>
              <th className="px-3 py-2.5 font-medium">Vehicle</th>
              <th className="px-3 py-2.5 font-medium">Time</th>
              <th className="px-5 py-2.5 text-right font-medium">Status</th>
            </tr>
          </thead>
          <tbody>
            {requests.map((r) => (
              <tr key={r.id} className="border-t border-white/5">
                <td className="whitespace-nowrap px-5 py-3 font-medium text-white">{r.type}</td>
                <td className="whitespace-nowrap px-3 py-3 text-white/60">{r.vehicle}</td>
                <td className="whitespace-nowrap px-3 py-3 text-white/45">{r.time}</td>
                <td className="px-5 py-3 text-right">
                  <Badge tone={REQ_TONE[r.status]}>{REQ_LABEL[r.status]}</Badge>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Panel>
  );
}

export function ActivityFeedPanel({
  activity,
  action,
}: {
  activity: ActivityEvent[];
  action?: ReactNode;
}) {
  return (
    <Panel title="Recent Activity" subtitle="Real-time timeline" action={action}>
      <ul className="space-y-1">
        {activity.map((e, i) => {
          const meta = ACT_META[e.type] ?? { icon: ActivityIcon, tone: "brand" as Tone };
          const last = i === activity.length - 1;
          return (
            <li key={e.id} className="flex gap-3">
              <div className="flex flex-col items-center">
                <IconChip icon={meta.icon} tone={meta.tone} className="h-9 w-9" />
                {!last && <span className="my-1 w-px flex-1 bg-white/10" />}
              </div>
              <div className="pb-4">
                <p className="text-sm font-medium text-white/90">{e.title}</p>
                <p className="mt-0.5 text-xs text-white/40">
                  {e.time}
                  {e.vehicle ? ` • ${e.vehicle}` : ""}
                </p>
              </div>
            </li>
          );
        })}
      </ul>
    </Panel>
  );
}

export function VehiclePerformanceTable({
  rows,
  action,
}: {
  rows: VehiclePerf[];
  action?: ReactNode;
}) {
  return (
    <Panel title="Vehicle Performance" subtitle="Per-vehicle insights" action={action} bodyClassName="p-0">
      <div className="overflow-x-auto">
        <table className="w-full min-w-[480px] text-sm">
          <thead>
            <tr className="text-left text-[11px] uppercase tracking-wide text-white/35">
              <th className="px-5 py-2.5 font-medium">Vehicle</th>
              <th className="px-3 py-2.5 font-medium">Scans</th>
              <th className="px-3 py-2.5 font-medium">Requests</th>
              <th className="px-5 py-2.5 font-medium">Conversion</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => (
              <tr key={r.id} className="border-t border-white/5">
                <td className="whitespace-nowrap px-5 py-3 font-medium text-white">{r.vehicle}</td>
                <td className="px-3 py-3 text-white/70">{r.scans}</td>
                <td className="px-3 py-3 text-white/70">{r.requests}</td>
                <td className="px-5 py-3">
                  <div className="flex items-center gap-2">
                    <ProgressBar value={r.conversion} className="w-20" />
                    <span className="text-xs font-semibold text-white/70">{r.conversion}%</span>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Panel>
  );
}

export function QrPerformancePanel({ qr }: { qr: QrPerformance }) {
  const totalScans = qr.uniqueScans + qr.repeatScans;
  const metrics: { label: string; value: number; tone: Tone }[] = [
    { label: "Unique Scans", value: qr.uniqueScans, tone: "brand" },
    { label: "Repeat Scans", value: qr.repeatScans, tone: "warning" },
    { label: "Successful Contacts", value: qr.successfulContacts, tone: "success" },
    { label: "Missed Contacts", value: qr.missedContacts, tone: "danger" },
  ];
  return (
    <Panel title="QR Performance" subtitle="Scans vs Contacts">
      <div className="flex flex-col items-center gap-5 sm:flex-row">
        <Donut value={qr.successfulContacts} total={totalScans} label="Contacted" color="#10B981" />
        <ul className="grid w-full grid-cols-2 gap-3">
          {metrics.map((m) => (
            <li key={m.label} className="rounded-xl bg-white/[0.03] p-3">
              <div className="flex items-center gap-2">
                <span className={cn("h-2 w-2 rounded-full", TONE_BAR[m.tone])} />
                <span className="text-xs text-white/50">{m.label}</span>
              </div>
              <p className="mt-1 text-lg font-bold text-white">{m.value}</p>
            </li>
          ))}
        </ul>
      </div>
    </Panel>
  );
}

export function EmergencyMonitoringPanel({ emergency }: { emergency: EmergencyStats }) {
  const stats: { label: string; value: number; icon: IconType; tone: Tone }[] = [
    { label: "Emergency Contacts", value: emergency.contactsConfigured, icon: UsersIcon, tone: "brand" },
    { label: "SOS Events", value: emergency.sosEvents, icon: AlertIcon, tone: emergency.sosEvents ? "danger" : "success" },
    { label: "Emergency Calls", value: emergency.emergencyCalls, icon: PhoneIcon, tone: "warning" },
  ];
  return (
    <Panel title="Emergency Monitoring" subtitle="Safety & SOS">
      <div className="grid grid-cols-3 gap-3">
        {stats.map((s) => (
          <div key={s.label} className="rounded-xl bg-white/[0.03] p-3 text-center">
            <IconChip icon={s.icon} tone={s.tone} className="mx-auto" />
            <p className="mt-2 text-xl font-bold text-white">{s.value}</p>
            <p className="text-[11px] text-white/45">{s.label}</p>
          </div>
        ))}
      </div>
    </Panel>
  );
}

function AddContactButton({
  onAction,
  label,
}: {
  onAction: ActionFn;
  label: string;
}) {
  return (
    <button
      type="button"
      onClick={() => onAction("add-contact")}
      className="inline-flex items-center gap-1.5 rounded-lg bg-brand/15 px-3 py-1.5 text-xs font-semibold text-brand transition hover:bg-brand/25"
    >
      <PlusIcon className="h-3.5 w-3.5" />
      {label}
    </button>
  );
}

export function EmergencyContactsPanel({
  contacts,
  isLoading,
  isError,
  onRetry,
  onAction,
}: {
  contacts: EmergencyContactListItem[];
  isLoading?: boolean;
  isError?: boolean;
  onRetry?: () => void;
  onAction: ActionFn;
}) {
  const subtitle = isLoading
    ? "Loading…"
    : isError
      ? "Couldn't load"
      : `${contacts.length} configured`;

  return (
    <Panel
      title="Emergency Contacts"
      subtitle={subtitle}
      action={<AddContactButton onAction={onAction} label="Add contact" />}
      bodyClassName="p-0"
    >
      {isLoading ? (
        <ul className="divide-y divide-white/5">
          {Array.from({ length: 3 }).map((_, i) => (
            <li key={i} className="flex items-center gap-3 px-5 py-3.5">
              <span className="h-9 w-9 shrink-0 animate-pulse rounded-full bg-white/5" />
              <div className="flex-1 space-y-2">
                <div className="h-3 w-1/3 animate-pulse rounded bg-white/5" />
                <div className="h-2.5 w-1/2 animate-pulse rounded bg-white/5" />
              </div>
            </li>
          ))}
        </ul>
      ) : isError ? (
        <div className="flex flex-col items-center gap-3 px-5 py-8 text-center">
          <p className="text-sm text-white/45">
            Couldn&apos;t load your emergency contacts.
          </p>
          {onRetry && (
            <button
              type="button"
              onClick={onRetry}
              className="inline-flex items-center gap-1.5 rounded-lg bg-white/5 px-3 py-1.5 text-xs font-semibold text-white/80 transition hover:bg-white/10"
            >
              Try again
            </button>
          )}
        </div>
      ) : contacts.length > 0 ? (
        <ul className="divide-y divide-white/5">
          {contacts.map((c, i) => (
            <li key={c.id} className="flex items-center gap-3 px-5 py-3.5">
              <span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-brand/15 text-sm font-bold text-brand">
                {i + 1}
              </span>
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <p className="truncate text-sm font-medium text-white">{c.name}</p>
                  {c.isPrimary && (
                    <Badge tone="warning">
                      <StarIcon className="h-3 w-3" />
                      Primary
                    </Badge>
                  )}
                </div>
                <p className="text-xs text-white/40">
                  {c.relation} • {c.phone}
                </p>
              </div>
              <span
                title={c.notifyOnSos ? "Notified on SOS" : "Not notified on SOS"}
                className={cn(
                  "grid h-8 w-8 shrink-0 place-items-center rounded-lg",
                  c.notifyOnSos ? "bg-danger/12 text-danger" : "bg-white/5 text-white/30",
                )}
              >
                <AlertIcon className="h-4 w-4" />
              </span>
            </li>
          ))}
        </ul>
      ) : (
        <div className="flex flex-col items-center gap-3 px-5 py-8 text-center">
          <p className="text-sm text-white/45">No emergency contacts configured yet.</p>
          <AddContactButton onAction={onAction} label="Add your first contact" />
        </div>
      )}
    </Panel>
  );
}

export function NotificationsPanel({
  notifications,
  action,
}: {
  notifications: NotificationItem[];
  action?: ReactNode;
}) {
  const unread = notifications.filter((n) => n.unread).length;
  return (
    <Panel title="Notifications" subtitle={`${unread} unread`} action={action} bodyClassName="p-0">
      {notifications.length > 0 ? (
        <ul className="divide-y divide-white/5">
          {notifications.map((n) => {
            const meta = NOTIF_META[n.category];
            return (
              <li key={n.id} className="flex items-start gap-3 px-5 py-3.5">
                <IconChip icon={meta.icon} tone={meta.tone} className="h-9 w-9" />
                <div className="min-w-0 flex-1">
                  <p className={cn("text-sm", n.unread ? "font-medium text-white" : "text-white/80")}>
                    {n.message}
                  </p>
                  <p className="mt-0.5 text-xs capitalize text-white/40">
                    {n.category} • {n.time}
                  </p>
                </div>
                {n.unread && <span className="mt-1.5 h-2 w-2 shrink-0 rounded-full bg-brand" />}
              </li>
            );
          })}
        </ul>
      ) : (
        <p className="px-5 py-6 text-sm text-white/45">You&apos;re all caught up.</p>
      )}
    </Panel>
  );
}

export function SubscriptionPanel({
  subscription,
  onAction,
}: {
  subscription: Subscription;
  onAction: ActionFn;
}) {
  // Plans are admin-defined, so the tier is whatever the API reports — never a
  // hard-coded slug comparison (which silently read every plan as "Free").
  const planName = subscription.planName ?? titleCasePlan(subscription.plan);
  const isPaid = (subscription.price ?? 0) > 0;
  const vehiclePct = usagePercent(
    subscription.vehiclesUsed,
    subscription.vehiclesTotal,
  );
  const stickerPct = usagePercent(
    subscription.qrStickersUsed ?? 0,
    subscription.qrStickersTotal ?? 0,
  );

  return (
    <Panel
      title="Subscription"
      action={
        <Badge tone={isPaid ? "brand" : "neutral"}>
          {isPaid && <CrownIcon className="h-3 w-3" />}
          {planName}
        </Badge>
      }
    >
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-xs text-white/45">Plan</p>
            <p className="text-base font-semibold text-white">{planName}</p>
          </div>
          <div className="text-right">
            <p className="text-xs text-white/45">
              {subscription.renewalDate ? "Renews" : "Renewal Date"}
            </p>
            <p className="text-sm font-medium text-white">
              {formatRenewal(subscription.renewalDate)}
            </p>
          </div>
        </div>

        <div>
          <div className="mb-1.5 flex justify-between text-xs">
            <span className="text-white/55">Vehicles</span>
            <span className="text-white/70">
              {subscription.vehiclesUsed} / {quotaLabel(subscription.vehiclesTotal)}
            </span>
          </div>
          <ProgressBar value={vehiclePct} />
        </div>

        {subscription.qrStickersTotal !== undefined && (
          <div>
            <div className="mb-1.5 flex justify-between text-xs">
              <span className="text-white/55">QR Stickers</span>
              <span className="text-white/70">
                {subscription.qrStickersUsed ?? 0} /{" "}
                {quotaLabel(subscription.qrStickersTotal)}
              </span>
            </div>
            <ProgressBar value={stickerPct} />
          </div>
        )}

        <div>
          <div className="mb-1.5 flex justify-between text-xs">
            <span className="text-white/55">Storage</span>
            <span className="text-white/70">{subscription.storagePercent}%</span>
          </div>
          <ProgressBar
            value={subscription.storagePercent}
            tone={subscription.storagePercent > 85 ? "warning" : "success"}
          />
        </div>

        <button
          type="button"
          onClick={() => onAction(isPaid ? "manage-subscription" : "upgrade")}
          className="btn-ghost w-full text-sm"
        >
          {isPaid ? "Manage Subscription" : "See Plans"}
        </button>
      </div>
    </Panel>
  );
}

/** `fleet-50` → `Fleet 50`, for a subscription with no snapshotted name. */
function titleCasePlan(slug: string): string {
  return slug
    .split(/[-_]/)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");
}

/** ISO date from the API → a short readable date; "—" when it never renews. */
function formatRenewal(iso: string | null): string {
  if (!iso) return "—";
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return iso;
  return date.toLocaleDateString("en-IN", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}
