'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import {
  X,
  Package,
  MapPin,
  CreditCard,
  Tag,
  User,
  Truck,
  RefreshCw,
  RotateCcw,
  DollarSign,
  Pencil,
  Trash2,
  History,
  RotateCw,
} from 'lucide-react';
import PaymentModal from '@/components/admin/orders/PaymentModal';
import RefundFullOrderModal from '@/components/admin/orders/RefundFullOrderModal';
import EditPaymentModal from '@/components/admin/orders/EditPaymentModal';
import CommonTimelineModal from '@/components/ui/CommonTimelineModal';
import toast from 'react-hot-toast';
import Image from 'next/image';
import { generateInvoiceHTML } from './InvoicePrint';
import { getApiErrorMessage } from '@/lib/utils/apiError';
import { useCurrencyStore } from '@/store/currencyStore';
import { calculateOrderGrandTotal } from '@/lib/orders/calculateGrandTotal';

// ─── Types ────────────────────────────────────────────────────────────────
interface OrderItem {
  id: string;
  product_name: string;
  sku: string;
  variant_name: string | null;
  variant_sku: string | null;
  attributes_snapshot: string | null;
  image_url: string | null;
  quantity: number;
  unit_price: number;
  compare_price: number | null;
  subtotal: number;
  discount_amount: number;
  tax_amount: number;
  total_price: number;
  is_returned: boolean;
  return_quantity: number;
  return_reason: string | null;
}

interface StatusHistory {
  id: string;
  old_status: string | null;
  new_status: string;
  note: string | null;
  changed_by_name: string | null;
  is_customer_visible: boolean;
  created_at: string;
}

interface PaymentRecord {
  id: string;
  payment_method: string;
  transaction_id: string | null;
  amount: number;
  status: string;
  note: string | null;
  screenshot_url?: string | null;
  deleted_at?: string | null;
  created_at: string;
}

interface BillingAddress {
  full_name: string;
  phone: string;
  address_line1: string;
  address_line2: string | null;
  city: string;
  state: string;
  postal_code: string;
  country: string;
  landmark?: string | null;
}

interface OrderDetail {
  order: {
    id: string;
    order_number: string;
    status: string;
    payment_method: string;
    payment_status: string;
    delivery_fee: number;
    tax_amount: number;
    tax_percentage: number;
    coupon_code: string | null;
    coupon_discount_amount: number;
    user_name: string;
    user_email: string;
    shipping_full_name: string | null;
    shipping_phone: string | null;
    shipping_address_line1: string | null;
    shipping_city: string | null;
    shipping_state: string | null;
    shipping_postal_code: string | null;
    shipping_country: string | null;
    shipping_landmark: string | null;
    customer_notes: string | null;
    admin_notes: string | null;
    cancellation_reason: string | null;
    created_at: string;
  };
  items: OrderItem[];
  status_history: StatusHistory[];
  billing_address: BillingAddress | null;
}

interface OrderDetailModalProps {
  isOpen: boolean;
  orderId: string | null;
  onClose: () => void;
  canUpdateStatus?: boolean;
  canSingleItemStatus?: boolean;
  canViewPayments?: boolean;
  canManagePayments?: boolean;
  canRefund?: boolean;
  canDeletePayments?: boolean;
  canViewPaymentTimeline?: boolean;
  canRestorePayments?: boolean;
  canViewDeletedPayments?: boolean;
  canPermanentDeletePayments?: boolean;
  canExport?: boolean;
  onStatusChange?: (orderId: string) => void;
  onDataChange?: () => void;
}

// ─── Constants ────────────────────────────────────────────────────────────
const STATUS_COLORS: Record<string, string> = {
  pending: '#F59E0B',
  confirmed: '#3B82F6',
  shipped: '#8B5CF6',
  delivered: '#059669',
  cancelled: '#EF4444',
  returned: '#DC2626',
  refunded: '#F97316',
};

const STATUS_LABELS: Record<string, string> = {
  pending: 'Pending',
  confirmed: 'Confirmed',
  shipped: 'Shipped',
  delivered: 'Delivered',
  cancelled: 'Cancelled',
  returned: 'Returned',
  refunded: 'Refunded',
};

const PAYMENT_METHOD_LABELS: Record<string, string> = {
  cod: 'Cash on Delivery',
  bank_transfer: 'Bank Transfer',
  paypal: 'PayPal',
  stripe: 'Stripe',
};

const PAYMENT_STATUS_COLORS: Record<string, string> = {
  pending: '#F59E0B',
  paid: '#10B981',
  failed: '#EF4444',
  refunded: '#8B5CF6',
  partially_refunded: '#F97316',
};

// ─── Initial States ───────────────────────────────────────────────────────
const INITIAL_RETURN_MODAL = {
  isOpen: false,
  itemId: null as string | null,
  itemName: '',
};

const INITIAL_EDIT_PAYMENT: {
  isOpen: boolean;
  payment: PaymentRecord | null;
} = {
  isOpen: false,
  payment: null,
};

const INITIAL_TIMELINE = {
  isOpen: false,
  paymentId: null as string | null,
  paymentMethod: '',
};

// ─── Sub-components ───────────────────────────────────────────────────────
function StatusBadge({ status }: { status: string }) {
  return (
    <span
      className="inline-flex px-3 py-1 text-sm font-medium rounded-full capitalize"
      style={{
        background: `${STATUS_COLORS[status]}20`,
        color: STATUS_COLORS[status],
        border: `1px solid ${STATUS_COLORS[status]}40`,
      }}
    >
      {STATUS_LABELS[status] || status}
    </span>
  );
}

function TimelineItem({ entry, isLast }: { entry: StatusHistory; isLast: boolean }) {
  const statusColor = STATUS_COLORS[entry.new_status] || '#6B7280';
  const oldStatusLabel = entry.old_status
    ? STATUS_LABELS[entry.old_status] || entry.old_status
    : 'Order Created';
  const newStatusLabel = STATUS_LABELS[entry.new_status] || entry.new_status;

  return (
    <div className="flex gap-3 pb-1 relative">
      <div className="flex flex-col items-center">
        <div
          className="w-3 h-3 rounded-full mt-1.5 hrink-0"
          style={{ background: statusColor }}
        />
        {!isLast && (
          <div
            className="w-0.5 flex-1 mt-1"
            style={{ background: 'var(--color-border)' }}
          />
        )}
      </div>
      <div className="flex-1 pb-3">
        <div className="flex items-center gap-2 mb-1">
          <span className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>
            {oldStatusLabel} → {newStatusLabel}
          </span>
          <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
            {new Date(entry.created_at).toLocaleString()}
          </span>
        </div>
        {entry.note && (
          <p
            className="text-xs mb-1 p-2 rounded"
            style={{
              background: 'var(--color-surface-alt)',
              color: 'var(--color-text-secondary)',
            }}
          >
            {entry.note}
          </p>
        )}
        {entry.changed_by_name && (
          <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
            by {entry.changed_by_name}
          </p>
        )}
      </div>
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────
export default function OrderDetailModal({
  isOpen,
  orderId,
  onClose,
  canUpdateStatus,
  canSingleItemStatus,
  canViewPayments,
  canManagePayments,
  canRefund,
  canDeletePayments,
  canViewPaymentTimeline,
  canRestorePayments,
  canViewDeletedPayments,
  canPermanentDeletePayments,
  onStatusChange,
  onDataChange,
  canExport
}: OrderDetailModalProps) {
  const [data, setData] = useState<OrderDetail | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'items' | 'timeline' | 'payments'>('items');
  const formatAmount = useCurrencyStore((s) => s.formatAmount);

  // Return modal state
  const [returnModal, setReturnModal] = useState(INITIAL_RETURN_MODAL);
  const [returnReason, setReturnReason] = useState('');
  const [processingReturn, setProcessingReturn] = useState(false);

  // Payment states
  const [payments, setPayments] = useState<PaymentRecord[]>([]);
  const [showDeletedPayments, setShowDeletedPayments] = useState(false);
  const [loadingPayments, setLoadingPayments] = useState(false);
  const [paymentModalOpen, setPaymentModalOpen] = useState(false);
  const [refundModalOpen, setRefundModalOpen] = useState(false);

  // Edit/Delete payment states
  const [editPaymentModal, setEditPaymentModal] = useState(INITIAL_EDIT_PAYMENT);
  const [deletePaymentId, setDeletePaymentId] = useState<string | null>(null);
  const [deletingPayment, setDeletingPayment] = useState(false);
  const [permanentDeletePaymentId, setPermanentDeletePaymentId] = useState<string | null>(null);
  const [restorePaymentId, setRestorePaymentId] = useState<string | null>(null);

  const [generatingInvoice, setGeneratingInvoice] = useState(false);

  // Payment Timeline state
  const [paymentTimeline, setPaymentTimeline] = useState(INITIAL_TIMELINE);

  // ─── Fetch functions ─────────────────────────────────────────────────
  const fetchOrderDetail = useCallback(async (id: string) => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/orders/${id}`);
      if (!res.ok) throw new Error('Failed to fetch order');
      const json = await res.json();
      setData(json.data);
    } catch (err) {
      setError('Failed to load order details');
      console.error('[OrderDetailModal]', err);
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchPayments = useCallback(
    async (includeDeleted = false) => {
      if (!orderId) return;
      setLoadingPayments(true);
      try {
        const url = includeDeleted
          ? `/api/orders/${orderId}/payments?includeDeleted=true`
          : `/api/orders/${orderId}/payments`;
        const res = await fetch(url);
        if (res.ok) {
          const json = await res.json();
          setPayments(json.data || []);
        }
      } catch {
        /* ignore */
      } finally {
        setLoadingPayments(false);
      }
    },
    [orderId]
  );

  // Opens the shared timeline modal for one payment; it fetches its own data
  // from /api/timeline/order_payment/:paymentId.
  const openPaymentTimeline = useCallback((paymentId: string, paymentMethod: string) => {
    setPaymentTimeline({ isOpen: true, paymentId, paymentMethod });
  }, []);

  const handleGenerateInvoice = async () => {
  if (!orderId) return;
  setGeneratingInvoice(true);
  try {
    const res = await fetch(`/api/orders/${orderId}/invoice`);
    if (res.ok) {
      const json = await res.json();
      const html = generateInvoiceHTML(json.data);
      const printWindow = window.open('', '_blank', 'width=900,height=700');
      if (printWindow) {
        printWindow.document.write(html);
        printWindow.document.close();
      }
    } else {
      toast.error('Failed to generate invoice');
    }
  } catch {
    toast.error('Network error');
  } finally {
    setGeneratingInvoice(false);
  }
};

  // ─── Reset state when modal opens ────────────────────────────────────
  const prevOrderIdRef = useRef<string | null>(null);

  useEffect(() => {
    if (isOpen && orderId && orderId !== prevOrderIdRef.current) {
      prevOrderIdRef.current = orderId;
      
      // Use setTimeout to batch state updates outside effect
      const timer = setTimeout(() => {
        setData(null);
        setError(null);
        setActiveTab('items');
        setReturnModal(INITIAL_RETURN_MODAL);
        setReturnReason('');
        setProcessingReturn(false);
        setPayments([]);
        setShowDeletedPayments(false);
        setLoadingPayments(false);
        setPaymentModalOpen(false);
        setEditPaymentModal(INITIAL_EDIT_PAYMENT);
        setDeletePaymentId(null);
        setDeletingPayment(false);
        setPermanentDeletePaymentId(null);
        setRestorePaymentId(null);
        setPaymentTimeline(INITIAL_TIMELINE);
        
        fetchOrderDetail(orderId);
      }, 0);
      
      return () => clearTimeout(timer);
    }
    
    if (!isOpen) {
      prevOrderIdRef.current = null;
    }
  }, [isOpen, orderId, fetchOrderDetail]);

  // ─── ESC key handler ────────────────────────────────────────────────
  useEffect(() => {
    const handleEsc = (e: KeyboardEvent) => {
      if (
        e.key === 'Escape' &&
        isOpen &&
        !paymentModalOpen &&
        !editPaymentModal.isOpen &&
        !deletePaymentId &&
        !returnModal.isOpen &&
        !paymentTimeline.isOpen &&
        !permanentDeletePaymentId &&
        !restorePaymentId
      ) {
        onClose();
      }
    };
    window.addEventListener('keydown', handleEsc);
    return () => window.removeEventListener('keydown', handleEsc);
  }, [
    isOpen,
    paymentModalOpen,
    editPaymentModal.isOpen,
    deletePaymentId,
    returnModal.isOpen,
    paymentTimeline.isOpen,
    permanentDeletePaymentId,
    restorePaymentId,
    onClose,
  ]);

  // ─── Handlers ───────────────────────────────────────────────────────
  const handleItemReturn = useCallback(
    async (itemId: string) => {
      if (!returnReason.trim()) return;
      setProcessingReturn(true);
      try {
        const res = await fetch(`/api/orders/items/${itemId}/return`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ return_reason: returnReason.trim() }),
        });
        if (res.ok) {
          setReturnModal(INITIAL_RETURN_MODAL);
          setReturnReason('');
          if (orderId) {
            fetchOrderDetail(orderId);
          }
          if (onDataChange) {
            onDataChange();
          }
          toast.success('Item marked as returned');
        } else {
          const data = await res.json();
          toast.error(getApiErrorMessage(data, 'Failed to process return'));
        }
      } catch {
        toast.error('Network error');
      } finally {
        setProcessingReturn(false);
      }
    },
    [returnReason, orderId, fetchOrderDetail, onDataChange]
  );

  const handlePaymentRecord = useCallback(
    async (paymentData: {
      payment_method: string;
      transaction_id: string;
      amount: number;
      status: string;
      note: string;
      item_id?: string | null;
      screenshot_public_id?: string | null;
      screenshot_url?: string | null;
    }) => {
      if (!orderId) return;
      try {
        const formData = new FormData();
        formData.append('payment_method', paymentData.payment_method);
        formData.append('transaction_id', paymentData.transaction_id || '');
        formData.append('amount', String(paymentData.amount));
        formData.append('status', paymentData.status);
        formData.append('note', paymentData.note);
        if (paymentData.item_id) formData.append('item_id', paymentData.item_id);
        if (paymentData.screenshot_url) {
          formData.append('screenshot_url', paymentData.screenshot_url);
        }

        const res = await fetch(`/api/orders/${orderId}/payments`, {
          method: 'POST',
          body: formData,
        });

        if (res.ok) {
          setPaymentModalOpen(false);
          fetchPayments(showDeletedPayments);
          fetchOrderDetail(orderId);
          onDataChange?.();
          toast.success('Payment recorded');
        } else {
          const data = await res.json();
          toast.error(getApiErrorMessage(data, 'Failed to record payment'));
        }
      } catch {
        toast.error('Network error');
      }
    },
    [orderId, fetchPayments, fetchOrderDetail, showDeletedPayments, onDataChange]
  );

  const handleFullOrderRefund = useCallback(
    async (refundData: {
      payment_method: string;
      transaction_id: string;
      note: string;
      screenshot_url: string;
    }) => {
      if (!orderId) return;
      try {
        const formData = new FormData();
        formData.append('payment_method', refundData.payment_method);
        formData.append('transaction_id', refundData.transaction_id || '');
        formData.append('note', refundData.note);
        formData.append('screenshot_url', refundData.screenshot_url);

        const res = await fetch(`/api/orders/${orderId}/refund`, {
          method: 'POST',
          body: formData,
        });

        const data = await res.json();
        if (res.ok && data.success) {
          setRefundModalOpen(false);
          fetchPayments(showDeletedPayments);
          fetchOrderDetail(orderId);
          onDataChange?.();
          toast.success(data.message || 'Refund processed');
        } else {
          toast.error(getApiErrorMessage(data, 'Failed to process refund'));
        }
      } catch {
        toast.error('Network error');
      }
    },
    [orderId, fetchPayments, fetchOrderDetail, showDeletedPayments, onDataChange]
  );

  const handleEditPayment = useCallback((payment: PaymentRecord) => {
    setEditPaymentModal({ isOpen: true, payment });
  }, []);

  const handleDeletePayment = useCallback(async () => {
    if (!deletePaymentId || !orderId) return;
    setDeletingPayment(true);
    try {
      const res = await fetch(`/api/orders/${orderId}/payments/${deletePaymentId}`, {
        method: 'DELETE',
      });
      if (res.ok) {
        setDeletePaymentId(null);
        fetchPayments(showDeletedPayments);
        fetchOrderDetail(orderId);
        onDataChange?.();
        toast.success('Payment record deleted');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to delete'));
      }
    } catch {
      toast.error('Network error');
    } finally {
      setDeletingPayment(false);
    }
  }, [deletePaymentId, orderId, fetchPayments, fetchOrderDetail, showDeletedPayments, onDataChange]);

  const handleRestorePayment = useCallback(async () => {
    if (!restorePaymentId || !orderId) return;
    try {
      const res = await fetch(`/api/orders/${orderId}/payments/${restorePaymentId}/restore`, {
        method: 'POST',
      });
      if (res.ok) {
        setRestorePaymentId(null);
        fetchPayments(showDeletedPayments);
        fetchOrderDetail(orderId);
        onDataChange?.();
        toast.success('Payment record restored');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to restore'));
      }
    } catch {
      toast.error('Network error');
    }
  }, [restorePaymentId, orderId, fetchPayments, fetchOrderDetail, showDeletedPayments, onDataChange]);

  const handlePermanentDeletePayment = useCallback(async () => {
    if (!permanentDeletePaymentId || !orderId) return;
    try {
      const res = await fetch(
        `/api/orders/${orderId}/payments/${permanentDeletePaymentId}/permanent`,
        { method: 'DELETE' }
      );
      if (res.ok) {
        setPermanentDeletePaymentId(null);
        fetchPayments(showDeletedPayments);
        fetchOrderDetail(orderId);
        onDataChange?.();
        toast.success('Payment record permanently deleted');
      } else {
        const data = await res.json();
        toast.error(getApiErrorMessage(data, 'Failed to delete'));
      }
    } catch {
      toast.error('Network error');
    }
  }, [permanentDeletePaymentId, orderId, fetchPayments, fetchOrderDetail, showDeletedPayments, onDataChange]);

  const handlePaymentSaved = useCallback(() => {
    setEditPaymentModal(INITIAL_EDIT_PAYMENT);
    fetchPayments(showDeletedPayments);
    if (orderId) fetchOrderDetail(orderId);
    onDataChange?.();
  }, [orderId, fetchPayments, fetchOrderDetail, showDeletedPayments, onDataChange]);

  const handleToggleDeletedPayments = useCallback(() => {
    setShowDeletedPayments((prev) => {
      fetchPayments(!prev);
      return !prev;
    });
  }, [fetchPayments]);

  // ─── Derived data ────────────────────────────────────────────────────
  const order = data?.order;
  const items = data?.items || [];
  const statusHistory = data?.status_history || [];
  const billingAddress = data?.billing_address;
  const activeItems = items.filter((i) => !i.is_returned);
  const returnedItems = items.filter((i) => i.is_returned);
  const hasRefundedPayment = payments.some((p) => p.status === 'refunded' && !p.deleted_at);
  const canRefundFullOrder = Boolean(canRefund) && activeItems.length === 0 && returnedItems.length > 0 && !hasRefundedPayment;

  const itemsSubtotal = activeItems.reduce((sum, item) => sum + Number(item.subtotal), 0);
  const itemsDiscount = activeItems.reduce((sum, item) => sum + Number(item.discount_amount), 0);
  const couponDiscount = Number(order?.coupon_discount_amount || 0);
  const deliveryFee = Number(order?.delivery_fee || 0);
  const taxAmount = Number(order?.tax_amount || 0);
  const grandTotal = calculateOrderGrandTotal({ itemsSubtotal, itemsDiscount, couponDiscount, deliveryFee, taxAmount });

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-start justify-center p-4 overflow-y-auto"
      style={{ background: 'rgba(0,0,0,0.5)' }}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className="rounded-xl w-full max-w-4xl my-8"
        style={{
          background: 'var(--color-surface)',
          border: '1px solid var(--color-border)',
          boxShadow: 'var(--shadow-card-lg)',
        }}
      >
        {/* ─── Header ─────────────────────────────────────────────── */}
        <div
          className="flex items-center justify-between p-6 border-b"
          style={{ borderColor: 'var(--color-border)' }}
        >
          <div className="flex items-center gap-4">
            <div
              className="w-10 h-10 rounded-lg flex items-center justify-center"
              style={{ background: 'var(--color-cta-light)' }}
            >
              <Package size={20} style={{ color: 'var(--color-cta)' }} />
            </div>
            <div>
              <h2 className="text-lg font-bold" style={{ color: 'var(--color-text)' }}>
                {order?.order_number || 'Loading...'}
              </h2>
              <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                {order ? new Date(order.created_at).toLocaleString() : ''}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            {order && <StatusBadge status={order.status} />}
            {canExport && (
              <button
                onClick={handleGenerateInvoice}
                disabled={generatingInvoice}
                className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium transition-all"
                style={{ background: 'var(--color-surface-alt)', color: 'var(--color-text)', border: '1px solid var(--color-border)' }}
                title="Generate Invoice"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                  <polyline points="14 2 14 8 20 8"/>
                  <line x1="16" y1="13" x2="8" y2="13"/>
                  <line x1="16" y1="17" x2="8" y2="17"/>
                  <polyline points="10 9 9 9 8 9"/>
                </svg>
                {generatingInvoice ? 'Generating...' : 'Invoice'}
              </button>
            )}
            {canUpdateStatus && order && onStatusChange && (
              <button
                onClick={() => onStatusChange(order.id)}
                className="p-2 rounded-lg transition-colors hover:bg-surface-alt"
                style={{ color: 'var(--color-cta)' }}
                title="Change Status"
              >
                <RefreshCw size={18} />
              </button>
            )}
            <button
              onClick={onClose}
              className="p-2 rounded-lg transition-colors hover:bg-surface-alt"
              style={{ color: 'var(--color-text-secondary)' }}
            >
              <X size={20} />
            </button>
          </div>
        </div>

        {/* ─── Content ─────────────────────────────────────────────── */}
        {loading ? (
          <div className="p-6 space-y-4">
            {Array.from({ length: 6 }).map((_, i) => (
              <div key={i} className="skeleton h-16 w-full" />
            ))}
          </div>
        ) : error ? (
          <div className="p-12 text-center">
            <p className="text-red-500 mb-4">{error}</p>
            <button
              onClick={() => orderId && fetchOrderDetail(orderId)}
              className="px-4 py-2 rounded-lg text-sm font-medium text-white"
              style={{ background: 'var(--color-cta)' }}
            >
              Retry
            </button>
          </div>
        ) : order ? (
          <div className="p-6">
            {/* ─── Customer & Payment Info ────────────────────────── */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
              {/* Customer */}
              <div
                className="p-4 rounded-lg"
                style={{
                  background: 'var(--color-surface-alt)',
                  border: '1px solid var(--color-border)',
                }}
              >
                <div className="flex items-center gap-2 mb-3">
                  <User size={16} style={{ color: 'var(--color-text-secondary)' }} />
                  <h4 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>
                    Customer
                  </h4>
                </div>
                <p className="font-medium text-sm" style={{ color: 'var(--color-text)' }}>
                  {order.user_name}
                </p>
                <p className="text-xs" style={{ color: 'var(--color-text-secondary)' }}>
                  {order.user_email}
                </p>
              </div>

              {/* Payment */}
              <div
                className="p-4 rounded-lg"
                style={{
                  background: 'var(--color-surface-alt)',
                  border: '1px solid var(--color-border)',
                }}
              >
                <div className="flex items-center gap-2 mb-3">
                  <CreditCard size={16} style={{ color: 'var(--color-text-secondary)' }} />
                  <h4 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>
                    Payment
                  </h4>
                </div>
                <p className="text-sm" style={{ color: 'var(--color-text)' }}>
                  {PAYMENT_METHOD_LABELS[order.payment_method]}
                </p>
                <p
                  className="text-xs capitalize font-medium"
                  style={{ color: PAYMENT_STATUS_COLORS[order.payment_status] }}
                >
                  {order.payment_status.replace(/_/g, ' ')}
                </p>
              </div>

              {/* Coupon */}
              {order.coupon_code && (
                <div
                  className="p-4 rounded-lg"
                  style={{
                    background: 'var(--color-surface-alt)',
                    border: '1px solid var(--color-border)',
                  }}
                >
                  <div className="flex items-center gap-2 mb-3">
                    <Tag size={16} style={{ color: 'var(--color-text-secondary)' }} />
                    <h4 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>
                      Coupon
                    </h4>
                  </div>
                  <p
                    className="font-mono font-bold text-sm"
                    style={{ color: 'var(--color-cta)' }}
                  >
                    {order.coupon_code}
                  </p>
                  <p className="text-xs" style={{ color: 'var(--color-success)' }}>
                    - {formatAmount(couponDiscount)}
                  </p>
                </div>
              )}
            </div>

            {/* ─── Addresses ──────────────────────────────────────── */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
              {billingAddress && (
                <div
                  className="p-4 rounded-lg"
                  style={{
                    background: 'var(--color-surface-alt)',
                    border: '1px solid var(--color-border)',
                  }}
                >
                  <div className="flex items-center gap-2 mb-3">
                    <MapPin size={16} style={{ color: 'var(--color-text-secondary)' }} />
                    <h4 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>
                      Billing Address
                    </h4>
                  </div>
                  <div className="space-y-1 text-sm" style={{ color: 'var(--color-text-secondary)' }}>
                    <p className="font-medium" style={{ color: 'var(--color-text)' }}>
                      {billingAddress.full_name}
                    </p>
                    <p>{billingAddress.phone}</p>
                    <p>{billingAddress.address_line1}</p>
                    <p>
                      {billingAddress.city}, {billingAddress.state} {billingAddress.postal_code}
                    </p>
                  </div>
                </div>
              )}
              {order.shipping_full_name && (
                <div
                  className="p-4 rounded-lg"
                  style={{
                    background: 'var(--color-surface-alt)',
                    border: '1px solid var(--color-border)',
                  }}
                >
                  <div className="flex items-center gap-2 mb-3">
                    <Truck size={16} style={{ color: 'var(--color-text-secondary)' }} />
                    <h4 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>
                      Shipping Address
                    </h4>
                  </div>
                  <div className="space-y-1 text-sm" style={{ color: 'var(--color-text-secondary)' }}>
                    <p className="font-medium" style={{ color: 'var(--color-text)' }}>
                      {order.shipping_full_name}
                    </p>
                    <p>{order.shipping_phone}</p>
                    <p>{order.shipping_address_line1}</p>
                    <p>
                      {order.shipping_city}, {order.shipping_state} {order.shipping_postal_code}
                    </p>
                  </div>
                </div>
              )}
            </div>

            {/* ─── Notes ──────────────────────────────────────────── */}
            {(order.customer_notes || order.cancellation_reason) && (
              <div className="space-y-2 mb-6">
                {order.customer_notes && (
                  <div
                    className="p-3 rounded-lg text-sm"
                    style={{ background: 'var(--color-info-light)', color: 'var(--color-info)' }}
                  >
                    <strong>Customer Note:</strong> {order.customer_notes}
                  </div>
                )}
                {order.cancellation_reason && (
                  <div
                    className="p-3 rounded-lg text-sm"
                    style={{
                      background: 'var(--color-danger-light)',
                      color: 'var(--color-danger)',
                    }}
                  >
                    <strong>Cancellation Reason:</strong> {order.cancellation_reason}
                  </div>
                )}
              </div>
            )}

            {/* ─── Tabs ───────────────────────────────────────────── */}
            <div className="border-b mb-4" style={{ borderColor: 'var(--color-border)' }}>
              <div className="flex gap-1">
                <button
                  onClick={() => setActiveTab('items')}
                  className={`px-4 py-2 text-sm font-medium border-b-2 transition-all ${
                    activeTab === 'items'
                      ? 'border-cta text-cta'
                      : 'border-transparent text-text-secondary hover:text-text'
                  }`}
                >
                  Items ({activeItems.length})
                </button>
                <button
                  onClick={() => setActiveTab('timeline')}
                  className={`px-4 py-2 text-sm font-medium border-b-2 transition-all ${
                    activeTab === 'timeline'
                      ? 'border-cta text-cta'
                      : 'border-transparent text-text-secondary hover:text-text'
                  }`}
                >
                  Timeline ({statusHistory.length})
                </button>
                {canViewPayments && (
                  <button
                    onClick={() => {
                      setActiveTab('payments');
                      fetchPayments(showDeletedPayments);
                    }}
                    className={`px-4 py-2 text-sm font-medium border-b-2 transition-all ${
                      activeTab === 'payments'
                        ? 'border-cta text-cta'
                        : 'border-transparent text-text-secondary hover:text-text'
                    }`}
                  >
                    Payments ({payments.length})
                  </button>
                )}
              </div>
            </div>

            {/* ─── Items Tab ──────────────────────────────────────── */}
            {activeTab === 'items' && (
              <div className="space-y-3">
                {activeItems.map((item) => (
                  <div
                    key={item.id}
                    className="p-4 rounded-lg flex items-start gap-4"
                    style={{
                      background: 'var(--color-surface-alt)',
                      border: '1px solid var(--color-border)',
                    }}
                  >
                    <div className="flex-1 min-w-0">
                      <h5 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>
                        {item.product_name}
                      </h5>
                      <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                        SKU: {item.sku}
                      </p>
                      {item.variant_name && (
                        <p className="text-xs" style={{ color: 'var(--color-text-secondary)' }}>
                          Variant: {item.variant_name}
                        </p>
                      )}
                      <div className="flex items-center gap-3 mt-2">
                        <span
                          className="text-xs px-2 py-0.5 rounded"
                          style={{
                            background: 'var(--color-surface)',
                            color: 'var(--color-text-secondary)',
                          }}
                        >
                          Qty: {Number(item.quantity)}
                        </span>
                        <span className="text-sm" style={{ color: 'var(--color-text-tertiary)' }}>
                          {Number(item.quantity)} x {formatAmount(item.unit_price)}
                        </span>
                        {Number(item.compare_price) > 0 && (
                          <span
                            className="text-xs line-through"
                            style={{ color: 'var(--color-text-tertiary)' }}
                          >
                            {formatAmount(item.compare_price)}
                          </span>
                        )}
                      </div>
                      <p className="text-sm font-bold mt-1" style={{ color: 'var(--color-text)' }}>
                        {formatAmount(item.total_price)}
                      </p>
                    </div>
                    {canSingleItemStatus && (
                      <button
                        onClick={() =>
                          setReturnModal({
                            isOpen: true,
                            itemId: item.id,
                            itemName: item.product_name,
                          })
                        }
                        className="p-1.5 rounded-lg text-xs font-medium transition-colors flex items-center gap-1 shrink-0"
                        style={{
                          background: 'var(--color-danger-light)',
                          color: 'var(--color-danger)',
                          border: '1px solid var(--color-danger)',
                        }}
                      >
                        <RotateCcw size={14} /> Return
                      </button>
                    )}
                  </div>
                ))}

                {/* Returned Items */}
                {returnedItems.length > 0 && (
                  <div className="mt-4">
                    <h5
                      className="text-sm font-semibold mb-2"
                      style={{ color: 'var(--color-danger)' }}
                    >
                      Returned Items
                    </h5>
                    {returnedItems.map((item) => (
                      <div
                        key={item.id}
                        className="p-4 rounded-lg mb-2 flex items-start gap-4 opacity-80"
                        style={{
                          background: 'var(--color-danger-light)',
                          border: '1px solid var(--color-danger)',
                        }}
                      >
                        <div className="flex-1">
                          <h5
                            className="text-sm font-semibold"
                            style={{ color: 'var(--color-text)' }}
                          >
                            {item.product_name}
                          </h5>
                          <p className="text-xs" style={{ color: 'var(--color-danger)' }}>
                            Return Reason: {item.return_reason}
                          </p>
                          <p
                            className="text-sm font-bold"
                            style={{ color: 'var(--color-text)' }}
                          >
                            {formatAmount(item.total_price)}
                          </p>
                        </div>
                        <span
                          className="text-xs px-2 py-1 rounded-full shrink-0"
                          style={{ background: 'var(--color-danger)', color: 'white' }}
                        >
                          Returned
                        </span>
                      </div>
                    ))}
                  </div>
                )}

                {/* Totals — only meaningful while at least one item is still
                    active. Once everything on the order is returned,
                    itemsSubtotal is 0 while the order-level coupon/delivery/
                    tax snapshot values are still the original ones, which
                    used to produce a nonsensical negative "Grand Total"
                    (e.g. "PKR -15") — caught live while testing a real
                    refund. A fully-returned order has nothing left to show
                    a running balance for; point to the Payments tab
                    (the real refund record) instead of faking a total. */}
                {activeItems.length > 0 ? (
                  <div
                    className="border-t pt-4 mt-4"
                    style={{ borderColor: 'var(--color-border)' }}
                  >
                    <div className="space-y-1.5 text-sm max-w-xs ml-auto">
                      <div className="flex justify-between">
                        <span style={{ color: 'var(--color-text-secondary)' }}>Subtotal</span>
                        <span style={{ color: 'var(--color-text)' }}>
                          {formatAmount(itemsSubtotal)}
                        </span>
                      </div>
                      {itemsDiscount > 0 && (
                        <div className="flex justify-between">
                          <span style={{ color: 'var(--color-text-secondary)' }}>
                            Item Discounts
                          </span>
                          <span style={{ color: 'var(--color-success)' }}>
                            - {formatAmount(itemsDiscount)}
                          </span>
                        </div>
                      )}
                      {couponDiscount > 0 && (
                        <div className="flex justify-between">
                          <span style={{ color: 'var(--color-text-secondary)' }}>
                            Coupon ({order.coupon_code})
                          </span>
                          <span style={{ color: 'var(--color-success)' }}>
                            - {formatAmount(couponDiscount)}
                          </span>
                        </div>
                      )}
                      <div className="flex justify-between">
                        <span style={{ color: 'var(--color-text-secondary)' }}>Delivery Fee</span>
                        <span style={{ color: 'var(--color-text)' }}>
                          {formatAmount(deliveryFee)}
                        </span>
                      </div>
                      {taxAmount > 0 && (
                        <div className="flex justify-between">
                          <span style={{ color: 'var(--color-text-secondary)' }}>
                            Tax / GST ({Number(order.tax_percentage || 0)}%)
                          </span>
                          <span style={{ color: 'var(--color-text)' }}>
                            {formatAmount(taxAmount)}
                          </span>
                        </div>
                      )}
                      <div
                        className="flex justify-between font-bold text-base pt-2 border-t"
                        style={{ borderColor: 'var(--color-border)' }}
                      >
                        <span style={{ color: 'var(--color-text)' }}>Grand Total</span>
                        <span style={{ color: 'var(--color-cta)' }}>
                          {formatAmount(grandTotal)}
                        </span>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div
                    className="border-t pt-4 mt-4 text-sm text-center"
                    style={{ borderColor: 'var(--color-border)', color: 'var(--color-text-secondary)' }}
                  >
                    {hasRefundedPayment
                      ? 'All items on this order have been returned. See the Payments tab for what was actually refunded.'
                      : 'All items on this order have been returned. Use "Refund Full Order" on the Payments tab to refund everything at once.'}
                  </div>
                )}
              </div>
            )}

            {/* ─── Timeline Tab ───────────────────────────────────── */}
            {activeTab === 'timeline' && (
              <div className="pl-2">
                {statusHistory.length > 0 ? (
                  statusHistory.map((entry, index) => (
                    <TimelineItem
                      key={entry.id || index}
                      entry={entry}
                      isLast={index === statusHistory.length - 1}
                    />
                  ))
                ) : (
                  <p
                    className="text-sm text-center py-8"
                    style={{ color: 'var(--color-text-tertiary)' }}
                  >
                    No timeline available
                  </p>
                )}
              </div>
            )}

            {/* ─── Payments Tab ───────────────────────────────────── */}
            {activeTab === 'payments' && (
              <div>
                <div className="flex items-center gap-2 mb-4">
                  {canManagePayments && (
                    <button
                      onClick={() => setPaymentModalOpen(true)}
                      className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white"
                      style={{ background: 'var(--color-cta)' }}
                    >
                      <DollarSign size={16} /> Record Payment
                    </button>
                  )}
                  {canRefundFullOrder && (
                    <button
                      onClick={() => setRefundModalOpen(true)}
                      className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white"
                      style={{ background: 'var(--color-danger)' }}
                    >
                      <DollarSign size={16} /> Refund Full Order
                    </button>
                  )}
                  {canViewDeletedPayments && (
                    <button
                      onClick={handleToggleDeletedPayments}
                      className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border"
                      style={{
                        borderColor: 'var(--color-border)',
                        color: 'var(--color-text)',
                        background: showDeletedPayments
                          ? 'var(--color-danger-light)'
                          : 'var(--color-surface)',
                      }}
                    >
                      {showDeletedPayments ? 'Show Active' : 'Show Deleted'}
                    </button>
                  )}
                </div>

                {loadingPayments ? (
                  <div className="space-y-3">
                    {Array.from({ length: 3 }).map((_, i) => (
                      <div key={i} className="skeleton h-16 w-full rounded-lg" />
                    ))}
                  </div>
                ) : payments.length > 0 ? (
                  <div className="space-y-3">
                    {payments.map((p) => (
                      <div
                        key={p.id}
                        className={`p-4 rounded-lg ${p.deleted_at ? 'opacity-60' : ''}`}
                        style={{
                          background: p.deleted_at
                            ? 'var(--color-danger-light)'
                            : 'var(--color-surface-alt)',
                          border: `1px solid ${
                            p.deleted_at ? 'var(--color-danger)' : 'var(--color-border)'
                          }`,
                        }}
                      >
                        <div className="flex justify-between items-start">
                          <div className="flex-1 min-w-0">
                            <p
                              className="text-sm font-medium capitalize"
                              style={{ color: 'var(--color-text)' }}
                            >
                              {p.payment_method.replace(/_/g, ' ')}
                            </p>
                            {p.transaction_id && (
                              <p
                                className="text-xs font-mono"
                                style={{ color: 'var(--color-text-tertiary)' }}
                              >
                                TXN: {p.transaction_id}
                              </p>
                            )}
                            {p.note && (
                              <p
                                className="text-xs mt-1"
                                style={{ color: 'var(--color-text-secondary)' }}
                              >
                                {p.note}
                              </p>
                            )}
                            {p.screenshot_url && (
                              <div className="mt-2 rounded-lg overflow-hidden relative max-w-xs max-h-32 cursor-pointer"
                                onClick={() => window.open(p.screenshot_url!, '_blank')}
                              >
                                <Image
                                  src={p.screenshot_url}
                                  alt="Payment Screenshot"
                                  width={320}
                                  height={128}
                                  className="object-cover w-full h-32"
                                  unoptimized={p.screenshot_url?.includes('res.cloudinary.com') ? false : true}
                                />
                                <div className="absolute inset-0 bg-black/0 hover:bg-black/10 transition-colors flex items-center justify-center">
                                  <span className="text-white text-xs opacity-0 hover:opacity-100 transition-opacity bg-black/50 px-2 py-1 rounded">
                                    Click to view full size
                                  </span>
                                </div>
                              </div>
                            )}
                            {p.deleted_at && (
                              <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>
                                Deleted: {new Date(p.deleted_at).toLocaleString()}
                              </p>
                            )}
                          </div>
                          <div className="flex items-start gap-2 shrink-0">
                            <div className="text-right">
                              <p
                                className="text-sm font-bold"
                                style={{ color: 'var(--color-text)' }}
                              >
                                {formatAmount(p.amount)}
                              </p>
                              <span
                                className="text-xs px-2 py-0.5 rounded-full capitalize"
                                style={{
                                  background:
                                    p.status === 'success'
                                      ? 'rgba(16,185,129,0.1)'
                                      : p.status === 'failed'
                                      ? 'rgba(239,68,68,0.1)'
                                      : 'rgba(245,158,11,0.1)',
                                  color:
                                    p.status === 'success'
                                      ? '#10B981'
                                      : p.status === 'failed'
                                      ? '#EF4444'
                                      : '#F59E0B',
                                }}
                              >
                                {p.status}
                              </span>
                            </div>
                            <div className="flex flex-col gap-1">
                              {/* Timeline - always visible if permitted */}
                              {canViewPaymentTimeline && (
                                <button
                                  onClick={() =>
                                    openPaymentTimeline(p.id, p.payment_method)
                                  }
                                  className="p-1 rounded hover:bg-surface-alt transition-colors"
                                  style={{ color: 'var(--color-text-secondary)' }}
                                  title="Payment Timeline"
                                >
                                  <History size={14} />
                                </button>
                              )}

                              {/* Edit - only for active records */}
                              {!p.deleted_at && canManagePayments && (
                                <button
                                  onClick={() => handleEditPayment(p)}
                                  className="p-1 rounded hover:bg-surface-alt transition-colors"
                                  style={{ color: 'var(--color-info)' }}
                                  title="Edit Payment"
                                >
                                  <Pencil size={14} />
                                </button>
                              )}

                              {/* Delete - only for active records */}
                              {!p.deleted_at && canDeletePayments && (
                                <button
                                  onClick={() => setDeletePaymentId(p.id)}
                                  className="p-1 rounded hover:bg-surface-alt transition-colors"
                                  style={{ color: 'var(--color-danger)' }}
                                  title="Delete Payment"
                                >
                                  <Trash2 size={14} />
                                </button>
                              )}

                              {/* Restore - only for deleted records */}
                              {p.deleted_at && canRestorePayments && (
                                <button
                                  onClick={() => setRestorePaymentId(p.id)}
                                  className="p-1 rounded hover:bg-surface-alt transition-colors"
                                  style={{ color: 'var(--color-success)' }}
                                  title="Restore Payment"
                                >
                                  <RotateCw size={14} />
                                </button>
                              )}

                              {/* Permanent Delete - only for deleted records */}
                              {p.deleted_at && canPermanentDeletePayments && (
                                <button
                                  onClick={() => setPermanentDeletePaymentId(p.id)}
                                  className="p-1 rounded hover:bg-surface-alt transition-colors"
                                  style={{ color: 'var(--color-danger)' }}
                                  title="Permanent Delete"
                                >
                                  <Trash2 size={14} />
                                </button>
                              )}
                            </div>
                          </div>
                        </div>
                        <p
                          className="text-xs mt-2"
                          style={{ color: 'var(--color-text-tertiary)' }}
                        >
                          {new Date(p.created_at).toLocaleString()}
                        </p>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p
                    className="text-sm text-center py-8"
                    style={{ color: 'var(--color-text-tertiary)' }}
                  >
                    No payment records found
                  </p>
                )}
              </div>
            )}
          </div>
        ) : null}

        {/* ─── Return Reason Modal ──────────────────────────────────── */}
        {returnModal.isOpen && (
          <div
            className="fixed inset-0 z-60 flex items-center justify-center p-4"
            style={{ background: 'rgba(0,0,0,0.5)' }}
          >
            <div
              className="rounded-lg p-6 w-full max-w-sm max-h-[90vh] overflow-y-auto"
              style={{
                background: 'var(--color-surface)',
                border: '1px solid var(--color-border)',
              }}
            >
              <h4 className="font-semibold mb-2" style={{ color: 'var(--color-text)' }}>
                Return Item
              </h4>
              <p className="text-sm mb-4" style={{ color: 'var(--color-text-secondary)' }}>
                {returnModal.itemName}
              </p>
              <textarea
                value={returnReason}
                onChange={(e) => setReturnReason(e.target.value)}
                placeholder="Enter return reason (required)..."
                rows={3}
                className="w-full px-3 py-2 rounded-lg text-sm outline-none mb-4 resize-none"
                style={{
                  background: 'var(--color-surface-alt)',
                  border: '1px solid var(--color-border)',
                  color: 'var(--color-text)',
                }}
              />
              <div className="flex gap-2 justify-end">
                <button
                  onClick={() => {
                    setReturnModal(INITIAL_RETURN_MODAL);
                    setReturnReason('');
                  }}
                  className="px-4 py-2 rounded-lg text-sm"
                  style={{
                    background: 'var(--color-surface-alt)',
                    color: 'var(--color-text)',
                    border: '1px solid var(--color-border)',
                  }}
                >
                  Cancel
                </button>
                <button
                  onClick={() => returnModal.itemId && handleItemReturn(returnModal.itemId)}
                  disabled={!returnReason.trim() || processingReturn}
                  className="px-4 py-2 rounded-lg text-sm text-white disabled:opacity-50"
                  style={{ background: 'var(--color-danger)' }}
                >
                  {processingReturn ? 'Processing...' : 'Mark Returned'}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* ─── Payment Record Modal ────────────────────────────────── */}
        <PaymentModal
          isOpen={paymentModalOpen}
          orderNumber={order?.order_number || ''}
          currentPaymentStatus={order?.payment_status || 'pending'}
          returnedItems={returnedItems.map((item) => ({
            id: item.id,
            product_name: item.product_name,
            total_price: Number(item.total_price),
            variant_name: item.variant_name,
          }))}
          onClose={() => setPaymentModalOpen(false)}
          onConfirm={handlePaymentRecord}
        />

        {/* ─── Refund Full Order Modal ─────────────────────────────── */}
        <RefundFullOrderModal
          isOpen={refundModalOpen}
          orderNumber={order?.order_number || ''}
          itemCount={returnedItems.length}
          onClose={() => setRefundModalOpen(false)}
          onConfirm={handleFullOrderRefund}
        />

        {/* ─── Edit Payment Modal ───────────────────────────────────── */}
        <EditPaymentModal
          isOpen={editPaymentModal.isOpen}
          payment={editPaymentModal.payment}
          orderId={orderId || ''}
          onClose={() => setEditPaymentModal(INITIAL_EDIT_PAYMENT)}
          onSaved={handlePaymentSaved}
        />

        {/* ─── Delete Payment Confirmation ──────────────────────────── */}
        {deletePaymentId && (
          <div
            className="fixed inset-0 z-60 flex items-center justify-center p-4"
            style={{ background: 'rgba(0,0,0,0.5)' }}
          >
            <div
              className="rounded-lg p-6 w-full max-w-sm max-h-[90vh] overflow-y-auto"
              style={{
                background: 'var(--color-surface)',
                border: '1px solid var(--color-border)',
              }}
            >
              <h4 className="font-semibold mb-2" style={{ color: 'var(--color-text)' }}>
                Delete Payment Record
              </h4>
              <p className="text-sm mb-4" style={{ color: 'var(--color-text-secondary)' }}>
                This will move the payment record to deleted items. You can restore it later.
              </p>
              <div className="flex gap-2 justify-end">
                <button
                  onClick={() => setDeletePaymentId(null)}
                  className="px-4 py-2 rounded-lg text-sm"
                  style={{
                    background: 'var(--color-surface-alt)',
                    color: 'var(--color-text)',
                    border: '1px solid var(--color-border)',
                  }}
                >
                  Cancel
                </button>
                <button
                  onClick={handleDeletePayment}
                  disabled={deletingPayment}
                  className="px-4 py-2 rounded-lg text-sm text-white disabled:opacity-50"
                  style={{ background: 'var(--color-danger)' }}
                >
                  {deletingPayment ? 'Deleting...' : 'Delete'}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* ─── Restore Payment Confirmation ──────────────────────────── */}
        {restorePaymentId && (
          <div
            className="fixed inset-0 z-60 flex items-center justify-center p-4"
            style={{ background: 'rgba(0,0,0,0.5)' }}
          >
            <div
              className="rounded-lg p-6 w-full max-w-sm max-h-[90vh] overflow-y-auto"
              style={{
                background: 'var(--color-surface)',
                border: '1px solid var(--color-border)',
              }}
            >
              <h4 className="font-semibold mb-2" style={{ color: 'var(--color-text)' }}>
                Restore Payment Record
              </h4>
              <p className="text-sm mb-4" style={{ color: 'var(--color-text-secondary)' }}>
                Restore this deleted payment record to active?
              </p>
              <div className="flex gap-2 justify-end">
                <button
                  onClick={() => setRestorePaymentId(null)}
                  className="px-4 py-2 rounded-lg text-sm"
                  style={{
                    background: 'var(--color-surface-alt)',
                    color: 'var(--color-text)',
                    border: '1px solid var(--color-border)',
                  }}
                >
                  Cancel
                </button>
                <button
                  onClick={handleRestorePayment}
                  className="px-4 py-2 rounded-lg text-sm text-white"
                  style={{ background: 'var(--color-success)' }}
                >
                  Restore
                </button>
              </div>
            </div>
          </div>
        )}

        {/* ─── Permanent Delete Confirmation ────────────────────────── */}
        {permanentDeletePaymentId && (
          <div
            className="fixed inset-0 z-60 flex items-center justify-center p-4"
            style={{ background: 'rgba(0,0,0,0.5)' }}
          >
            <div
              className="rounded-lg p-6 w-full max-w-sm max-h-[90vh] overflow-y-auto"
              style={{
                background: 'var(--color-surface)',
                border: '1px solid var(--color-border)',
              }}
            >
              <h4 className="font-semibold mb-2" style={{ color: 'var(--color-text)' }}>
                Permanently Delete Payment
              </h4>
              <p className="text-sm mb-4" style={{ color: 'var(--color-text-secondary)' }}>
                This action cannot be undone. Are you absolutely sure?
              </p>
              <div className="flex gap-2 justify-end">
                <button
                  onClick={() => setPermanentDeletePaymentId(null)}
                  className="px-4 py-2 rounded-lg text-sm"
                  style={{
                    background: 'var(--color-surface-alt)',
                    color: 'var(--color-text)',
                    border: '1px solid var(--color-border)',
                  }}
                >
                  Cancel
                </button>
                <button
                  onClick={handlePermanentDeletePayment}
                  className="px-4 py-2 rounded-lg text-sm text-white"
                  style={{ background: 'var(--color-danger)' }}
                >
                  Delete Forever
                </button>
              </div>
            </div>
          </div>
        )}

        {/* ─── Payment Timeline Modal ────────────────────────────────── */}
        <CommonTimelineModal
          isOpen={paymentTimeline.isOpen}
          onClose={() => setPaymentTimeline(INITIAL_TIMELINE)}
          entityType="order_payment"
          entityId={paymentTimeline.paymentId ?? ''}
          title={`${paymentTimeline.paymentMethod ? paymentTimeline.paymentMethod.replace(/_/g, ' ') + ' ' : ''}Payment Timeline`}
        />
      </div>
    </div>
  );
}