import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  Box,
  Button,
  Header,
  Icon,
  IconButton,
  Icons,
  Scroll,
  Spinner,
  Text,
  Tooltip,
  TooltipProvider,
  color,
  config,
} from 'folds';
import { EventType, MatrixClient, MatrixEvent, MsgType, Room } from 'matrix-js-sdk';
import { IEncryptedFile, IImageInfo, IThumbnailContent } from '../../../types/matrix/common';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { decryptFile, downloadEncryptedMedia, mxcUrlToHttp } from '../../utils/matrix';
import { ContainerColor } from '../../styles/ContainerColor.css';

type GalleryTab = 'image' | 'video' | 'file';

const TAB_LABELS: Record<GalleryTab, string> = {
  image: 'Images',
  video: 'Videos',
  file: 'Files',
};

const TAB_MSGTYPES: Record<GalleryTab, MsgType> = {
  image: MsgType.Image,
  video: MsgType.Video,
  file: MsgType.File,
};

// ── Decrypt hook ──────────────────────────────────────────────────────────────

type DecryptState = { status: 'loading' } | { status: 'ok'; url: string } | { status: 'error' };

function useDecryptedMediaUrl(
  mx: MatrixClient,
  mxcUrl: string | undefined,
  encInfo: IEncryptedFile | undefined,
  useAuthentication: boolean,
  mimeType?: string,
): DecryptState {
  const [state, setState] = useState<DecryptState>({ status: 'loading' });
  const prevBlobUrl = useRef<string | null>(null);

  useEffect(() => {
    if (!mxcUrl) {
      setState({ status: 'error' });
      return;
    }
    let cancelled = false;
    setState({ status: 'loading' });

    const run = async () => {
      const httpUrl = mxcUrlToHttp(mx, mxcUrl, useAuthentication);
      if (!httpUrl) throw new Error('bad url');
      if (encInfo) {
        const blob = await downloadEncryptedMedia(httpUrl, (buf) =>
          decryptFile(buf, mimeType ?? 'application/octet-stream', encInfo),
        );
        const blobUrl = URL.createObjectURL(blob);
        if (cancelled) {
          URL.revokeObjectURL(blobUrl);
          return;
        }
        if (prevBlobUrl.current) URL.revokeObjectURL(prevBlobUrl.current);
        prevBlobUrl.current = blobUrl;
        setState({ status: 'ok', url: blobUrl });
      } else {
        setState({ status: 'ok', url: httpUrl });
      }
    };

    run().catch(() => {
      if (!cancelled) setState({ status: 'error' });
    });

    return () => {
      cancelled = true;
    };
  }, [mx, mxcUrl, encInfo, useAuthentication, mimeType]);

  useEffect(
    () => () => {
      if (prevBlobUrl.current) URL.revokeObjectURL(prevBlobUrl.current);
    },
    [],
  );

  return state;
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function formatRelativeDate(ts: number): string {
  const diff = Date.now() - ts;
  const mins = Math.floor(diff / 60000);
  if (mins < 2) return 'Just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(diff / 3600000);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(diff / 86400000);
  if (days < 7) return `${days}d ago`;
  return new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}

function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / 1048576).toFixed(1)} MB`;
}

function monthLabel(ts: number): string {
  return new Date(ts).toLocaleDateString(undefined, { month: 'long', year: 'numeric' });
}

function getSenderName(room: Room, userId: string): string {
  return room.getMember(userId)?.name ?? userId.split(':')[0]?.slice(1) ?? userId;
}

// ── Lightbox ──────────────────────────────────────────────────────────────────

type LightboxItem = {
  mxcUrl: string;
  encInfo?: IEncryptedFile;
  mimeType?: string;
  msgtype: MsgType.Image | MsgType.Video;
  body: string;
  sender: string;
  ts: number;
};

function LightboxMedia({
  item,
  useAuthentication,
}: {
  item: LightboxItem;
  useAuthentication: boolean;
}) {
  const mx = useMatrixClient();
  const media = useDecryptedMediaUrl(
    mx,
    item.mxcUrl,
    item.encInfo,
    useAuthentication,
    item.mimeType,
  );

  return (
    <Box
      direction="Column"
      alignItems="Center"
      justifyContent="Center"
      style={{ height: '100%', gap: config.space.S200 }}
    >
      {media.status === 'loading' && (
        <Box direction="Column" alignItems="Center" gap="200">
          <Spinner size="600" />
          <Text size="T300" priority="300">
            {item.encInfo ? 'Decrypting…' : 'Loading…'}
          </Text>
        </Box>
      )}
      {media.status === 'error' && (
        <Box direction="Column" alignItems="Center" gap="200">
          <Icon src={Icons.Warning} size="600" />
          <Text size="T300" priority="300">
            Failed to load
          </Text>
        </Box>
      )}
      {media.status === 'ok' &&
        (item.msgtype === MsgType.Video ? (
          // eslint-disable-next-line jsx-a11y/media-has-caption
          <video
            src={media.url}
            controls
            autoPlay
            style={{
              maxWidth: '100%',
              maxHeight: 'calc(100vh - 120px)',
              borderRadius: config.radii.R300,
              display: 'block',
              background: '#000',
            }}
          />
        ) : (
          <img
            src={media.url}
            alt={item.body}
            style={{
              maxWidth: '100%',
              maxHeight: 'calc(100vh - 120px)',
              objectFit: 'contain',
              borderRadius: config.radii.R300,
              display: 'block',
            }}
          />
        ))}
    </Box>
  );
}

function Lightbox({
  items,
  initialIndex,
  useAuthentication,
  onClose,
}: {
  items: LightboxItem[];
  initialIndex: number;
  useAuthentication: boolean;
  onClose: () => void;
}) {
  const [index, setIndex] = useState(initialIndex);

  const prev = useCallback(() => setIndex((i) => Math.max(0, i - 1)), []);
  const next = useCallback(
    () => setIndex((i) => Math.min(items.length - 1, i + 1)),
    [items.length],
  );
  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'ArrowLeft') prev();
      else if (e.key === 'ArrowRight') next();
      else if (e.key === 'Escape') onClose();
    },
    [prev, next, onClose],
  );

  const item = items[index];
  if (!item) return null;

  const dateStr = new Date(item.ts).toLocaleDateString(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });

  return (
    // eslint-disable-next-line jsx-a11y/no-static-element-interactions
    <div
      role="dialog"
      aria-modal
      aria-label="Media viewer"
      onKeyDown={handleKeyDown}
      tabIndex={-1}
      style={{
        position: 'fixed',
        inset: 0,
        zIndex: 1000,
        background: 'rgba(0,0,0,0.92)',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/* Header bar */}
      <Box
        alignItems="Center"
        gap="200"
        style={{
          padding: `${config.space.S200} ${config.space.S300}`,
          borderBottom: '1px solid rgba(255,255,255,0.08)',
          flexShrink: 0,
        }}
      >
        <Box grow="Yes" direction="Column" style={{ overflow: 'hidden' }}>
          <Text size="T400" truncate style={{ color: '#fff', fontWeight: 500 }}>
            {item.body || (item.msgtype === MsgType.Video ? 'Video' : 'Image')}
          </Text>
          <Text size="T200" style={{ color: 'rgba(255,255,255,0.5)' }}>
            {item.sender} · {dateStr}
          </Text>
        </Box>
        <Text size="T200" style={{ color: 'rgba(255,255,255,0.4)', flexShrink: 0 }}>
          {index + 1} / {items.length}
        </Text>
        <TooltipProvider
          position="Bottom"
          align="End"
          offset={4}
          tooltip={
            <Tooltip>
              <Text>Close</Text>
            </Tooltip>
          }
        >
          {(ref) => (
            <IconButton ref={ref} variant="Surface" aria-label="Close" onClick={onClose}>
              <Icon src={Icons.Cross} />
            </IconButton>
          )}
        </TooltipProvider>
      </Box>

      {/* Media area with nav arrows */}
      <Box
        grow="Yes"
        alignItems="Center"
        justifyContent="Center"
        style={{ overflow: 'hidden', padding: config.space.S400 }}
      >
        {index > 0 && (
          <IconButton
            variant="Surface"
            aria-label="Previous"
            onClick={prev}
            style={{ flexShrink: 0, marginRight: config.space.S200 }}
          >
            <Icon src={Icons.ArrowLeft} />
          </IconButton>
        )}
        <Box
          grow="Yes"
          alignItems="Center"
          justifyContent="Center"
          style={{ overflow: 'hidden', height: '100%' }}
        >
          <LightboxMedia
            key={`${item.mxcUrl}-${item.ts}`}
            item={item}
            useAuthentication={useAuthentication}
          />
        </Box>
        {index < items.length - 1 && (
          <IconButton
            variant="Surface"
            aria-label="Next"
            onClick={next}
            style={{ flexShrink: 0, marginLeft: config.space.S200 }}
          >
            <Icon src={Icons.ArrowRight} />
          </IconButton>
        )}
      </Box>
    </div>
  );
}

// ── Gallery tile ──────────────────────────────────────────────────────────────

function GalleryTile({
  mxcUrl,
  encInfo,
  mimeType,
  isVideo,
  body,
  sender,
  ts,
  useAuthentication,
  onClick,
}: {
  mxcUrl: string;
  encInfo?: IEncryptedFile;
  mimeType?: string;
  isVideo: boolean;
  body: string;
  sender: string;
  ts: number;
  useAuthentication: boolean;
  onClick: () => void;
}) {
  const mx = useMatrixClient();
  const media = useDecryptedMediaUrl(mx, mxcUrl, encInfo, useAuthentication, mimeType);
  const [hovered, setHovered] = useState(false);
  const relDate = formatRelativeDate(ts);

  return (
    <button
      type="button"
      aria-label={body || (isVideo ? 'Video' : 'Image')}
      onClick={onClick}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        position: 'relative',
        aspectRatio: '1',
        overflow: 'hidden',
        borderRadius: config.radii.R300,
        background: color.SurfaceVariant.Container,
        border: `1px solid ${hovered ? color.Primary.Main : color.SurfaceVariant.ContainerLine}`,
        cursor: 'pointer',
        padding: 0,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        transition: 'border-color 0.15s',
      }}
    >
      {media.status === 'loading' && <Spinner size="200" />}
      {media.status === 'error' && (
        <Box
          direction="Column"
          alignItems="Center"
          gap="100"
          style={{ padding: config.space.S100 }}
        >
          <Icon src={isVideo ? Icons.Play : Icons.Photo} size="300" />
          <Text
            size="T200"
            truncate
            style={{ maxWidth: '100%', textAlign: 'center', opacity: 0.5 }}
          >
            {body}
          </Text>
        </Box>
      )}
      {media.status === 'ok' && (
        <img
          src={media.url}
          alt={body}
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
        />
      )}

      {/* Video play badge */}
      {isVideo && media.status === 'ok' && (
        <div
          style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: 28,
            height: 28,
            borderRadius: '50%',
            background: 'rgba(0,0,0,0.6)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            pointerEvents: 'none',
          }}
        >
          <Icon src={Icons.Play} size="200" />
        </div>
      )}

      {/* Hover overlay */}
      {hovered && media.status === 'ok' && (
        <div
          style={{
            position: 'absolute',
            inset: 0,
            background: 'linear-gradient(to top, rgba(0,0,0,0.72) 0%, transparent 55%)',
            pointerEvents: 'none',
          }}
        >
          <div
            style={{
              position: 'absolute',
              bottom: 0,
              left: 0,
              right: 0,
              padding: `${config.space.S100} ${config.space.S200}`,
            }}
          >
            <Text size="T200" truncate style={{ color: '#fff', display: 'block', lineHeight: 1.3 }}>
              {sender}
            </Text>
            <Text size="T200" style={{ color: 'rgba(255,255,255,0.65)', opacity: 0.8 }}>
              {relDate}
            </Text>
          </div>
        </div>
      )}
    </button>
  );
}

// ── Month separator ───────────────────────────────────────────────────────────

function MonthSeparator({ label }: { label: string }) {
  return (
    <Box
      alignItems="Center"
      gap="200"
      style={{ padding: `${config.space.S100} 0`, gridColumn: '1 / -1' }}
    >
      <div style={{ flex: 1, height: 1, background: color.Surface.ContainerLine }} />
      <Text size="T200" priority="300" style={{ flexShrink: 0, whiteSpace: 'nowrap' }}>
        {label}
      </Text>
      <div style={{ flex: 1, height: 1, background: color.Surface.ContainerLine }} />
    </Box>
  );
}

// ── Tab button ────────────────────────────────────────────────────────────────

function TabButton({
  label,
  active,
  onClick,
}: {
  label: string;
  active: boolean;
  onClick: () => void;
}) {
  return (
    <Button
      size="300"
      variant={active ? 'Primary' : 'Secondary'}
      fill={active ? 'Soft' : 'None'}
      radii="300"
      onClick={onClick}
    >
      <Text size="B300">{label}</Text>
    </Button>
  );
}

// ── Main component ────────────────────────────────────────────────────────────

type MediaGalleryProps = {
  room: Room;
  onClose: () => void;
};

export function MediaGallery({ room, onClose }: MediaGalleryProps) {
  const mx = useMatrixClient();
  const useAuthentication = useMediaAuthentication();

  const [tab, setTab] = useState<GalleryTab>('image');
  const [loading, setLoading] = useState(false);
  const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
  const [canLoadMore, setCanLoadMore] = useState(true);
  const [loadError, setLoadError] = useState(false);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
  const sentinelRef = useRef<HTMLDivElement>(null);

  const handleTabChange = useCallback((t: GalleryTab) => {
    setTab(t);
    setLightboxIndex(null); // stale index would open wrong item in new tab's lightboxItems
  }, []);

  const msgtype = TAB_MSGTYPES[tab];

  const getFilteredEvents = useCallback(
    (): MatrixEvent[] =>
      room
        .getLiveTimeline()
        .getEvents()
        .filter((ev) => {
          if (ev.isRedacted()) return false;
          const c = ev.getContent();
          return ev.getType() === EventType.RoomMessage && c.msgtype === msgtype;
        })
        .slice()
        .reverse(),
    [room, msgtype],
  );

  const [events, setEvents] = useState<MatrixEvent[]>(() => getFilteredEvents());

  useEffect(() => {
    setEvents(getFilteredEvents());
    setCanLoadMore(true);
    setHasLoadedOnce(false);
    setLoadError(false);
  }, [getFilteredEvents]);

  const handleLoadMore = useCallback(async () => {
    if (loading || !canLoadMore) return;
    setLoading(true);
    setLoadError(false);
    try {
      const hasMore = await mx.paginateEventTimeline(room.getLiveTimeline(), {
        backwards: true,
        limit: 100,
      });
      setEvents(getFilteredEvents());
      setCanLoadMore(hasMore);
      setHasLoadedOnce(true);
    } catch {
      // Stop auto-retry: the sentinel would keep firing on every render otherwise.
      // The user can retry manually via the button shown in the error state.
      setLoadError(true);
    } finally {
      setLoading(false);
    }
  }, [loading, canLoadMore, mx, room, getFilteredEvents]);

  // Auto-load when sentinel scrolls into view
  useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel || !canLoadMore || loading) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry?.isIntersecting) handleLoadMore();
      },
      { threshold: 0.1 },
    );
    observer.observe(sentinel);
    return () => observer.disconnect();
  }, [canLoadMore, loading, handleLoadMore]);

  // Lightbox items (images + videos, flat)
  const lightboxItems: LightboxItem[] = events
    .filter((ev) => {
      const c = ev.getContent();
      return c.msgtype === MsgType.Image || c.msgtype === MsgType.Video;
    })
    .map((ev) => {
      const c = ev.getContent();
      const isEnc = !!c.file;
      return {
        mxcUrl: c.file?.url ?? c.url ?? '',
        encInfo: isEnc ? c.file : undefined,
        mimeType: c.info?.mimetype,
        msgtype: c.msgtype as MsgType.Image | MsgType.Video,
        body: c.body ?? '',
        sender: getSenderName(room, ev.getSender() ?? ''),
        ts: ev.getTs(),
      };
    });

  // Group image/video events by month for the grid
  type MonthGroup = { label: string; events: MatrixEvent[] };
  const monthGroups: MonthGroup[] = [];
  let currentLabel = '';
  for (const ev of events) {
    const label = monthLabel(ev.getTs());
    if (label !== currentLabel) {
      currentLabel = label;
      monthGroups.push({ label, events: [] });
    }
    monthGroups[monthGroups.length - 1]!.events.push(ev);
  }

  return (
    <>
      <Box
        className={ContainerColor({ variant: 'Surface' })}
        direction="Column"
        style={{
          position: 'fixed',
          top: 0,
          right: 0,
          bottom: 0,
          width: '320px',
          zIndex: 500,
          borderLeft: `1px solid ${color.Surface.ContainerLine}`,
          overflow: 'hidden',
        }}
      >
        {/* Header */}
        <Header
          variant="Surface"
          size="600"
          style={{
            flexShrink: 0,
            paddingRight: config.space.S200,
            paddingLeft: config.space.S300,
            borderBottom: `1px solid ${color.Surface.ContainerLine}`,
          }}
        >
          <Box grow="Yes" alignItems="Center" gap="200">
            <Icon size="200" src={Icons.Photo} />
            <Box grow="Yes">
              <Text size="H5" truncate>
                Media Gallery
              </Text>
            </Box>
            {events.length > 0 && (
              <Text size="T200" priority="300" style={{ flexShrink: 0 }}>
                {events.length}
              </Text>
            )}
            <TooltipProvider
              position="Bottom"
              align="End"
              offset={4}
              tooltip={
                <Tooltip>
                  <Text>Close</Text>
                </Tooltip>
              }
            >
              {(ref) => (
                <IconButton ref={ref} variant="Background" aria-label="Close" onClick={onClose}>
                  <Icon src={Icons.Cross} />
                </IconButton>
              )}
            </TooltipProvider>
          </Box>
        </Header>

        {/* Tabs */}
        <Box
          shrink="No"
          gap="100"
          style={{ padding: `${config.space.S200} ${config.space.S200} 0` }}
        >
          {(Object.keys(TAB_LABELS) as GalleryTab[]).map((t) => (
            <TabButton
              key={t}
              label={TAB_LABELS[t]}
              active={tab === t}
              onClick={() => handleTabChange(t)}
            />
          ))}
        </Box>

        {/* Content */}
        <Box grow="Yes" style={{ position: 'relative', overflow: 'hidden' }}>
          <Scroll variant="Background" size="300" visibility="Hover" hideTrack>
            <Box direction="Column" style={{ padding: config.space.S200, gap: 0 }}>
              {/* ── Image / video grid ── */}
              {(tab === 'image' || tab === 'video') && (
                <>
                  {events.length === 0 && !loading && (
                    <Box
                      direction="Column"
                      alignItems="Center"
                      gap="200"
                      style={{ padding: config.space.S400 }}
                    >
                      <Icon src={tab === 'video' ? Icons.Play : Icons.Photo} size="600" />
                      <Text size="T300" priority="300" align="Center">
                        {hasLoadedOnce
                          ? `No ${TAB_LABELS[tab].toLowerCase()} found.`
                          : `No ${TAB_LABELS[tab].toLowerCase()} in recent history.`}
                      </Text>
                    </Box>
                  )}

                  {/* Month groups */}
                  {(() => {
                    let flatIdx = 0;
                    return monthGroups.map((group) => (
                      <Box
                        key={group.label}
                        direction="Column"
                        style={{ marginBottom: config.space.S200 }}
                      >
                        {/* Month header — only shown when there are multiple groups */}
                        {monthGroups.length > 1 && <MonthSeparator label={group.label} />}
                        <div
                          style={{
                            display: 'grid',
                            gridTemplateColumns: 'repeat(3, 1fr)',
                            gap: config.space.S100,
                          }}
                        >
                          {group.events.map((mEvent) => {
                            const c = mEvent.getContent();
                            const isEnc = !!c.file;
                            const isVideo = c.msgtype === MsgType.Video;
                            const info: (IImageInfo & IThumbnailContent) | undefined = c.info;

                            // Prefer thumbnail_file (encrypted thumb) > file > thumbnail_url > url
                            const thumbMxc: string | undefined = isEnc
                              ? (info?.thumbnail_file?.url ?? c.file?.url)
                              : (info?.thumbnail_url ?? c.url);
                            const thumbEnc: IEncryptedFile | undefined = isEnc
                              ? (info?.thumbnail_file ?? c.file)
                              : undefined;
                            const thumbMime: string | undefined =
                              info?.thumbnail_file != null
                                ? (info.thumbnail_info?.mimetype ?? 'image/jpeg')
                                : (info?.mimetype ?? 'image/jpeg');

                            // Guard before incrementing: skipped tiles must not consume a slot
                            if (!thumbMxc) return null;
                            const idx = flatIdx++;
                            return (
                              <GalleryTile
                                key={mEvent.getId()}
                                mxcUrl={thumbMxc}
                                encInfo={thumbEnc}
                                mimeType={thumbMime}
                                isVideo={isVideo}
                                body={c.body ?? ''}
                                sender={getSenderName(room, mEvent.getSender() ?? '')}
                                ts={mEvent.getTs()}
                                useAuthentication={useAuthentication}
                                onClick={() => setLightboxIndex(idx)}
                              />
                            );
                          })}
                        </div>
                      </Box>
                    ));
                  })()}
                </>
              )}

              {/* ── File list ── */}
              {tab === 'file' && (
                <>
                  {events.length === 0 && !loading && (
                    <Box
                      direction="Column"
                      alignItems="Center"
                      gap="200"
                      style={{ padding: config.space.S400 }}
                    >
                      <Icon src={Icons.File} size="600" />
                      <Text size="T300" priority="300" align="Center">
                        {hasLoadedOnce ? 'No files found.' : 'No files in recent history.'}
                      </Text>
                    </Box>
                  )}
                  <Box direction="Column" gap="100">
                    {events.map((mEvent) => {
                      const c = mEvent.getContent();
                      const mxcUrl: string | undefined = c.file?.url ?? c.url;
                      const body: string = c.body ?? 'Unnamed file';
                      const size: number | undefined = c.info?.size;
                      const sender = getSenderName(room, mEvent.getSender() ?? '');
                      const downloadUrl = mxcUrl
                        ? (mxcUrlToHttp(mx, mxcUrl, useAuthentication) ?? '#')
                        : '#';
                      return (
                        <Box
                          key={mEvent.getId()}
                          alignItems="Center"
                          gap="200"
                          style={{
                            padding: `${config.space.S200} ${config.space.S300}`,
                            borderRadius: config.radii.R300,
                            border: `1px solid ${color.Surface.ContainerLine}`,
                            background: color.Surface.Container,
                          }}
                        >
                          <Icon size="300" src={Icons.File} />
                          <Box
                            grow="Yes"
                            direction="Column"
                            style={{ overflow: 'hidden', gap: '2px' }}
                          >
                            <Text size="T300" truncate title={body}>
                              {body}
                            </Text>
                            <Text size="T200" priority="300">
                              {sender}
                              {size != null ? ` · ${formatBytes(size)}` : ''}
                            </Text>
                          </Box>
                          <IconButton
                            variant="Background"
                            size="300"
                            radii="300"
                            aria-label={`Download ${body}`}
                            onClick={() => {
                              const a = document.createElement('a');
                              a.href = downloadUrl;
                              a.download = body;
                              a.target = '_blank';
                              a.rel = 'noreferrer';
                              a.click();
                            }}
                          >
                            <Icon size="200" src={Icons.Download} />
                          </IconButton>
                        </Box>
                      );
                    })}
                  </Box>
                </>
              )}

              {/* ── Pagination status / sentinel ── */}
              {loading && (
                <Box justifyContent="Center" style={{ padding: config.space.S300 }}>
                  <Spinner />
                </Box>
              )}
              {loadError && !loading && (
                <Box
                  direction="Column"
                  alignItems="Center"
                  gap="200"
                  style={{ padding: config.space.S300 }}
                >
                  <Text size="T200" priority="300" align="Center">
                    Failed to load history.
                  </Text>
                  <Button
                    size="300"
                    variant="Secondary"
                    fill="Soft"
                    radii="300"
                    onClick={handleLoadMore}
                  >
                    <Text size="B300">Retry</Text>
                  </Button>
                </Box>
              )}
              {!loading && !loadError && !canLoadMore && hasLoadedOnce && events.length > 0 && (
                <Text
                  size="T200"
                  priority="300"
                  align="Center"
                  style={{ padding: `${config.space.S200} 0` }}
                >
                  Beginning of history
                </Text>
              )}
              {/* IntersectionObserver sentinel — only rendered when safe to auto-trigger */}
              {canLoadMore && !loading && !loadError && (
                <div ref={sentinelRef} style={{ height: 1 }} />
              )}
            </Box>
          </Scroll>
        </Box>
      </Box>

      {/* Lightbox */}
      {lightboxIndex !== null && (
        <Lightbox
          items={lightboxItems}
          initialIndex={lightboxIndex}
          useAuthentication={useAuthentication}
          onClose={() => setLightboxIndex(null)}
        />
      )}
    </>
  );
}
