'use client';

import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import { useRouter } from 'next/navigation';
import DataTable, { Column } from '@/components/ui/DataTable';
import Pagination from '@/components/ui/Pagination';
import FilterPanel from '@/components/ui/FilterPanel';
import Toolbar from '@/components/ui/Toolbar';
import Modal from '@/components/ui/CustomModal';
import CommonTimelineModal from '@/components/ui/CommonTimelineModal';
import { toast } from 'react-hot-toast';
import { ArchiveRestore, History, SquarePen, Trash2, Check, X, ExternalLink } from 'lucide-react';
import { getApiErrorMessage } from '@/lib/utils/apiError';

// ─── Types ────────────────────────────────────────────────────────────────────

interface SitemapUrl {
  id: string;
  url_path: string;
  priority: number;
  last_modified: string | null; // YYYY-MM-DD
  is_active: boolean;
  deleted_at: string | null;
  created_at: string;
}

interface PaginationData {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
}

interface TabCounts {
  active: number;
  deleted: number;
}

interface SitemapUrlsTableProps {
  canEdit: boolean;
  canDelete: boolean;
  canBulkDelete: boolean;
  canViewDeleted: boolean;
  canPermanentDelete: boolean;
  canRestore: boolean;
  canBulkRestore: boolean;
  canViewTimeline: boolean;
  canActivateDeactivate: boolean;
  initialSitemapUrls: {
    sitemapUrls: SitemapUrl[];
    pagination: PaginationData;
  };
  initialCounts: TabCounts;
}

type TabType = 'active' | 'deleted';

interface ActiveFilters {
  search: string;
  status: string;
  startDate: string;
  endDate: string;
}

interface DeletedFilters {
  search: string;
  startDate: string;
  endDate: string;
}

interface ModalConfig {
  isOpen: boolean;
  type: 'danger' | 'warning' | 'info' | 'success';
  title: string;
  message: string;
  confirmText?: string;
  cancelText?: string;
  onConfirm: () => void;
}

// ─── Constants ────────────────────────────────────────────────────────────────

const ICON_STROKE = { fill: 'none', stroke: 'currentColor', strokeWidth: 2 } as const;

const EMPTY_ACTIVE_FILTERS: ActiveFilters = { search: '', status: '', startDate: '', endDate: '' };
const EMPTY_DELETED_FILTERS: DeletedFilters = { search: '', startDate: '', endDate: '' };

const MODAL_CLOSED: ModalConfig = {
  isOpen: false, type: 'danger', title: '', message: '',
  confirmText: 'Confirm', cancelText: 'Cancel', onConfirm: () => {},
};

// ─── API Helpers ──────────────────────────────────────────────────────────────

function jsonInit(method: string, body: unknown): RequestInit {
  return { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) };
}

async function fetchSitemapUrlsApi(
  page: number,
  tab: TabType,
  active: ActiveFilters,
  deleted: DeletedFilters,
  signal: AbortSignal,
) {
  const params = new URLSearchParams({
    page: String(page),
    limit: '10',
    includeDeleted: tab === 'deleted' ? 'true' : 'false',
  });

  if (tab === 'deleted') {
    if (deleted.search.trim()) params.append('search', deleted.search.trim());
    if (deleted.startDate) params.append('deletedStartDate', deleted.startDate);
    if (deleted.endDate) params.append('deletedEndDate', deleted.endDate);
  } else {
    if (active.search.trim()) params.append('search', active.search.trim());
    if (active.status) params.append('status', active.status);
    if (active.startDate) params.append('startDate', active.startDate);
    if (active.endDate) params.append('endDate', active.endDate);
  }

  const res = await fetch(`/api/sitemap-urls?${params}`, { cache: 'no-store', signal });
  if (!res.ok) throw new Error('Failed to fetch sitemap URLs');
  return res.json() as Promise<{ data: { sitemapUrls: SitemapUrl[]; pagination: PaginationData } }>;
}

async function fetchCountsApi(): Promise<TabCounts> {
  const res = await fetch('/api/sitemap-urls/counts', { cache: 'no-store' });
  if (!res.ok) throw new Error('Failed to fetch counts');
  const json = await res.json();
  return json.data as TabCounts;
}

// 'YYYY-MM-DD' shown as a local date without a timezone shift.
function formatDateOnly(value: string | null): string {
  if (!value) return '—';
  const [y, m, d] = value.split('-').map(Number);
  return new Date(y, m - 1, d).toLocaleDateString();
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function PriorityBadge({ priority }: { priority: number }) {
  return (
    <div className="flex items-center gap-2 min-w-[90px]">
      <div className="h-1.5 w-12 rounded-full overflow-hidden" style={{ background: 'var(--color-surface-alt)' }}>
        <div className="h-full rounded-full" style={{ width: `${priority * 100}%`, background: 'var(--color-cta)' }} />
      </div>
      <span className="text-xs font-medium tabular-nums" style={{ color: 'var(--color-text-secondary)' }}>
        {priority.toFixed(1)}
      </span>
    </div>
  );
}

function StatusBadge({ entry }: { entry: SitemapUrl }) {
  const [label, bg, color] = entry.deleted_at
    ? ['Deleted', 'var(--color-danger-light)', 'var(--color-danger)']
    : entry.is_active
      ? ['Active', 'var(--color-success-light)', 'var(--color-success)']
      : ['Inactive', 'var(--color-warning-light)', 'var(--color-warning)'];
  return (
    <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full" style={{ background: bg, color }}>
      {label}
    </span>
  );
}

function ActionButton({ title, color, onClick, children }: {
  title: string;
  color: string;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button onClick={onClick} className="p-1 rounded hover:bg-surface-alt transition-colors" style={{ color }} title={title}>
      {children}
    </button>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function SitemapUrlsTable({
  canEdit,
  canDelete,
  canBulkDelete,
  canViewDeleted,
  canPermanentDelete,
  canRestore,
  canBulkRestore,
  canViewTimeline,
  canActivateDeactivate,
  initialSitemapUrls,
  initialCounts,
}: SitemapUrlsTableProps) {
  const router = useRouter();

  // ── Core state ────────────────────────────────────────────────────────────
  const [entries, setEntries] = useState<SitemapUrl[]>(initialSitemapUrls.sitemapUrls);
  const [pagination, setPagination] = useState<PaginationData>(initialSitemapUrls.pagination);
  const [counts, setCounts] = useState<TabCounts>(initialCounts);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<TabType>('active');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [showFilters, setShowFilters] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [modal, setModal] = useState<ModalConfig>(MODAL_CLOSED);
  const [timelineModal, setTimelineModal] = useState({ isOpen: false, entryId: '', entryName: '' });

  // ── Committed / draft filters ─────────────────────────────────────────────
  const [activeFilters, setActiveFilters] = useState<ActiveFilters>(EMPTY_ACTIVE_FILTERS);
  const [deletedFilters, setDeletedFilters] = useState<DeletedFilters>(EMPTY_DELETED_FILTERS);
  const [draftActive, setDraftActive] = useState<ActiveFilters>(EMPTY_ACTIVE_FILTERS);
  const [draftDeleted, setDraftDeleted] = useState<DeletedFilters>(EMPTY_DELETED_FILTERS);

  // ── Refs ──────────────────────────────────────────────────────────────────
  const abortRef = useRef<AbortController | null>(null);
  const entriesRef = useRef(entries);
  const selectedRef = useRef(selectedIds);

  useEffect(() => { entriesRef.current = entries; }, [entries]);
  useEffect(() => { selectedRef.current = selectedIds; }, [selectedIds]);
  useEffect(() => () => abortRef.current?.abort(), []);

  // ── Fetch functions ──────────────────────────────────────────────────────
  const fetchEntries = useCallback(async (
    page: number,
    tab: TabType,
    committed: { active: ActiveFilters; deleted: DeletedFilters },
  ) => {
    abortRef.current?.abort();
    const ctrl = new AbortController();
    abortRef.current = ctrl;

    setLoading(true);
    try {
      const json = await fetchSitemapUrlsApi(page, tab, committed.active, committed.deleted, ctrl.signal);
      setEntries(json.data.sitemapUrls);
      setPagination(json.data.pagination);
      setCurrentPage(page);
      setSelectedIds(new Set());
    } catch (err) {
      if ((err as Error).name === 'AbortError') return;
      console.error('Failed to fetch sitemap URLs:', err);
      toast.error('Failed to load sitemap URLs');
    } finally {
      if (abortRef.current === ctrl) setLoading(false);
    }
  }, []);

  const refreshCounts = useCallback(async () => {
    try {
      setCounts(await fetchCountsApi());
    } catch {
      console.warn('Could not refresh sitemap URL counts');
    }
  }, []);

  const refreshAfterMutation = useCallback(async () => {
    await Promise.all([
      fetchEntries(currentPage, activeTab, { active: activeFilters, deleted: deletedFilters }),
      refreshCounts(),
    ]);
  }, [fetchEntries, refreshCounts, currentPage, activeTab, activeFilters, deletedFilters]);

  // ── Modal helpers ─────────────────────────────────────────────────────────
  const closeModal = useCallback(() => {
    if (!isDeleting) setModal(MODAL_CLOSED);
  }, [isDeleting]);

  const openModal = useCallback((config: Omit<ModalConfig, 'isOpen'>) => {
    setModal({ isOpen: true, ...config });
  }, []);

  // One place for every mutating request: run it, close the modal, refresh
  // the list + tab counts, toast the server's message.
  const runMutation = useCallback(async (
    url: string,
    init: RequestInit,
    successFallback: string,
    errorFallback: string,
  ) => {
    setIsDeleting(true);
    try {
      const res = await fetch(url, init);
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setModal(MODAL_CLOSED);
        await refreshAfterMutation();
        toast.success(data.message || successFallback);
      } else {
        toast.error(getApiErrorMessage(data, errorFallback));
      }
    } catch {
      toast.error('Network error — please try again');
    } finally {
      setIsDeleting(false);
    }
  }, [refreshAfterMutation]);

  // ── CRUD operations ───────────────────────────────────────────────────────
  const handleStatusChange = useCallback((id: string, isActive: boolean) =>
    runMutation(`/api/sitemap-urls/${id}/status`, jsonInit('PATCH', { is_active: isActive }),
      `Sitemap URL ${isActive ? 'activated' : 'deactivated'}`, 'Failed to update status'),
  [runMutation]);

  const handleDelete = useCallback((id: string) =>
    runMutation(`/api/sitemap-urls/${id}`, { method: 'DELETE' }, 'Sitemap URL deleted', 'Failed to delete sitemap URL'),
  [runMutation]);

  const handlePermanentDelete = useCallback((id: string) =>
    runMutation(`/api/sitemap-urls/${id}/permanent`, { method: 'DELETE' }, 'Sitemap URL permanently deleted', 'Failed to delete sitemap URL'),
  [runMutation]);

  const handleRestore = useCallback((id: string) =>
    runMutation(`/api/sitemap-urls/${id}/restore`, { method: 'POST' }, 'Sitemap URL restored', 'Failed to restore sitemap URL'),
  [runMutation]);

  const handleBulkDelete = useCallback(() =>
    runMutation('/api/sitemap-urls/bulk', jsonInit('DELETE', { ids: Array.from(selectedRef.current) }),
      'Sitemap URLs deleted', 'Failed to delete sitemap URLs'),
  [runMutation]);

  const handleBulkPermanentDelete = useCallback(() =>
    runMutation('/api/sitemap-urls/bulk/permanent', jsonInit('DELETE', { ids: Array.from(selectedRef.current) }),
      'Sitemap URLs permanently deleted', 'Failed to delete sitemap URLs'),
  [runMutation]);

  const handleBulkRestore = useCallback(() =>
    runMutation('/api/sitemap-urls/bulk/restore', jsonInit('POST', { ids: Array.from(selectedRef.current) }),
      'Sitemap URLs restored', 'Failed to restore sitemap URLs'),
  [runMutation]);

  // ── Action handlers ───────────────────────────────────────────────────────
  const handleEditClick = useCallback((id: string) => {
    router.push(`/admin/dashboard/sitemap-urls/edit/${id}`);
  }, [router]);

  const handleDeleteClick = useCallback((entry: SitemapUrl) => {
    if (activeTab === 'deleted') {
      openModal({
        type: 'danger',
        title: 'Permanently Delete Sitemap URL',
        message: `Permanently delete "${entry.url_path}"? This cannot be undone.`,
        confirmText: 'Permanently Delete',
        cancelText: 'Cancel',
        onConfirm: () => handlePermanentDelete(entry.id),
      });
      return;
    }
    openModal({
      type: 'danger',
      title: 'Delete Sitemap URL',
      message: `Delete "${entry.url_path}"? It will be removed from the sitemap and moved to deleted items.`,
      confirmText: 'Delete',
      cancelText: 'Cancel',
      onConfirm: () => handleDelete(entry.id),
    });
  }, [activeTab, handleDelete, handlePermanentDelete, openModal]);

  const handleRestoreClick = useCallback((entry: SitemapUrl) => {
    openModal({
      type: 'info',
      title: 'Restore Sitemap URL',
      message: `Restore "${entry.url_path}"? It will be active again.`,
      confirmText: 'Restore',
      cancelText: 'Cancel',
      onConfirm: () => handleRestore(entry.id),
    });
  }, [handleRestore, openModal]);

  const handleToggleStatusClick = useCallback((entry: SitemapUrl) => {
    const activate = !entry.is_active;
    openModal({
      type: activate ? 'success' : 'warning',
      title: activate ? 'Activate Sitemap URL' : 'Deactivate Sitemap URL',
      message: activate
        ? `Activate "${entry.url_path}"? It will be listed in the sitemap.`
        : `Deactivate "${entry.url_path}"? It will be left out of the sitemap.`,
      confirmText: activate ? 'Activate' : 'Deactivate',
      cancelText: 'Cancel',
      onConfirm: () => handleStatusChange(entry.id, activate),
    });
  }, [handleStatusChange, openModal]);

  // ── Bulk confirmations ────────────────────────────────────────────────────
  const showBulkDeleteConfirmation = useCallback(() => {
    const count = selectedRef.current.size;
    openModal(activeTab === 'deleted'
      ? {
          type: 'danger',
          title: 'Permanent Bulk Delete',
          message: `Permanently delete ${count} sitemap URL(s)? This cannot be undone.`,
          confirmText: 'Permanently Delete All',
          cancelText: 'Cancel',
          onConfirm: handleBulkPermanentDelete,
        }
      : {
          type: 'danger',
          title: 'Bulk Delete Sitemap URLs',
          message: `Delete ${count} sitemap URL(s)? They will move to deleted items.`,
          confirmText: 'Delete All',
          cancelText: 'Cancel',
          onConfirm: handleBulkDelete,
        });
  }, [activeTab, handleBulkDelete, handleBulkPermanentDelete, openModal]);

  const showBulkRestoreConfirmation = useCallback(() => {
    openModal({
      type: 'info',
      title: 'Bulk Restore Sitemap URLs',
      message: `Restore ${selectedRef.current.size} sitemap URL(s)?`,
      confirmText: 'Restore All',
      cancelText: 'Cancel',
      onConfirm: handleBulkRestore,
    });
  }, [handleBulkRestore, openModal]);

  // ── Tabs / filters / pagination / selection ───────────────────────────────
  const handleTabChange = useCallback((tab: TabType) => {
    setActiveTab(tab);
    setShowFilters(false);
    setActiveFilters(EMPTY_ACTIVE_FILTERS);
    setDeletedFilters(EMPTY_DELETED_FILTERS);
    setDraftActive(EMPTY_ACTIVE_FILTERS);
    setDraftDeleted(EMPTY_DELETED_FILTERS);
    fetchEntries(1, tab, { active: EMPTY_ACTIVE_FILTERS, deleted: EMPTY_DELETED_FILTERS });
  }, [fetchEntries]);

  const handleToggleFilters = useCallback(() => {
    setShowFilters((prev) => {
      if (!prev) {
        setDraftActive({ ...activeFilters });
        setDraftDeleted({ ...deletedFilters });
      }
      return !prev;
    });
  }, [activeFilters, deletedFilters]);

  const handleApplyFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDeletedFilters(draftDeleted);
      fetchEntries(1, activeTab, { active: activeFilters, deleted: draftDeleted });
    } else {
      setActiveFilters(draftActive);
      fetchEntries(1, activeTab, { active: draftActive, deleted: deletedFilters });
    }
  }, [activeTab, draftActive, draftDeleted, activeFilters, deletedFilters, fetchEntries]);

  const handleResetFilters = useCallback(() => {
    if (activeTab === 'deleted') {
      setDraftDeleted(EMPTY_DELETED_FILTERS);
      setDeletedFilters(EMPTY_DELETED_FILTERS);
      fetchEntries(1, activeTab, { active: activeFilters, deleted: EMPTY_DELETED_FILTERS });
    } else {
      setDraftActive(EMPTY_ACTIVE_FILTERS);
      setActiveFilters(EMPTY_ACTIVE_FILTERS);
      fetchEntries(1, activeTab, { active: EMPTY_ACTIVE_FILTERS, deleted: deletedFilters });
    }
  }, [activeTab, activeFilters, deletedFilters, fetchEntries]);

  const handlePageChange = useCallback((page: number) => {
    if (page < 1 || page > pagination.totalPages) return;
    fetchEntries(page, activeTab, { active: activeFilters, deleted: deletedFilters });
  }, [pagination.totalPages, fetchEntries, activeTab, activeFilters, deletedFilters]);

  const handleSelectAll = useCallback(() => {
    setSelectedIds((prev) =>
      prev.size === entriesRef.current.length ? new Set() : new Set(entriesRef.current.map((e) => e.id)),
    );
  }, []);

  const handleSelect = useCallback((id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  }, []);

  // ── Columns ───────────────────────────────────────────────────────────────
  const columns = useMemo<Column<SitemapUrl>[]>(() => {
    const cols: Column<SitemapUrl>[] = [
      {
        key: 'url_path',
        header: 'URL Path',
        render: (entry) => (
          <a
            href={entry.url_path}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-1.5 font-mono text-sm break-all hover:underline"
            style={{ color: 'var(--color-text)' }}
            title="Open on the store"
          >
            {entry.url_path}
            <ExternalLink size={12} className="shrink-0" style={{ color: 'var(--color-text-tertiary)' }} />
          </a>
        ),
      },
      { key: 'priority', header: 'Priority', render: (entry) => <PriorityBadge priority={entry.priority} /> },
      {
        key: 'last_modified',
        header: 'Last Modified',
        render: (entry) => (
          <span style={{ color: 'var(--color-text-secondary)' }}>{formatDateOnly(entry.last_modified)}</span>
        ),
      },
      { key: 'status', header: 'Status', render: (entry) => <StatusBadge entry={entry} /> },
      {
        key: 'created_at',
        header: 'Created At',
        render: (entry) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {new Date(entry.created_at).toLocaleDateString()}
          </span>
        ),
      },
    ];

    if (activeTab === 'deleted') {
      cols.push({
        key: 'deleted_at',
        header: 'Deleted At',
        render: (entry) => (
          <span style={{ color: 'var(--color-text-tertiary)' }}>
            {entry.deleted_at ? new Date(entry.deleted_at).toLocaleDateString() : '-'}
          </span>
        ),
      });
    }

    cols.push({
      key: 'actions',
      header: 'Actions',
      className: 'text-right',
      render: (entry) => (
        <div className="flex justify-end gap-2">
          {canViewTimeline && (
            <ActionButton title="View Timeline" color="var(--color-text-secondary)"
              onClick={() => setTimelineModal({ isOpen: true, entryId: entry.id, entryName: entry.url_path })}>
              <History size={16} />
            </ActionButton>
          )}
          {activeTab === 'deleted' ? (
            <>
              {canRestore && (
                <ActionButton title="Restore Sitemap URL" color="var(--color-success)" onClick={() => handleRestoreClick(entry)}>
                  <ArchiveRestore size={16} />
                </ActionButton>
              )}
              {canPermanentDelete && (
                <ActionButton title="Permanently Delete" color="var(--color-danger)" onClick={() => handleDeleteClick(entry)}>
                  <Trash2 size={16} />
                </ActionButton>
              )}
            </>
          ) : (
            <>
              {canActivateDeactivate && (
                <ActionButton
                  title={entry.is_active ? 'Deactivate Sitemap URL' : 'Activate Sitemap URL'}
                  color={entry.is_active ? 'var(--color-warning)' : 'var(--color-success)'}
                  onClick={() => handleToggleStatusClick(entry)}
                >
                  {entry.is_active ? <X size={16} /> : <Check size={16} />}
                </ActionButton>
              )}
              {canEdit && (
                <ActionButton title="Edit Sitemap URL" color="var(--color-info)" onClick={() => handleEditClick(entry.id)}>
                  <SquarePen size={16} />
                </ActionButton>
              )}
              {canDelete && (
                <ActionButton title="Delete" color="var(--color-danger)" onClick={() => handleDeleteClick(entry)}>
                  <Trash2 size={16} />
                </ActionButton>
              )}
            </>
          )}
        </div>
      ),
    });

    return cols;
  }, [
    activeTab, canEdit, canDelete, canPermanentDelete, canRestore, canViewTimeline, canActivateDeactivate,
    handleEditClick, handleDeleteClick, handleRestoreClick, handleToggleStatusClick,
  ]);

  // ── Filter fields ─────────────────────────────────────────────────────────
  const filterFields = useMemo(() => {
    if (activeTab === 'deleted') {
      return [
        {
          name: 'deletedSearch',
          label: 'Search',
          type: 'text' as const,
          placeholder: 'Search by URL path...',
          value: draftDeleted.search,
          onChange: (v: string) => setDraftDeleted((p) => ({ ...p, search: v })),
        },
        {
          name: 'deletedStartDate',
          label: 'Deleted From',
          type: 'date' as const,
          value: draftDeleted.startDate,
          onChange: (v: string) => setDraftDeleted((p) => ({ ...p, startDate: v })),
        },
        {
          name: 'deletedEndDate',
          label: 'Deleted To',
          type: 'date' as const,
          value: draftDeleted.endDate,
          onChange: (v: string) => setDraftDeleted((p) => ({ ...p, endDate: v })),
        },
      ];
    }
    return [
      {
        name: 'search',
        label: 'Search',
        type: 'text' as const,
        placeholder: 'Search by URL path...',
        value: draftActive.search,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, search: v })),
      },
      {
        name: 'status',
        label: 'Status',
        type: 'select' as const,
        options: [
          { value: '', label: 'All Status' },
          { value: 'active', label: 'Active' },
          { value: 'inactive', label: 'Inactive' },
        ],
        value: draftActive.status,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, status: v })),
      },
      {
        name: 'startDate',
        label: 'Created From',
        type: 'date' as const,
        value: draftActive.startDate,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, startDate: v })),
      },
      {
        name: 'endDate',
        label: 'Created To',
        type: 'date' as const,
        value: draftActive.endDate,
        onChange: (v: string) => setDraftActive((p) => ({ ...p, endDate: v })),
      },
    ];
  }, [activeTab, draftActive, draftDeleted]);

  // ── Bulk action bar ───────────────────────────────────────────────────────
  const bulkActionBar = useMemo(() => {
    if (selectedIds.size === 0) return null;

    const deleteIcon = (
      <svg width="16" height="16" {...ICON_STROKE}>
        <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
      </svg>
    );

    if (activeTab === 'deleted') {
      return (
        <div className="flex gap-2">
          {canBulkRestore && (
            <button
              onClick={showBulkRestoreConfirmation}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
              style={{ background: 'var(--color-success)', color: 'white' }}
            >
              <ArchiveRestore size={16} />
              Restore ({selectedIds.size})
            </button>
          )}
          {canPermanentDelete && (
            <button
              onClick={showBulkDeleteConfirmation}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
              style={{ background: 'var(--color-danger)', color: 'white' }}
            >
              {deleteIcon}
              Permanently Delete ({selectedIds.size})
            </button>
          )}
        </div>
      );
    }

    if (!canBulkDelete) return null;
    return (
      <button
        onClick={showBulkDeleteConfirmation}
        className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium"
        style={{ background: 'var(--color-danger)', color: 'white' }}
      >
        {deleteIcon}
        Delete ({selectedIds.size})
      </button>
    );
  }, [
    selectedIds, activeTab, canBulkDelete, canBulkRestore, canPermanentDelete,
    showBulkDeleteConfirmation, showBulkRestoreConfirmation,
  ]);

  // ── Render ────────────────────────────────────────────────────────────────
  return (
    <div className="space-y-4">
      {canViewDeleted && (
        <div className="flex border-b overflow-x-auto whitespace-nowrap" style={{ borderColor: 'var(--color-border)' }}>
          <button
            onClick={() => handleTabChange('active')}
            className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
              activeTab === 'active'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Active Sitemap URLs ({counts.active})
          </button>
          <button
            onClick={() => handleTabChange('deleted')}
            className={`px-4 py-2 text-sm font-medium transition-all border-b-2 ${
              activeTab === 'deleted'
                ? 'border-red-500 text-red-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Deleted Sitemap URLs ({counts.deleted})
          </button>
        </div>
      )}

      <Toolbar
        leftActions={
          <>
            <button
              onClick={handleToggleFilters}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all border"
              style={{
                borderColor: 'var(--color-border)',
                color: 'var(--color-text)',
                background: 'var(--color-surface)',
              }}
            >
              <svg width="16" height="16" {...ICON_STROKE}>
                <path d="M3 6h18M6 12h12M10 18h4"/>
              </svg>
              {showFilters ? 'Hide Filters' : 'Show Filters'}
            </button>
            {bulkActionBar}
          </>
        }
      />

      {showFilters && (
        <FilterPanel
          fields={filterFields}
          onApply={handleApplyFilters}
          onReset={handleResetFilters}
          applyButtonText="Apply Filters"
          resetButtonText="Reset"
        />
      )}

      <DataTable
        columns={columns}
        data={entries}
        loading={loading}
        selectedIds={selectedIds}
        onSelect={handleSelect}
        onSelectAll={handleSelectAll}
        getRowId={(entry) => entry.id}
        showCheckbox={activeTab === 'deleted' ? (canPermanentDelete || canBulkRestore) : canBulkDelete}
        emptyMessage={activeTab === 'deleted' ? 'No deleted sitemap URLs found' : 'No sitemap URLs found'}
        skeletonRows={10}
      />

      {!loading && pagination.totalPages > 0 && (
        <Pagination
          currentPage={currentPage}
          totalPages={pagination.totalPages}
          totalItems={pagination.total}
          itemsPerPage={pagination.limit}
          onPageChange={handlePageChange}
          showItemsInfo
        />
      )}

      <Modal
        isOpen={modal.isOpen}
        onClose={closeModal}
        onConfirm={modal.onConfirm}
        title={modal.title}
        message={modal.message}
        confirmText={modal.confirmText}
        cancelText={modal.cancelText}
        type={modal.type}
        isLoading={isDeleting}
      />

      <CommonTimelineModal
        isOpen={timelineModal.isOpen}
        onClose={() => setTimelineModal({ isOpen: false, entryId: '', entryName: '' })}
        entityType="sitemap_url"
        entityId={timelineModal.entryId}
        entityName={timelineModal.entryName}
        title="Sitemap URL Timeline"
      />
    </div>
  );
}
