'use client';

import DateRangeFilter from '@/components/admin/DateRangeFilter';
import ConfirmDialog from '@/components/ConfirmDialog';
import GenericToast from '@/components/GenericToast';
import clsx from 'clsx';
import { format } from 'date-fns';
import { motion } from 'framer-motion';
import {
    Check,
    ChevronDown,
    ChevronLeft,
    ChevronRight,
    Clock,
    DollarSign,
    Download,
    Eye,
    Loader2,
    Mail,
    RefreshCw,
    RotateCcw,
    Search,
    ShoppingBag,
    X
} from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import {
    getBuyRequests,
    processManualPayment,
    resendLicenseEmail,
    sendManualPaymentInstructionsEmail,
    sendPaymentLinkEmail,
    updateBuyRequestPrice,
    updateBuyRequestStatus
} from './buy-requests-actions';

interface BuyRequest {
    id: number;
    customerName: string;
    customerEmail: string;
    planId: string;
    status: string;
    customPrice: number | null;
    customLicenseDurationDays: number | null;
    customMaxActivations: number | null;
    emailSentAt: Date | null;
    submissionAt: Date | null;
    licenseSentAt: Date | null;
    transactionId: string | null;
    manualReceiptUrl: string | null;
    createdAt: Date;
    updatedAt: Date | null;
}

const statuses = [
    { label: 'All Statuses', value: 'ALL' },
    { label: 'Pending', value: 'PENDING' },
    { label: 'Processing', value: 'PROCESSING' },
    { label: 'Completed', value: 'COMPLETED' },
    { label: 'Cancelled', value: 'CANCELLED' },
];

const pricing_plans = [
    { label: 'All Plans', value: 'ALL' },
    { label: 'Pro', value: 'PRO' },
    { label: 'Enterprise', value: 'ENTERPRISE' },
];

const receiptStatuses = [
    { label: 'All Receipt Status', value: 'ALL' },
    { label: 'No Link Sent', value: 'NO_LINK' },
    { label: 'Waiting for Receipt', value: 'WAITING' },
    { label: 'Receipt Received', value: 'RECEIVED' },
];

const planDefaults: Record<string, { maxActivations: number; duration: number }> = {
    'PRO': { maxActivations: 5, duration: 365 },
    'ENTERPRISE': { maxActivations: 100, duration: 365 }
};

export default function BuyRequestsClient() {
    const [requests, setRequests] = useState<BuyRequest[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState('');
    const [statusFilter, setStatusFilter] = useState('ALL');
    const [planFilter, setPlanFilter] = useState('ALL');
    const [receiptStatusFilter, setReceiptStatusFilter] = useState('ALL');
    const [currentPage, setCurrentPage] = useState(1);
    const [activeTab, setActiveTab] = useState<'overview' | 'manage'>('overview');
    const [itemsPerPage] = useState(10);
    const [toast, setToast] = useState({ isVisible: false, message: '', type: 'success' as 'success' | 'error' });
    const [processingAction, setProcessingAction] = useState<{ id: number; action: 'online' | 'manual' | 'status' | 'price' } | null>(null);
    const [isConfirmOpen, setIsConfirmOpen] = useState(false);
    const [pendingPayment, setPendingPayment] = useState<BuyRequest | null>(null);
    const [isPriceDialogOpen, setIsPriceDialogOpen] = useState(false);
    const [priceEditRequest, setPriceEditRequest] = useState<BuyRequest | null>(null);
    const [newPrice, setNewPrice] = useState('');
    const [newDuration, setNewDuration] = useState('365');
    const [newActivations, setNewActivations] = useState('100');
    const [reviewRequest, setReviewRequest] = useState<BuyRequest | null>(null);
    const [isCancelConfirmOpen, setIsCancelConfirmOpen] = useState(false);
    const [pendingCancelRequest, setPendingCancelRequest] = useState<BuyRequest | null>(null);
    const [fromDate, setFromDate] = useState('');
    const [toDate, setToDate] = useState('');

    useEffect(() => {
        loadRequests();
    }, []);

    const loadRequests = async (options?: { silent?: boolean }) => {
        if (!options?.silent) setLoading(true);
        try {
            const data = await getBuyRequests();
            if (data.success && data.requests) {
                setRequests(data.requests as any);
            } else {
                showToast(data.error || 'Failed to load buy requests', 'error');
            }
        } catch (error) {
            showToast('Failed to load buy requests', 'error');
        } finally {
            if (!options?.silent) setLoading(false);
        }
    };

    const showToast = (message: string, type: 'success' | 'error' = 'success') => {
        setToast({ isVisible: true, message, type });
    };

    const handleStatusChange = (status: string) => {
        setStatusFilter(status);
        setCurrentPage(1);
    };

    const handleDateChange = (key: 'from' | 'to', val: string) => {
        if (key === 'from') setFromDate(val);
        else setToDate(val);
        setCurrentPage(1);
    };

    const filteredRequests = useMemo(() => {
        return requests.filter(req => {
            const matchesSearch = 
                req.customerName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                req.customerEmail.toLowerCase().includes(searchQuery.toLowerCase()) ||
                req.id.toString().includes(searchQuery);
            
            const matchesStatus = statusFilter === 'ALL' || req.status === statusFilter;
            const matchesPlan = planFilter === 'ALL' || req.planId === planFilter;
            
            // Receipt status filter logic
            let matchesReceiptStatus = true;
            if (receiptStatusFilter !== 'ALL') {
                if (receiptStatusFilter === 'NO_LINK') {
                    matchesReceiptStatus = req.emailSentAt == null;
                } else if (receiptStatusFilter === 'WAITING') {
                    matchesReceiptStatus = req.emailSentAt != null && req.submissionAt == null;
                } else if (receiptStatusFilter === 'RECEIVED') {
                    matchesReceiptStatus = req.emailSentAt != null && req.submissionAt != null;
                }
            }
            
            const reqDate = new Date(req.createdAt);
            let matchesDate = true;
            if (fromDate) {
                const from = new Date(fromDate);
                from.setHours(0, 0, 0, 0);
                if (reqDate < from) matchesDate = false;
            }
            if (toDate) {
                const to = new Date(toDate);
                to.setHours(23, 59, 59, 999);
                if (reqDate > to) matchesDate = false;
            }
            
            return matchesSearch && matchesStatus && matchesPlan && matchesReceiptStatus && matchesDate;
        });
    }, [requests, searchQuery, statusFilter, planFilter, receiptStatusFilter, fromDate, toDate]);

    const totalPages = Math.ceil(filteredRequests.length / itemsPerPage);
    const paginatedRequests = filteredRequests.slice(
        (currentPage - 1) * itemsPerPage,
        currentPage * itemsPerPage
    );

    const stats = useMemo(() => {
        const total = requests.length;
        const pending = requests.filter(r => r.status?.toUpperCase() === 'PENDING').length;
        const processing = requests.filter(r => r.status?.toUpperCase() === 'PROCESSING').length;
        const completed = requests.filter(r => r.status?.toUpperCase() === 'COMPLETED' || r.status?.toUpperCase() === 'PAID').length;
        const cancelled = requests.filter(r => r.status?.toUpperCase() === 'CANCELLED').length;
        
        const potentialRevenue = requests
            .filter(r => r.status?.toUpperCase() !== 'CANCELLED')
            .reduce((acc, curr) => acc + (curr.customPrice || 29), 0);
            
        const actualRevenue = requests
            .filter(r => r.status?.toUpperCase() === 'COMPLETED' || r.status?.toUpperCase() === 'PAID')
            .reduce((acc, curr) => acc + (curr.customPrice || 29), 0);

        return { total, pending, processing, completed, cancelled, potentialRevenue, actualRevenue };
    }, [requests]);

    const handleSendPaymentLink = async (request: BuyRequest) => {
        setProcessingAction({ id: request.id, action: 'online' });
        try {
            const result = await sendPaymentLinkEmail(request.id);
            if (result.success) {
                showToast('Online payment link sent');
                loadRequests({ silent: true });
            } else {
                showToast(result.error || 'Failed to send payment link', 'error');
            }
        } catch (error) {
            showToast('An unexpected error occurred', 'error');
        } finally {
            setProcessingAction(null);
        }
    };

    const handleSendManualInstructions = async (request: BuyRequest) => {
        setProcessingAction({ id: request.id, action: 'manual' });
        try {
            const result = await sendManualPaymentInstructionsEmail(request.id);
            if (result.success) {
                showToast('Manual payment instructions sent');
                loadRequests({ silent: true });
            } else {
                showToast(result.error || 'Failed to send instructions', 'error');
            }
        } catch (error) {
            showToast('An unexpected error occurred', 'error');
        } finally {
            setProcessingAction(null);
        }
    };

    const initiatePayment = (request: BuyRequest) => {
        setPendingPayment(request);
        setIsConfirmOpen(true);
    };

    const executePayment = async () => {
        if (!pendingPayment) return;
        
        // Validate Enterprise pricing
        if (pendingPayment.planId === 'ENTERPRISE' && !pendingPayment.customPrice) {
            showToast('Please set a custom price for Enterprise plan first', 'error');
            setIsConfirmOpen(false);
            return;
        }
        
        // Set loading state BEFORE closing dialog so spinner is visible
        setProcessingAction({ id: pendingPayment.id, action: 'status' });
        setIsConfirmOpen(false);
        
        try {
            // Calculate the amount from customPrice or default price (Pro: $29)
            const amount = pendingPayment.customPrice || 29;
            
            const result = await processManualPayment(pendingPayment.id, amount);
            if (result.success) {
                showToast('Payment confirmed and license sent to customer');
                loadRequests({ silent: true });
            } else {
                // Clean up error message for user-friendly display
                let errorMsg = result.error || 'Failed to process payment';
                
                // Shorten email delivery errors
                if (errorMsg.includes('recipients were rejected') || errorMsg.includes('could not deliver')) {
                    errorMsg = 'Email delivery failed - please verify customer email address';
                } else if (errorMsg.includes('smtp') || errorMsg.includes('mail')) {
                    errorMsg = 'Email service error - please try again or contact customer directly';
                }
                
                showToast(errorMsg, 'error');
            }
        } catch (error: any) {
            // Handle unexpected errors with user-friendly message
            let errorMsg = 'An unexpected error occurred';
            if (error?.message?.includes('email') || error?.message?.includes('mail')) {
                errorMsg = 'Email delivery failed - please contact customer directly';
            }
            showToast(errorMsg, 'error');
        } finally {
            setProcessingAction(null);
            setPendingPayment(null);
        }
    };

    const handleCancelRequest = (request: BuyRequest) => {
        setPendingCancelRequest(request);
        setIsCancelConfirmOpen(true);
    };

    const executeCancel = async () => {
        if (!pendingCancelRequest) return;
        setProcessingAction({ id: pendingCancelRequest.id, action: 'status' });
        setIsCancelConfirmOpen(false);
        try {
            const result = await updateBuyRequestStatus(pendingCancelRequest.id, 'CANCELLED');
            if (result.success) {
                showToast('Request cancelled successfully');
                loadRequests({ silent: true });
            } else {
                showToast(result.error || 'Failed to cancel request', 'error');
            }
        } catch (error) {
            showToast('An unexpected error occurred', 'error');
        } finally {
            setProcessingAction(null);
            setPendingCancelRequest(null);
        }
    };

    const handleSetPrice = async () => {
        if (!priceEditRequest || !newPrice) return;
        setProcessingAction({ id: priceEditRequest.id, action: 'price' });
        try {
            const result = await updateBuyRequestPrice(
                priceEditRequest.id, 
                parseFloat(newPrice),
                parseInt(newDuration),
                parseInt(newActivations)
            );
            if (result.success) {
                showToast('Price and terms updated');
                setIsPriceDialogOpen(false);
                loadRequests({ silent: true });
            } else {
                showToast(result.error || 'Failed to update price', 'error');
            }
        } catch (error) {
            showToast('An unexpected error occurred', 'error');
        } finally {
            setProcessingAction(null);
        }
    };

    const handleRestoreRequest = async (request: BuyRequest) => {
        setProcessingAction({ id: request.id, action: 'status' });
        try {
            const result = await updateBuyRequestStatus(request.id, 'PENDING');
            if (result.success) {
                showToast('Request restored to Pending');
                loadRequests({ silent: true });
            } else {
                showToast(result.error || 'Failed to restore request', 'error');
            }
        } catch (error) {
            showToast('An unexpected error occurred', 'error');
        } finally {
            setProcessingAction(null);
        }
    };

    const handleResendLicense = async (request: BuyRequest) => {
        setProcessingAction({ id: request.id, action: 'status' });
        try {
            const result = await resendLicenseEmail(request.id);
            if (result.success) {
                showToast('License email resent successfully');
                loadRequests({ silent: true });
            } else {
                showToast(result.error || 'Failed to resend license email', 'error');
            }
        } catch (error) {
            showToast('An unexpected error occurred', 'error');
        } finally {
            setProcessingAction(null);
        }
    };


    const getStatusStyle = (status: string) => {
        const s = status?.toUpperCase();
        switch (s) {
            case 'PENDING': return 'bg-amber-500/10 text-amber-500 border-amber-500/20';
            case 'SENT': return 'bg-blue-500/10 text-blue-500 border-blue-500/20';
            case 'PROCESSING': 
            case 'REVIEW': 
                return 'bg-purple-500/10 text-purple-500 border-purple-500/20';
            case 'COMPLETED': 
            case 'PAID': 
                return 'bg-green-500/10 text-green-500 border-green-500/20';
            case 'CANCELLED': return 'bg-red-500/10 text-red-500 border-red-500/20';
            default: return 'bg-stone-500/10 text-stone-500 border-stone-500/20';
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex flex-row items-center justify-between gap-4">
                <div>
                   <h1 className="text-3xl font-bold text-white flex items-center gap-3">
                        <ShoppingBag className="text-amber-500" />
                        Buy Requests
                    </h1>
                    <p className="text-gray-400 mt-2 hidden sm:block">View and manage manual purchase requests.</p>
                </div>
                
                <button 
                    onClick={() => loadRequests()}
                    className="p-2 bg-stone-800 rounded-lg hover:bg-stone-700 text-stone-400 hover:text-white transition-colors border border-white/5 shrink-0"
                    title="Refresh Data"
                >
                    <RefreshCw size={20} />
                </button>
            </div>

            {/* Tabs Navigation */}
            <div className="flex border-b border-white/5 mb-6">
                <button
                    onClick={() => setActiveTab('overview')}
                    className={clsx(
                        "px-6 py-3 text-sm font-bold transition-all relative",
                        activeTab === 'overview' ? "text-amber-500" : "text-stone-500 hover:text-stone-300"
                    )}
                >
                    Overview
                    {activeTab === 'overview' && (
                        <motion.div layoutId="activeTab" className="absolute bottom-0 left-0 right-0 h-0.5 bg-amber-500" />
                    )}
                </button>
                <button
                    onClick={() => setActiveTab('manage')}
                    className={clsx(
                        "px-6 py-3 text-sm font-bold transition-all relative",
                        activeTab === 'manage' ? "text-amber-500" : "text-stone-500 hover:text-stone-300"
                    )}
                >
                    Manage Requests
                    {activeTab === 'manage' && (
                        <motion.div layoutId="activeTab" className="absolute bottom-0 left-0 right-0 h-0.5 bg-amber-500" />
                    )}
                </button>
            </div>

            <div className="flex flex-col gap-6 w-full">
                {activeTab === 'overview' ? (
                    /* Overview Content */
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                        <div className="glass p-6 rounded-2xl border border-white/5 flex flex-col gap-1">
                            <span className="text-xs font-bold text-stone-500 uppercase tracking-widest">Total Requests</span>
                            <span className="text-3xl font-bold text-white">{stats.total}</span>
                        </div>
                        <div className="glass p-6 rounded-2xl border border-white/5 flex flex-col gap-1">
                            <span className="text-xs font-bold text-amber-500 uppercase tracking-widest">Active (Pending/Proc)</span>
                            <span className="text-3xl font-bold text-amber-500">{stats.pending + stats.processing}</span>
                        </div>
                        <div className="glass p-6 rounded-2xl border border-white/5 flex flex-col gap-1">
                            <span className="text-xs font-bold text-green-500 uppercase tracking-widest">Completed Sales</span>
                            <span className="text-3xl font-bold text-green-500">{stats.completed}</span>
                        </div>
                        <div className="glass p-6 rounded-2xl border border-white/5 flex flex-col gap-1">
                            <span className="text-xs font-bold text-blue-500 uppercase tracking-widest">Actual Revenue</span>
                            <span className="text-3xl font-bold text-blue-500">${stats.actualRevenue.toFixed(2)}</span>
                        </div>
                        
                        <div className="lg:col-span-4 glass rounded-2xl border border-white/5 overflow-hidden">
                            <div className="p-6 border-b border-white/5">
                                <h3 className="font-bold text-white uppercase text-xs tracking-widest">Pipeline Summary</h3>
                            </div>
                            <div className="p-6 grid grid-cols-1 md:grid-cols-3 gap-8">
                                <div className="space-y-4">
                                    <div className="flex justify-between text-xs">
                                        <span className="text-stone-400">Total Count</span>
                                        <span className="text-white font-bold">{stats.total}</span>
                                    </div>
                                    <div className="flex justify-between text-xs">
                                        <span className="text-stone-400">Conversion Rate</span>
                                        <span className="text-green-500 font-bold">
                                            {stats.total > 0 ? ((stats.completed / (stats.total - stats.cancelled || 1)) * 100).toFixed(1) : 0}%
                                        </span>
                                    </div>
                                </div>
                                <div className="space-y-4">
                                    <div className="flex justify-between text-xs">
                                        <span className="text-stone-400">Potential Gross</span>
                                        <span className="text-amber-500/50 font-bold">${stats.potentialRevenue.toFixed(2)}</span>
                                    </div>
                                    <div className="flex justify-between text-xs">
                                        <span className="text-stone-400">Realized Gross</span>
                                        <span className="text-blue-500 font-bold">${stats.actualRevenue.toFixed(2)}</span>
                                    </div>
                                </div>
                                <div className="space-y-2">
                                     <div className="h-2 w-full bg-white/5 rounded-full overflow-hidden flex">
                                         <div style={{ width: `${(stats.completed / stats.total) * 100}%` }} className="bg-green-500 h-full" />
                                         <div style={{ width: `${(stats.processing / stats.total) * 100}%` }} className="bg-purple-500 h-full" />
                                         <div style={{ width: `${(stats.pending / stats.total) * 100}%` }} className="bg-amber-500 h-full" />
                                     </div>
                                     <div className="flex gap-4 justify-center">
                                         <div className="flex items-center gap-1.5 text-[9px] font-bold text-stone-500"><div className="w-1.5 h-1.5 rounded-full bg-green-500" /> COMPLETED</div>
                                         <div className="flex items-center gap-1.5 text-[9px] font-bold text-stone-500"><div className="w-1.5 h-1.5 rounded-full bg-purple-500" /> PROCESSING</div>
                                         <div className="flex items-center gap-1.5 text-[9px] font-bold text-stone-500"><div className="w-1.5 h-1.5 rounded-full bg-amber-500" /> PENDING</div>
                                     </div>
                                </div>
                            </div>
                        </div>
                        
                        <div className="lg:col-span-4 glass rounded-2xl border border-white/5 overflow-hidden">
                             <div className="p-6 border-b border-white/5 flex justify-between items-center">
                                <h3 className="font-bold text-white uppercase text-xs tracking-widest">Recent Activity</h3>
                                <button onClick={() => setActiveTab('manage')} className="text-[10px] font-bold text-amber-500 hover:text-amber-400 uppercase tracking-widest">View All</button>
                            </div>
                            <div className="divide-y divide-white/5">
                                {requests.slice(0, 5).map(req => (
                                    <div key={req.id} className="p-4 flex items-center justify-between hover:bg-white/[0.02] transition-all">
                                        <div className="flex flex-col">
                                            <span className="text-sm font-bold text-white">{req.customerName}</span>
                                            <span className="text-[10px] text-stone-500 uppercase font-bold">{req.planId} • {format(new Date(req.createdAt), 'MMM dd')}</span>
                                        </div>
                                        <span className={clsx("px-2 py-0.5 rounded-full text-[9px] font-bold border", getStatusStyle(req.status))}>{req.status}</span>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                ) : (
                    /* Manage Content */
                    <div className="glass rounded-2xl border border-white/10 overflow-hidden">
                        <div className="p-4 md:p-6 space-y-6">
                        <div className="flex flex-wrap gap-4 items-end">
                            <div className="relative flex-1 min-w-[200px] sm:min-w-[240px] md:max-w-[320px]">
                                    <label className="text-[10px] font-bold text-stone-500 uppercase tracking-wider ml-1 mb-1 block">Search</label>
                                    <div className="relative">
                                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" size={16} />
                                        <input 
                                            type="text" 
                                            placeholder="Search by ID, name or email..." 
                                            value={searchQuery}
                                            onChange={(e) => setSearchQuery(e.target.value)}
                                            className="w-full bg-black/40 border border-white/10 rounded-lg pl-10 pr-4 py-2 text-sm focus:outline-none focus:border-amber-500 transition-colors text-white"
                                        />
                                    </div>
                                </div>

                                <div className="flex flex-col gap-1.5 min-w-[110px] sm:min-w-[130px]">
                                    <label className="text-[10px] font-bold text-stone-500 uppercase tracking-wider ml-1 block">Status</label>
                                    <div className="relative">
                                        <select 
                                            value={statusFilter}
                                            onChange={(e) => handleStatusChange(e.target.value)}
                                            className="bg-black/40 border border-white/10 rounded-lg pl-3 pr-10 py-2 text-sm focus:outline-none focus:border-amber-500 transition-colors cursor-pointer appearance-none w-full text-white"
                                        >
                                            {statuses.map(s => (
                                                <option key={s.value} value={s.value} className="bg-stone-900">
                                                    {s.label}
                                                </option>
                                            ))}
                                        </select>
                                        <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-stone-500 pointer-events-none" />
                                    </div>
                                </div>

                                <div className="flex flex-col gap-1.5 min-w-[100px] sm:min-w-[120px]">
                                    <label className="text-[10px] font-bold text-stone-500 uppercase tracking-wider ml-1 block">Plan</label>
                                    <div className="relative">
                                        <select 
                                            value={planFilter}
                                            onChange={(e) => setPlanFilter(e.target.value)}
                                            className="bg-black/40 border border-white/10 rounded-lg pl-3 pr-10 py-2 text-sm focus:outline-none focus:border-amber-500 transition-colors cursor-pointer appearance-none w-full text-white"
                                        >
                                            {pricing_plans.map(p => (
                                                <option key={p.value} value={p.value} className="bg-stone-900">
                                                    {p.label}
                                                </option>
                                            ))}
                                        </select>
                                        <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-stone-500 pointer-events-none" />
                                    </div>
                                </div>

                                <div className="flex flex-col gap-1.5 min-w-[130px] sm:min-w-[160px]">
                                    <label className="text-[10px] font-bold text-stone-500 uppercase tracking-wider ml-1 block">Receipt</label>
                                    <div className="relative">
                                        <select 
                                            value={receiptStatusFilter}
                                            onChange={(e) => { setReceiptStatusFilter(e.target.value); setCurrentPage(1); }}
                                            className="bg-black/40 border border-white/10 rounded-lg pl-3 pr-10 py-2 text-sm focus:outline-none focus:border-amber-500 transition-colors cursor-pointer appearance-none w-full text-white"
                                        >
                                            {receiptStatuses.map(s => (
                                                <option key={s.value} value={s.value} className="bg-stone-900">
                                                    {s.label}
                                                </option>
                                            ))}
                                        </select>
                                        <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-stone-500 pointer-events-none" />
                                    </div>
                                </div>

                            <DateRangeFilter 
                                fromDate={fromDate}
                                toDate={toDate}
                                onDateChange={handleDateChange}
                            />
                        </div>

                        <div className="overflow-x-auto rounded-xl border border-white/10 bg-black/20">
                            <table className="w-full text-left min-w-[1000px]">
                                <thead className="bg-white/5 text-[10px] text-stone-400 uppercase tracking-wider whitespace-nowrap border-b border-white/10">
                                    <tr>
                                        <th className="p-4 font-medium">ID</th>
                                        <th className="p-4 font-medium">Date</th>
                                        <th className="p-4 font-medium">Customer</th>
                                        <th className="p-4 font-medium">Plan</th>
                                        <th className="p-4 font-medium">Status</th>
                                        <th className="p-4 font-medium text-center">Payment Link</th>
                                        <th className="p-4 font-medium text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-white/5">
                                    {loading ? (
                                        <tr>
                                            <td colSpan={7} className="p-12 text-center text-stone-500">
                                                <Loader2 size={32} className="animate-spin mx-auto mb-4 opacity-20" />
                                                <p className="text-sm font-medium">Loading buy requests...</p>
                                            </td>
                                        </tr>
                                    ) : paginatedRequests.length === 0 ? (
                                        <tr>
                                            <td colSpan={7} className="p-12 text-center text-stone-500">
                                                <ShoppingBag size={48} className="mx-auto mb-4 opacity-10" />
                                                <p className="text-sm font-medium">No buy requests found matching your criteria.</p>
                                            </td>
                                        </tr>
                                    ) : (
                                        paginatedRequests.map((req) => (
                                            <tr key={req.id} className="group hover:bg-white/[0.02] transition-colors">
                                                <td className="p-4">
                                                    <span className="text-xs font-mono text-stone-500">#{req.id}</span>
                                                </td>
                                                <td className="p-4">
                                                    <div className="flex flex-col">
                                                        <span className="text-sm text-stone-300">{format(new Date(req.createdAt), 'MMM dd, yyyy')}</span>
                                                        <span className="text-[10px] text-stone-500">{format(new Date(req.createdAt), 'HH:mm')}</span>
                                                    </div>
                                                </td>
                                                <td className="p-4">
                                                    <div className="flex flex-col">
                                                        <span className="text-sm font-bold text-white">{req.customerName}</span>
                                                        <span className="text-xs text-stone-400 flex items-center gap-1">
                                                            <Mail size={12} />
                                                            {req.customerEmail}
                                                        </span>
                                                    </div>
                                                </td>
                                                <td className="p-4">
                                                    <div className="flex flex-col">
                                                        <span className="text-xs font-bold text-stone-300">{req.planId}</span>
                                                        <span className={clsx(
                                                            "text-[10px] font-bold flex items-center gap-1",
                                                            (req.planId === 'ENTERPRISE' && !req.customPrice) ? "text-stone-500" : "text-amber-500"
                                                        )}>
                                                            {req.planId === 'ENTERPRISE' && !req.customPrice ? (
                                                                "Pricing Pending"
                                                            ) : (
                                                                <>
                                                                    ${(req.customPrice || 29).toFixed(2)}
                                                                    {!req.customPrice && <span className="text-[8px] text-stone-500 font-normal">(Default)</span>}
                                                                </>
                                                            )}
                                                        </span>
                                                    </div>
                                                </td>
                                                <td className="p-4">
                                                    <div className="flex flex-col gap-1">
                                                        <span className={clsx(
                                                            "px-2.5 py-1 rounded-full text-[10px] font-bold border",
                                                            getStatusStyle(req.status)
                                                        )}>
                                                            {req.status}
                                                        </span>
                                                        {req.emailSentAt != null && req.submissionAt == null && (
                                                            <span className="text-[9px] text-amber-400 font-medium flex items-center gap-1">
                                                                <Clock size={10} />
                                                                Waiting for Receipt
                                                            </span>
                                                        )}
                                                        {req.submissionAt != null && (
                                                            <span className="text-[9px] text-green-400 font-medium flex items-center gap-1">
                                                                <Check size={10} />
                                                                Receipt Received
                                                            </span>
                                                        )}
                                                        {req.status?.toUpperCase() === 'COMPLETED' && !req.licenseSentAt && (
                                                            <span className="text-[9px] text-red-400 font-medium flex items-center gap-1">
                                                                <X size={10} />
                                                                Email Failed
                                                            </span>
                                                        )}
                                                    </div>
                                                </td>
                                                <td className="p-4 text-center">
                                                    <div className="flex flex-col items-center gap-2">
                                                        {req.status?.toUpperCase() === 'COMPLETED' || req.status?.toUpperCase() === 'PAID' ? (
                                                            <span className="text-[10px] text-stone-500 uppercase font-bold">N/A</span>
                                                        ) : req.status?.toUpperCase() === 'CANCELLED' ? (
                                                            <span className="text-[10px] text-red-500/50 uppercase font-bold">Cancelled</span>
                                                        ) : (
                                                            <>
                                                                <div className="flex flex-row gap-1 w-full justify-center">
                                                                    <button
                                                                        onClick={(e) => { e.stopPropagation(); handleSendPaymentLink(req); }}
                                                                        disabled={(!!processingAction && processingAction.id === req.id) || (req.planId === 'ENTERPRISE' && !req.customPrice)}
                                                                        className={clsx(
                                                                            "flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-lg text-[10px] font-bold transition-all border whitespace-nowrap",
                                                                            (req.planId === 'ENTERPRISE' && !req.customPrice)
                                                                                ? "bg-stone-800 text-stone-600 border-white/5 cursor-not-allowed"
                                                                                : "bg-amber-500 text-black border-amber-500 hover:bg-amber-600 shadow-lg shadow-amber-500/10"
                                                                        )}
                                                                        title={req.planId === 'ENTERPRISE' && !req.customPrice ? "Please set a custom price for Enterprise first" : req.emailSentAt ? "Resend Link for Online Payment (Stripe/PayPal)" : "Send Link for Online Payment (Stripe/PayPal)"}
                                                                    >
                                                                        {processingAction?.id === req.id && processingAction?.action === 'online' ? (
                                                                            <Loader2 size={12} className="animate-spin" />
                                                                        ) : (
                                                                            <Mail size={12} />
                                                                        )}
                                                                        Online
                                                                    </button>

                                                                    <button
                                                                        onClick={(e) => { e.stopPropagation(); handleSendManualInstructions(req); }}
                                                                        disabled={(!!processingAction && processingAction.id === req.id) || (req.planId === 'ENTERPRISE' && !req.customPrice)}
                                                                        className={clsx(
                                                                            "flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-lg text-[10px] font-bold transition-all border whitespace-nowrap",
                                                                            (req.planId === 'ENTERPRISE' && !req.customPrice)
                                                                                ? "bg-stone-800 text-stone-600 border-white/5 cursor-not-allowed"
                                                                                : "bg-stone-800 text-stone-300 border-white/10 hover:bg-stone-700"
                                                                        )}
                                                                        title={req.planId === 'ENTERPRISE' && !req.customPrice ? "Please set a custom price for Enterprise first" : req.emailSentAt ? "Resend Bank Details for Manual Payment" : "Send Bank Details for Manual Payment"}
                                                                    >
                                                                        {processingAction?.id === req.id && processingAction?.action === 'manual' ? (
                                                                            <Loader2 size={12} className="animate-spin" />
                                                                        ) : (
                                                                            <DollarSign size={12} />
                                                                        )}
                                                                        Manual
                                                                    </button>
                                                                </div>
                                                                
                                                                {req.emailSentAt != null && (
                                                                    <div className="flex items-center gap-1 text-green-500">
                                                                        <Check size={10} />
                                                                        <span className="text-[9px] font-bold uppercase tracking-wider">Instructions Sent</span>
                                                                    </div>
                                                                )}
                                                            </>
                                                        )}
                                                    </div>
                                                </td>
                                                <td className="p-4 text-right">
                                                    <div className="flex items-center justify-end gap-2">
                                                        {req.submissionAt != null && (
                                                            <button
                                                                onClick={() => setReviewRequest(req)}
                                                                className="p-2 bg-purple-500/10 text-purple-500 hover:bg-purple-500 hover:text-white rounded-lg border border-purple-500/20 transition-all"
                                                                title="Review Receipt"
                                                            >
                                                                <Eye size={16} />
                                                            </button>
                                                        )}
                                                        {req.emailSentAt != null && req.submissionAt == null && (
                                                            <button
                                                                disabled
                                                                className="p-2 bg-stone-800 text-stone-600 rounded-lg border border-white/5 cursor-not-allowed opacity-50"
                                                                title="Waiting for customer to submit receipt"
                                                            >
                                                                <Eye size={16} />
                                                            </button>
                                                        )}
                                                        
                                                        {req.status?.toUpperCase() === 'CANCELLED' && (
                                                            <button
                                                                onClick={() => handleRestoreRequest(req)}
                                                                disabled={processingAction?.id === req.id}
                                                                className="p-2 bg-blue-500/10 text-blue-500 hover:bg-blue-500 hover:text-white rounded-lg border border-blue-500/20 transition-all font-bold flex items-center gap-1"
                                                                title="Restore Request"
                                                            >
                                                                {processingAction?.id === req.id && processingAction?.action === 'status' ? (
                                                                    <Loader2 size={16} className="animate-spin" />
                                                                ) : (
                                                                    <>
                                                                        <RotateCcw size={16} />
                                                                        <span className="text-[10px] uppercase">Restore</span>
                                                                    </>
                                                                )}
                                                            </button>
                                                        )}

                                                        {req.status?.toUpperCase() !== 'COMPLETED' && req.status?.toUpperCase() !== 'PAID' && req.status?.toUpperCase() !== 'CANCELLED' && (
                                                            <>
                                                                <button
                                                                    onClick={() => {
                                                                        setPriceEditRequest(req);
                                                                        setNewPrice((req.customPrice || (req.planId === 'ENTERPRISE' ? '' : '29')).toString());
                                                                        setNewDuration((req.customLicenseDurationDays || 365).toString());
                                                                        setNewActivations((req.customMaxActivations || (req.planId ? planDefaults[req.planId]?.maxActivations : 100)).toString());
                                                                        setIsPriceDialogOpen(true);
                                                                    }}
                                                                    className="p-2 bg-stone-800 text-stone-400 hover:bg-white/10 hover:text-white rounded-lg border border-white/5 transition-all"
                                                                    title="Set Custom Price"
                                                                >
                                                                    <DollarSign size={16} />
                                                                </button>

                                                                <button
                                                                    onClick={() => initiatePayment(req)}
                                                                    disabled={processingAction?.id === req.id && processingAction?.action === 'status'}
                                                                    className="p-2 bg-green-500/10 text-green-500 hover:bg-green-500 hover:text-white rounded-lg border border-green-500/20 transition-all"
                                                                    title="Mark as Paid"
                                                                >
                                                                    {processingAction?.id === req.id && processingAction?.action === 'status' ? (
                                                                        <Loader2 size={16} className="animate-spin" />
                                                                    ) : (
                                                                        <Check size={16} />
                                                                    )}
                                                                </button>
                                                                
                                                                <button
                                                                    onClick={() => handleCancelRequest(req)}
                                                                    className="p-2 bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white rounded-lg border border-red-500/20 transition-all"
                                                                    title="Cancel Request"
                                                                >
                                                                    <X size={16} />
                                                                </button>
                                                            </>
                                                        )}
                                                    </div>
                                                </td>
                                            </tr>
                                        ))
                                    )}
                                </tbody>
                            </table>
                        </div>

                        {/* Pagination */}
                        {filteredRequests.length > 0 && (
                            <div className="flex flex-col sm:flex-row items-center justify-between gap-4 pt-4 border-t border-white/5">
                                <div className="text-[10px] font-bold text-stone-500 uppercase tracking-widest">
                                    Showing <span className="text-white">{(currentPage - 1) * itemsPerPage + 1}</span> to <span className="text-white">{Math.min(currentPage * itemsPerPage, filteredRequests.length)}</span> of <span className="text-white">{filteredRequests.length}</span> results
                                </div>
                                
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                                        disabled={currentPage === 1}
                                        className="p-1.5 rounded-lg border border-white/5 bg-stone-900/40 hover:bg-white/5 disabled:opacity-30 disabled:hover:bg-transparent transition-colors"
                                    >
                                        <ChevronLeft size={16} />
                                    </button>
                                    
                                    <div className="flex items-center gap-1">
                                        {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                                            let pageNum = i + 1;
                                            if (totalPages > 5) {
                                                if (currentPage > 3) {
                                                    pageNum = currentPage - 2 + i;
                                                }
                                                if (pageNum > totalPages) {
                                                    pageNum = totalPages - 4 + i;
                                                }
                                            }
                                            
                                            return (
                                                <button
                                                    key={pageNum}
                                                    onClick={() => setCurrentPage(pageNum)}
                                                    className={clsx(
                                                        "w-7 h-7 flex items-center justify-center rounded-lg text-xs font-bold transition-all",
                                                        currentPage === pageNum 
                                                            ? "bg-amber-500 text-black shadow-lg shadow-amber-500/20" 
                                                            : "bg-white/5 text-stone-400 hover:bg-white/10 hover:text-white"
                                                    )}
                                                >
                                                    {pageNum}
                                                </button>
                                            );
                                        })}
                                    </div>

                                    <button
                                        onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                                        disabled={currentPage === totalPages}
                                        className="p-1.5 rounded-lg border border-white/5 bg-stone-900/40 hover:bg-white/5 disabled:opacity-30 disabled:hover:bg-transparent transition-colors"
                                    >
                                        <ChevronRight size={16} />
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
                )}
            </div>

            {/* Confirmation Dialog */}
            <ConfirmDialog
                isOpen={isConfirmOpen}
                onClose={() => {
                    setIsConfirmOpen(false);
                    setPendingPayment(null);
                }}
                onConfirm={executePayment}
                title="Confirm Payment Fulfillment"
                message={
                    <div className="space-y-4">
                        <p>Are you sure you want to mark this request as PAID? This will generate a license and send it to {pendingPayment?.customerEmail}.</p>
                        {pendingPayment?.transactionId && (
                            <div className="p-3 bg-stone-800 rounded-lg border border-white/5 space-y-1">
                                <p className="text-[10px] text-stone-500 uppercase font-bold">Client Submitted Transaction ID</p>
                                <p className="text-white font-mono text-sm">{pendingPayment.transactionId}</p>
                            </div>
                        )}
                        <div className="grid grid-cols-2 gap-4">
                            <div className="p-3 bg-stone-800 rounded-lg border border-white/5 space-y-1">
                                <p className="text-[10px] text-stone-500 uppercase font-bold">Price</p>
                                <p className="text-amber-500 font-bold">
                                    ${(pendingPayment?.customPrice || (pendingPayment?.planId === 'ENTERPRISE' ? 99 : 29)).toFixed(2)}
                                </p>
                            </div>
                            <div className="p-3 bg-stone-800 rounded-lg border border-white/5 space-y-1">
                                <p className="text-[10px] text-stone-500 uppercase font-bold">Plan</p>
                                <p className="text-white font-bold">{pendingPayment?.planId}</p>
                            </div>
                        </div>
                    </div>
                }
                confirmText="Fulfill Order"
                isLoading={processingAction?.id === pendingPayment?.id && processingAction?.action === 'status'}
                variant="success"
            />

            {/* Cancel Confirmation Dialog */}
            <ConfirmDialog
                isOpen={isCancelConfirmOpen}
                onClose={() => {
                    setIsCancelConfirmOpen(false);
                    setPendingCancelRequest(null);
                }}
                onConfirm={executeCancel}
                title="Cancel Buy Request"
                message={
                    <div className="space-y-4">
                        <p>Are you sure you want to cancel this request?</p>
                        {pendingCancelRequest && (
                            <div className="p-3 bg-stone-800 rounded-lg border border-white/5 space-y-2">
                                <div className="flex justify-between items-center">
                                    <span className="text-[10px] text-stone-500 uppercase font-bold">Customer</span>
                                    <span className="text-white font-bold">{pendingCancelRequest.customerName}</span>
                                </div>
                                <div className="flex justify-between items-center">
                                    <span className="text-[10px] text-stone-500 uppercase font-bold">Email</span>
                                    <span className="text-white text-sm">{pendingCancelRequest.customerEmail}</span>
                                </div>
                                <div className="flex justify-between items-center">
                                    <span className="text-[10px] text-stone-500 uppercase font-bold">Plan</span>
                                    <span className="text-white font-bold">{pendingCancelRequest.planId}</span>
                                </div>
                            </div>
                        )}
                    </div>
                }
                confirmText="Cancel Request"
                variant="danger"
            />

            {/* Custom Price Dialog */}
            {isPriceDialogOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
                    <motion.div 
                        initial={{ opacity: 0, scale: 0.95 }}
                        animate={{ opacity: 1, scale: 1 }}
                        className="glass bg-stone-900 border border-white/10 w-full max-w-md p-6 rounded-2xl"
                    >
                        <h3 className="text-xl font-bold text-white mb-2">Set Custom Price</h3>
                        <p className="text-stone-400 text-sm mb-6">Enter the fixed price for {priceEditRequest?.customerName}'s license.</p>
                        
                        <div className="space-y-4 mb-8">
                            <label className="block">
                                <span className="text-xs font-bold text-stone-500 uppercase tracking-widest">Price (USD)</span>
                                <input 
                                    type="number"
                                    step="0.01"
                                    value={newPrice}
                                    onChange={(e) => setNewPrice(e.target.value)}
                                    placeholder="0.00"
                                    className="w-full mt-1 bg-black/40 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-amber-500 transition-all font-mono"
                                />
                            </label>
                            
                            <label className="block">
                                <span className="text-xs font-bold text-stone-500 uppercase tracking-widest">License Duration (Days)</span>
                                <input 
                                    type="number"
                                    min="1"
                                    value={newDuration}
                                    onChange={(e) => setNewDuration(e.target.value)}
                                    placeholder="365"
                                    className="w-full mt-1 bg-black/40 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-amber-500 transition-all font-mono"
                                />
                            </label>
                            
                            <div className="block">
                                <div className="flex justify-between items-center mb-1">
                                    <span className="text-xs font-bold text-stone-500 uppercase tracking-widest">Max Activations</span>
                                    {priceEditRequest?.planId && planDefaults[priceEditRequest.planId] !== undefined && (
                                        <button 
                                            onClick={() => setNewActivations(planDefaults[priceEditRequest.planId!].maxActivations.toString())}
                                            className="text-[10px] text-amber-500 hover:text-amber-400 font-bold uppercase tracking-wider flex items-center gap-1 transition-colors"
                                        >
                                            <RefreshCw size={10} />
                                            Reset to Default ({planDefaults[priceEditRequest.planId].maxActivations})
                                        </button>
                                    )}
                                </div>
                                <input 
                                    type="number"
                                    min="1"
                                    value={newActivations}
                                    onChange={(e) => setNewActivations(e.target.value)}
                                    placeholder="100"
                                    className="w-full bg-black/40 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-amber-500 transition-all font-mono"
                                />
                            </div>
                            
                            <p className="text-[10px] text-stone-500 italic">This price and terms will be automatically locked for the client when they open their payment link.</p>
                        </div>

                        <div className="flex justify-end gap-3">
                            <button 
                                onClick={() => setIsPriceDialogOpen(false)}
                                className="px-4 py-2 text-stone-400 hover:text-white transition-colors text-sm font-bold"
                            >
                                Cancel
                            </button>
                            <button 
                                onClick={handleSetPrice}
                                disabled={!newPrice || processingAction?.id === priceEditRequest?.id}
                                className="flex-1 px-4 py-2 bg-amber-500 text-black rounded-lg font-bold hover:bg-amber-600 transition-all disabled:opacity-50 disabled:hover:bg-amber-500 flex items-center justify-center gap-2"
                            >
                                {processingAction?.id === priceEditRequest?.id && processingAction?.action === 'price' ? <Loader2 size={14} className="animate-spin" /> : "Save Price"}
                            </button>
                        </div>
                    </motion.div>
                </div>
            )}

            {/* Receipt Review Modal */}
            {reviewRequest && (
                <div className="fixed inset-0 z-[60] flex items-center justify-center p-8 bg-black/95 backdrop-blur-xl">
                    <div className="relative w-full max-w-6xl h-[90vh] flex flex-row gap-6">
                        {/* Sidebar with details */}
                        <div className="w-80 flex flex-col gap-6 shrink-0">
                            <div className="flex items-center justify-between">
                                <div className="flex flex-col">
                                    <h3 className="text-xl font-bold text-white">Payment Verification</h3>
                                    <p className="text-stone-400 text-xs">Request #{reviewRequest.id}</p>
                                </div>
                                <button 
                                    onClick={() => setReviewRequest(null)}
                                    className="p-2 text-stone-500 hover:text-white transition-colors"
                                >
                                    <X size={24} />
                                </button>
                            </div>

                            <div className="space-y-4">
                                <div className="p-4 bg-white/5 rounded-2xl border border-white/10 space-y-3">
                                    <div>
                                        <p className="text-[10px] font-bold text-stone-500 uppercase tracking-widest mb-1">Customer</p>
                                        <p className="text-white font-bold">{reviewRequest.customerName}</p>
                                        <p className="text-xs text-stone-400">{reviewRequest.customerEmail}</p>
                                    </div>
                                    <div>
                                        <p className="text-[10px] font-bold text-stone-500 uppercase tracking-widest mb-1">Transaction ID</p>
                                        <div className="p-3 bg-black/40 rounded-xl border border-white/5 font-mono text-sm text-amber-500 break-all">
                                            {reviewRequest.transactionId || 'Not provided'}
                                        </div>
                                    </div>
                                    <div>
                                        <p className="text-[10px] font-bold text-stone-500 uppercase tracking-widest mb-1">Plan</p>
                                        <p className="text-white font-bold">{reviewRequest.planId}</p>
                                    </div>
                                    <div>
                                        <p className="text-[10px] font-bold text-stone-500 uppercase tracking-widest mb-1">Price</p>
                                        {reviewRequest.planId === 'ENTERPRISE' && !reviewRequest.customPrice ? (
                                            <p className="text-stone-500 font-bold">Negotiable</p>
                                        ) : (
                                            <p className="text-amber-500 font-bold">${(reviewRequest.customPrice || 29).toFixed(2)}</p>
                                        )}
                                    </div>
                                </div>

                                <div className="p-4 bg-amber-500/5 rounded-2xl border border-amber-500/10">
                                    <p className="text-xs text-amber-500/60 leading-relaxed italic">
                                        "Please verify this transaction ID in your bank portal before confirming the payment. Once confirmed, a license will be generated and sent immediately."
                                    </p>
                                </div>
                            </div>

                            <div className="mt-auto flex flex-col gap-3">
                                <a 
                                    href={reviewRequest.manualReceiptUrl || '#'} 
                                    download={`receipt-req-${reviewRequest.id}`}
                                    className="w-full py-3 bg-white/10 hover:bg-white/20 text-white rounded-xl text-center text-sm font-bold transition-all flex items-center justify-center gap-2"
                                >
                                    <Download size={16} />
                                    Download Proof
                                </a>
                                <button 
                                    onClick={() => {
                                        if (reviewRequest) {
                                            initiatePayment(reviewRequest);
                                            setReviewRequest(null);
                                        }
                                    }}
                                    className="w-full py-4 bg-green-500 hover:bg-green-600 text-black rounded-xl text-lg font-bold shadow-lg shadow-green-500/20 transition-all flex items-center justify-center gap-2"
                                >
                                    <Check size={20} />
                                    Confirm & Paid
                                </button>
                            </div>
                        </div>

                        {/* Main Content (Image/PDF) */}
                        <div className="flex-1 bg-black/50 rounded-3xl border border-white/10 overflow-hidden relative shadow-2xl">
                            {reviewRequest.manualReceiptUrl?.endsWith('.pdf') || reviewRequest.manualReceiptUrl?.startsWith('data:application/pdf') ? (
                                <iframe 
                                    src={reviewRequest.manualReceiptUrl || undefined} 
                                    className="w-full h-full border-none bg-stone-100"
                                />
                            ) : (
                                <img 
                                    src={reviewRequest.manualReceiptUrl || ''} 
                                    alt="Payment Receipt" 
                                    className="w-full h-full object-contain"
                                    onError={(e) => {
                                        const target = e.target as HTMLImageElement;
                                        target.style.display = 'none';
                                        const parent = target.parentElement;
                                        if (parent) {
                                            const errorMsg = document.createElement('div');
                                            errorMsg.className = "absolute inset-0 flex flex-col items-center justify-center text-stone-500 gap-3";
                                            errorMsg.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg><p class="font-bold">Image failed to load</p><p class="text-xs">The file might be corrupted or missing from the server.</p>';
                                            parent.appendChild(errorMsg);
                                        }
                                    }}
                                />
                            )}
                        </div>
                    </div>
                </div>
            )}
            
            <GenericToast 
                message={toast.message}
                type={toast.type}
                isVisible={toast.isVisible}
                onClose={() => setToast(prev => ({ ...prev, isVisible: false }))}
            />
        </div>
    );
}
