"use client";

import * as React from "react";
import {
  History,
  Filter,
  RefreshCw,
  FileText,
  User,
  Clock,
  MapPin,
  ChevronDown,
  ChevronRight,
  Image as ImageIcon,
  ArrowRight,
  AlertTriangle,
  CheckCircle2,
  Trash2,
  Search,
  ExternalLink,
  Code2,
} from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { formatLocationDisplay } from "@/lib/admin/location-formatter";
import type { AuditLocation } from "@/lib/admin/db";

interface ContentActivityItem {
  id: string;
  actorId: string;
  actorName: string;
  actorEmail: string;
  actorRole: string;
  postId: string | null;
  postTitle: string | null;
  postSlug: string | null;
  action: string;
  details: Record<string, any>;
  location?: AuditLocation | null;
  timestamp: string;
}

function getActionBadgeStyle(action: string) {
  if (action.includes("DELETE") || action.includes("ARCHIVE")) {
    return "bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-950/40 dark:text-rose-300 dark:border-rose-900/50";
  }
  if (action.includes("PUBLISH") || action.includes("UPDATE_LIVE")) {
    return "bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-300 dark:border-emerald-900/50";
  }
  if (action.includes("BANNER") || action.includes("MEDIA_REPLACE")) {
    return "bg-purple-50 text-purple-700 border-purple-200 dark:bg-purple-950/40 dark:text-purple-300 dark:border-purple-900/50";
  }
  if (action.startsWith("MEDIA_")) {
    return "bg-cyan-50 text-cyan-700 border-cyan-200 dark:bg-cyan-950/40 dark:text-cyan-300 dark:border-cyan-900/50";
  }
  if (action.startsWith("CATEGORY_")) {
    return "bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-900/50";
  }
  if (action.startsWith("REDIRECT_")) {
    return "bg-indigo-50 text-indigo-700 border-indigo-200 dark:bg-indigo-950/40 dark:text-indigo-300 dark:border-indigo-900/50";
  }
  return "bg-neutral-100 text-neutral-800 border-neutral-200 dark:bg-neutral-800 dark:text-neutral-200 dark:border-neutral-700";
}

function getActionHumanLabel(action: string) {
  const map: Record<string, string> = {
    POST_CREATED: "Article Created",
    POST_EDITED: "Article Draft Saved",
    POST_PUBLISHED: "Article Published",
    POST_UNPUBLISHED: "Article Unpublished",
    POST_SCHEDULED: "Article Scheduled",
    POST_ARCHIVED: "Article Archived",
    POST_RESTORED: "Article Restored",
    POST_DELETED: "Article Deleted",
    POST_BANNER_CHANGED: "Banner Image Changed",
    POST_UPDATED_LIVE: "Live Article Updated",
    POST_DUPLICATED: "Article Duplicated",
    TITLE_CHANGED: "Title Changed",
    SLUG_CHANGED: "Slug & URL Changed",
    SEO_METADATA_UPDATED: "SEO Metadata Updated",
    MEDIA_UPLOADED: "Media Asset Uploaded",
    MEDIA_REPLACED: "Media Asset Replaced",
    MEDIA_DELETED: "Media Asset Deleted",
    MEDIA_METADATA_UPDATED: "Media Metadata Updated",
    MEDIA_ATTACHED: "Media Attached to Article",
    MEDIA_DETACHED: "Media Detached",
    MEDIA_BULK_UPLOADED: "Bulk Media Uploaded",
    MEDIA_BULK_DELETED: "Bulk Media Deleted",
    MEDIA_CHANGED: "Media Changed",
    CATEGORY_CREATED: "Category Created",
    CATEGORY_UPDATED: "Category Updated",
    CATEGORY_DELETED: "Category Deleted",
    REDIRECT_CREATED: "Redirect Rule Created",
    REDIRECT_DELETED: "Redirect Rule Deleted",
    REVISION_RESTORED: "Revision Restored",
    PUSH_NOTIFICATION_SENT: "Push Notification Sent",
  };
  return map[action] || action.replace(/_/g, " ");
}

export default function ContentActivityPage() {
  const [logs, setLogs] = React.useState<ContentActivityItem[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [categoryFilter, setCategoryFilter] = React.useState("ALL");
  const [searchQuery, setSearchQuery] = React.useState("");
  const [error, setError] = React.useState<string | null>(null);
  const [expandedIds, setExpandedIds] = React.useState<Set<string>>(new Set());

  const fetchLogs = React.useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const params = new URLSearchParams();
      if (categoryFilter !== "ALL") params.set("action", categoryFilter);
      params.set("limit", "100");

      const res = await fetch(`/api/admin/activity?${params.toString()}`);
      if (res.status === 403) {
        setError("Access Denied: You do not have permission to view content activity.");
        return;
      }
      if (!res.ok) throw new Error("Failed to load content activity");
      const data = await res.json();
      setLogs(data.logs || []);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setLoading(false);
    }
  }, [categoryFilter]);

  React.useEffect(() => {
    fetchLogs();
  }, [fetchLogs]);

  const toggleExpand = (id: string) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const filteredLogs = React.useMemo(() => {
    if (!searchQuery.trim()) return logs;
    const q = searchQuery.toLowerCase();
    return logs.filter((log) => {
      return (
        log.action.toLowerCase().includes(q) ||
        (log.postTitle && log.postTitle.toLowerCase().includes(q)) ||
        (log.postSlug && log.postSlug.toLowerCase().includes(q)) ||
        log.actorName.toLowerCase().includes(q) ||
        log.actorEmail.toLowerCase().includes(q) ||
        (log.location?.city && log.location.city.toLowerCase().includes(q)) ||
        (log.location?.address && log.location.address.toLowerCase().includes(q)) ||
        (log.details?.assetName && String(log.details.assetName).toLowerCase().includes(q)) ||
        (log.details?.filename && String(log.details.filename).toLowerCase().includes(q)) ||
        (log.details?.categoryName && String(log.details.categoryName).toLowerCase().includes(q))
      );
    });
  }, [logs, searchQuery]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <div className="flex items-center gap-2">
            <h1 className="font-bold text-xl tracking-tight text-neutral-900 dark:text-white">
              Content Activity History
            </h1>
            <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-[9px] font-bold text-emerald-800 uppercase tracking-wider dark:bg-emerald-950/60 dark:text-emerald-300">
              Authoritative Audit Log
            </span>
          </div>
          <p className="mt-0.5 text-xs text-neutral-500">
            Chronological audit of all editorial operations: article drafting, revisions, media uploads, replacements, deletions, and publishing.
          </p>
        </div>

        <button
          type="button"
          onClick={fetchLogs}
          disabled={loading}
          className="flex h-8 items-center gap-1.5 rounded-lg border border-neutral-200 px-3 text-xs font-medium text-neutral-700 hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-300 dark:hover:bg-neutral-800 transition shadow-xs"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
          <span>Refresh History</span>
        </button>
      </div>

      {error && (
        <div className="rounded-xl border border-red-200 bg-red-50 p-4 text-xs text-red-700 dark:border-red-900/50 dark:bg-red-950/50 dark:text-red-300">
          {error}
        </div>
      )}

      {/* Filter & Search Bar */}
      <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 rounded-xl border border-neutral-200 bg-white p-3 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
        <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2.5">
          <div className="flex items-center gap-2">
            <Filter className="h-3.5 w-3.5 text-neutral-400 shrink-0" />
            <Select value={categoryFilter} onValueChange={setCategoryFilter}>
              <SelectTrigger className="h-8 w-44 text-xs">
                <SelectValue placeholder="All Categories" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">All Editorial Actions</SelectItem>
                <SelectItem value="MEDIA">Media Operations</SelectItem>
                <SelectItem value="POSTS">Article Operations</SelectItem>
                <SelectItem value="CATEGORIES">Category Operations</SelectItem>
                <SelectItem value="REDIRECTS">Redirect Operations</SelectItem>
                <SelectItem value="MEDIA_UPLOADED">Media Uploaded</SelectItem>
                <SelectItem value="MEDIA_REPLACED">Media Replaced</SelectItem>
                <SelectItem value="MEDIA_DELETED">Media Deleted</SelectItem>
                <SelectItem value="MEDIA_BULK_UPLOADED">Bulk Media Uploaded</SelectItem>
                <SelectItem value="MEDIA_BULK_DELETED">Bulk Media Deleted</SelectItem>
                <SelectItem value="POST_BANNER_CHANGED">Banner Changed</SelectItem>
                <SelectItem value="POST_PUBLISHED">Post Published</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="relative flex-1 sm:w-64">
            <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-neutral-400" />
            <Input
              placeholder="Search by subject, actor, asset..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="h-8 pl-8 text-xs"
            />
          </div>
        </div>

        <span className="text-xs text-neutral-400">
          Showing {filteredLogs.length} event{filteredLogs.length === 1 ? "" : "s"}
        </span>
      </div>

      {/* Activity Table */}
      <div className="overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead>
              <tr className="border-b border-neutral-200 bg-neutral-50/75 text-[11px] font-semibold text-neutral-500 uppercase tracking-wider dark:border-neutral-800 dark:bg-neutral-950/50">
                <th className="w-8 px-3 py-3 text-center"></th>
                <th className="px-4 py-3">Timestamp</th>
                <th className="px-4 py-3">Editorial Action</th>
                <th className="px-4 py-3">Subject / Resource</th>
                <th className="px-4 py-3">Author / Editor</th>
                <th className="px-4 py-3">Role</th>
                <th className="px-4 py-3">Location</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-200 dark:divide-neutral-800">
              {loading ? (
                <tr>
                  <td colSpan={7} className="px-5 py-12 text-center text-xs text-neutral-400">
                    <div className="flex items-center justify-center gap-2">
                      <RefreshCw className="h-4 w-4 animate-spin text-neutral-400" />
                      <span>Loading editorial activity history...</span>
                    </div>
                  </td>
                </tr>
              ) : filteredLogs.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-5 py-12 text-center text-xs text-neutral-400">
                    No editorial activity found matching your criteria.
                  </td>
                </tr>
              ) : (
                filteredLogs.map((log) => {
                  const isExpanded = expandedIds.has(log.id);
                  const locationText = formatLocationDisplay(log.location);
                  const hasLocation =
                    log.location?.status === "available" ||
                    (log.location?.latitude != null && log.location?.longitude != null) ||
                    (log.location?.address && log.location.address.trim().length > 0);

                  return (
                    <React.Fragment key={log.id}>
                      <tr
                        onClick={() => toggleExpand(log.id)}
                        className={`cursor-pointer transition hover:bg-neutral-50/80 dark:hover:bg-neutral-800/40 ${
                          isExpanded ? "bg-neutral-50/60 dark:bg-neutral-800/20" : ""
                        }`}
                      >
                        {/* Toggle Arrow */}
                        <td className="px-3 py-3.5 text-center text-neutral-400">
                          {isExpanded ? (
                            <ChevronDown className="h-4 w-4 mx-auto text-neutral-600 dark:text-neutral-300" />
                          ) : (
                            <ChevronRight className="h-4 w-4 mx-auto text-neutral-400" />
                          )}
                        </td>

                        {/* Timestamp */}
                        <td suppressHydrationWarning className="px-4 py-3.5 font-mono text-[11px] text-neutral-500 whitespace-nowrap">
                          {new Date(log.timestamp).toLocaleString("en-US", {
                            month: "short",
                            day: "numeric",
                            hour: "2-digit",
                            minute: "2-digit",
                          })}
                        </td>

                        {/* Action Badge */}
                        <td className="px-4 py-3.5">
                          <span
                            className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider whitespace-nowrap ${getActionBadgeStyle(
                              log.action
                            )}`}
                          >
                            {getActionHumanLabel(log.action)}
                          </span>
                        </td>

                        {/* Subject */}
                        <td className="px-4 py-3.5 max-w-xs">
                          {log.postTitle ? (
                            <div>
                              <span className="font-semibold text-neutral-900 dark:text-white truncate block">
                                {log.postTitle}
                              </span>
                              {log.postSlug && (
                                <span className="font-mono text-[10px] text-neutral-400 truncate block">
                                  /{log.postSlug}
                                </span>
                              )}
                            </div>
                          ) : log.details?.assetName || log.details?.filename || log.details?.newAsset?.name ? (
                            <div className="flex items-center gap-1.5 font-medium text-neutral-800 dark:text-neutral-200 truncate">
                              <ImageIcon className="h-3 w-3 text-cyan-600 shrink-0" />
                              <span className="truncate">
                                {log.details.assetName || log.details.filename || log.details.newAsset?.name}
                              </span>
                            </div>
                          ) : log.details?.categoryName ? (
                            <span className="font-semibold text-neutral-900 dark:text-white">
                              Category: {log.details.categoryName}
                            </span>
                          ) : log.details?.source && log.details?.destination ? (
                            <span className="font-mono text-[11px] text-neutral-700 dark:text-neutral-300">
                              {log.details.source} → {log.details.destination}
                            </span>
                          ) : (
                            <span className="text-neutral-400">Content Management</span>
                          )}
                        </td>

                        {/* Author */}
                        <td className="px-4 py-3.5 whitespace-nowrap">
                          <div className="font-semibold text-neutral-900 dark:text-white">
                            {log.actorName}
                          </div>
                          <div className="text-[10px] text-neutral-400 truncate max-w-[140px]">
                            {log.actorEmail}
                          </div>
                        </td>

                        {/* Role */}
                        <td className="px-4 py-3.5 whitespace-nowrap">
                          <span className="text-neutral-600 dark:text-neutral-400 text-[11px]">
                            {(log.actorRole || "—").replace(/_/g, " ")}
                          </span>
                        </td>

                        {/* Location */}
                        <td className="px-4 py-3.5 whitespace-nowrap">
                          {hasLocation ? (
                            <span
                              className="inline-flex items-center gap-1 rounded-md bg-cyan-50 px-2 py-0.5 text-[10px] font-medium text-cyan-800 border border-cyan-200 dark:border-cyan-900/40 dark:bg-cyan-950/40 dark:text-cyan-300"
                              title={
                                log.location?.latitude != null && log.location?.longitude != null
                                  ? `Coordinates: ${log.location.latitude}, ${log.location.longitude}`
                                  : undefined
                              }
                            >
                              <MapPin className="h-3 w-3 text-cyan-600 shrink-0" />
                              <span className="truncate max-w-[160px]">{locationText}</span>
                            </span>
                          ) : log.location?.status === "denied" ? (
                            <span className="inline-flex items-center gap-1 text-[10px] text-neutral-400">
                              Location access denied
                            </span>
                          ) : (
                            <span className="text-[10px] text-neutral-400">Location unavailable</span>
                          )}
                        </td>
                      </tr>

                      {/* Expandable Details Row */}
                      {isExpanded && (
                        <tr className="bg-neutral-50/75 dark:bg-neutral-950/50">
                          <td colSpan={7} className="p-4 border-b border-neutral-200 dark:border-neutral-800">
                            <div className="rounded-xl border border-neutral-200 bg-white p-4 space-y-4 text-xs dark:border-neutral-800 dark:bg-neutral-900 shadow-xs">
                              {/* Top Bar: Action Summary */}
                              <div className="flex flex-wrap items-center justify-between gap-2 pb-3 border-b border-neutral-100 dark:border-neutral-800">
                                <div className="flex items-center gap-2">
                                  <span
                                    className={`inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider ${getActionBadgeStyle(
                                      log.action
                                    )}`}
                                  >
                                    {getActionHumanLabel(log.action)}
                                  </span>
                                  <span className="font-semibold text-neutral-800 dark:text-neutral-200">
                                    {log.postTitle || log.details?.assetName || log.details?.filename || "Operational Event"}
                                  </span>
                                </div>
                                <span suppressHydrationWarning className="font-mono text-[11px] text-neutral-400">
                                  {new Date(log.timestamp).toLocaleString("en-US", {
                                    dateStyle: "full",
                                    timeStyle: "medium",
                                  })}
                                </span>
                              </div>

                              {/* Two-Column Grid: Business Context & Location / Actor Context */}
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {/* Left Column: Detailed Business Action Data */}
                                <div className="space-y-2 rounded-lg border border-neutral-100 bg-neutral-50/50 p-3 dark:border-neutral-800 dark:bg-neutral-950/40">
                                  <h4 className="font-semibold text-neutral-700 dark:text-neutral-300 flex items-center gap-1.5 text-[11px]">
                                    <FileText className="h-3.5 w-3.5 text-cyan-600" />
                                    <span>Operation Specifics</span>
                                  </h4>

                                  {/* Media Replacement Details */}
                                  {log.action === "MEDIA_REPLACED" && (
                                    <div className="space-y-1.5 text-[11px]">
                                      <div className="grid grid-cols-2 gap-2">
                                        <div className="rounded border border-neutral-200 p-2 dark:border-neutral-750 bg-white dark:bg-neutral-900">
                                          <span className="text-neutral-400 block text-[10px] uppercase font-bold">
                                            Previous Asset
                                          </span>
                                          <p className="font-medium truncate text-neutral-700 dark:text-neutral-300">
                                            {log.details.oldAsset?.name || "Previous file"}
                                          </p>
                                          {log.details.oldAsset?.publicId && (
                                            <code className="text-[9px] text-neutral-400 block truncate">
                                              {log.details.oldAsset.publicId}
                                            </code>
                                          )}
                                        </div>
                                        <div className="rounded border border-cyan-200 p-2 dark:border-cyan-900/60 bg-cyan-50/40 dark:bg-cyan-950/20">
                                          <span className="text-cyan-700 dark:text-cyan-300 block text-[10px] uppercase font-bold">
                                            New Asset
                                          </span>
                                          <p className="font-medium truncate text-cyan-900 dark:text-cyan-100">
                                            {log.details.newAsset?.name || "Updated file"}
                                          </p>
                                          {log.details.newAsset?.publicId && (
                                            <code className="text-[9px] text-cyan-700/70 block truncate">
                                              {log.details.newAsset.publicId}
                                            </code>
                                          )}
                                        </div>
                                      </div>
                                    </div>
                                  )}

                                  {/* Post Banner Changed Details */}
                                  {log.action === "POST_BANNER_CHANGED" && (
                                    <div className="space-y-1.5 text-[11px]">
                                      <div className="grid grid-cols-2 gap-2">
                                        <div className="rounded border border-neutral-200 p-2 dark:border-neutral-750 bg-white dark:bg-neutral-900">
                                          <span className="text-neutral-400 block text-[10px] uppercase font-bold">
                                            Old Banner
                                          </span>
                                          <p className="font-mono text-[10px] text-neutral-600 dark:text-neutral-300 truncate">
                                            {log.details.previousBanner || "None"}
                                          </p>
                                        </div>
                                        <div className="rounded border border-purple-200 p-2 dark:border-purple-900/60 bg-purple-50/40 dark:bg-purple-950/20">
                                          <span className="text-purple-700 dark:text-purple-300 block text-[10px] uppercase font-bold">
                                            New Banner
                                          </span>
                                          <p className="font-mono text-[10px] text-purple-900 dark:text-purple-100 truncate">
                                            {log.details.newBanner || "Removed"}
                                          </p>
                                        </div>
                                      </div>
                                    </div>
                                  )}

                                  {/* Media Bulk Operations */}
                                  {log.action === "MEDIA_BULK_DELETED" && (
                                    <div className="space-y-1 text-[11px]">
                                      <p className="font-semibold text-neutral-800 dark:text-neutral-200">
                                        Bulk Delete Summary: {log.details.deletedCount} deleted,{" "}
                                        {log.details.skippedCount} skipped (in use)
                                      </p>
                                      {log.details.deletedNames?.length > 0 && (
                                        <div>
                                          <span className="text-neutral-400 text-[10px]">Deleted assets:</span>
                                          <p className="truncate text-neutral-600 dark:text-neutral-400">
                                            {log.details.deletedNames.join(", ")}
                                          </p>
                                        </div>
                                      )}
                                      {log.details.skippedNames?.length > 0 && (
                                        <div>
                                          <span className="text-amber-600 text-[10px] font-bold">
                                            Protected from deletion (used in articles):
                                          </span>
                                          <p className="truncate text-amber-700 dark:text-amber-300">
                                            {log.details.skippedNames.join(", ")}
                                          </p>
                                        </div>
                                      )}
                                    </div>
                                  )}

                                  {/* Bulk Uploads */}
                                  {log.action === "MEDIA_BULK_UPLOADED" && (
                                    <div className="space-y-1 text-[11px]">
                                      <p className="font-semibold text-neutral-800 dark:text-neutral-200">
                                        Bulk Upload: {log.details.count} files uploaded
                                      </p>
                                      {log.details.filenames && (
                                        <p className="truncate text-neutral-600 dark:text-neutral-400">
                                          {Array.isArray(log.details.filenames)
                                            ? log.details.filenames.join(", ")
                                            : String(log.details.filenames)}
                                        </p>
                                      )}
                                    </div>
                                  )}

                                  {/* Single Media Upload / Delete */}
                                  {(log.action === "MEDIA_UPLOADED" || log.action === "MEDIA_DELETED") && (
                                    <div className="grid grid-cols-2 gap-2 text-[11px] text-neutral-600 dark:text-neutral-400">
                                      <div>
                                        <strong>Asset:</strong> {log.details.assetName || log.details.filename || "—"}
                                      </div>
                                      <div>
                                        <strong>Format:</strong> {log.details.format || log.details.mimeType || "WebP"}
                                      </div>
                                      {log.details.size && (
                                        <div>
                                          <strong>Size:</strong> {(log.details.size / 1024).toFixed(1)} KB
                                        </div>
                                      )}
                                      {log.details.publicId && (
                                        <div className="col-span-2">
                                          <strong>Public ID:</strong>{" "}
                                          <code className="text-[10px] bg-neutral-100 dark:bg-neutral-800 px-1 rounded">
                                            {log.details.publicId}
                                          </code>
                                        </div>
                                      )}
                                    </div>
                                  )}

                                  {/* Generic details summary for other actions */}
                                  {!["MEDIA_REPLACED", "POST_BANNER_CHANGED", "MEDIA_BULK_DELETED", "MEDIA_BULK_UPLOADED", "MEDIA_UPLOADED", "MEDIA_DELETED"].includes(
                                    log.action
                                  ) && (
                                    <div className="space-y-1 text-[11px] text-neutral-600 dark:text-neutral-400">
                                      {log.details.note && <p>{log.details.note}</p>}
                                      {log.details.change && <p>{log.details.change}</p>}
                                      {log.details.version && <p>Document Version: v{log.details.version}</p>}
                                      {log.details.redirectCreated && (
                                        <p className="font-mono text-[10px]">
                                          Redirect: {log.details.redirectCreated}
                                        </p>
                                      )}
                                    </div>
                                  )}
                                </div>

                                {/* Right Column: Actor & Location Telemetry */}
                                <div className="space-y-2 rounded-lg border border-neutral-100 bg-neutral-50/50 p-3 dark:border-neutral-800 dark:bg-neutral-950/40">
                                  <h4 className="font-semibold text-neutral-700 dark:text-neutral-300 flex items-center gap-1.5 text-[11px]">
                                    <MapPin className="h-3.5 w-3.5 text-cyan-600" />
                                    <span>Actor & Physical Location</span>
                                  </h4>

                                  <div className="space-y-1 text-[11px] text-neutral-600 dark:text-neutral-400">
                                    <div>
                                      <strong>Administrator:</strong> {log.actorName} ({log.actorEmail})
                                    </div>
                                    <div>
                                      <strong>Role:</strong> {(log.actorRole || "—").replace(/_/g, " ")}
                                    </div>
                                    <div className="pt-1 border-t border-neutral-200/60 dark:border-neutral-800">
                                      <strong>Location:</strong>{" "}
                                      <span className="font-medium text-neutral-900 dark:text-white">
                                        {locationText}
                                      </span>
                                    </div>

                                    {log.location?.latitude != null && log.location?.longitude != null && (
                                      <div>
                                        <strong>Coordinates:</strong>{" "}
                                        <span className="font-mono text-[10px]">
                                          {log.location.latitude}, {log.location.longitude}
                                        </span>
                                      </div>
                                    )}

                                    {log.location?.source && (
                                      <div>
                                        <strong>Location Source:</strong> {log.location.source}
                                      </div>
                                    )}

                                    {log.location?.status && (
                                      <div>
                                        <strong>Status:</strong>{" "}
                                        <span className="uppercase text-[9px] font-bold px-1.5 py-0.5 rounded bg-neutral-200 dark:bg-neutral-800">
                                          {log.location.status}
                                        </span>
                                      </div>
                                    )}
                                  </div>
                                </div>
                              </div>

                              {/* Technical Details JSON Drawer (Optional Forensic Section) */}
                              <details className="text-[11px] text-neutral-500">
                                <summary className="cursor-pointer font-medium hover:text-neutral-700 dark:hover:text-neutral-300 flex items-center gap-1 select-none">
                                  <Code2 className="h-3 w-3" />
                                  <span>View Raw Forensic JSON Payload</span>
                                </summary>
                                <pre className="mt-2 overflow-x-auto rounded-lg bg-neutral-900 p-3 font-mono text-[10px] text-neutral-300 dark:bg-black">
                                  {JSON.stringify(
                                    {
                                      id: log.id,
                                      action: log.action,
                                      actor: {
                                        id: log.actorId,
                                        name: log.actorName,
                                        email: log.actorEmail,
                                        role: log.actorRole,
                                      },
                                      location: log.location,
                                      details: log.details,
                                      timestamp: log.timestamp,
                                    },
                                    null,
                                    2
                                  )}
                                </pre>
                              </details>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
