@extends('layouts.app')

@section('title', '법인카드 거래내역')

@push('styles')
<style>
    @media print { .no-print { display: none !important; } }
</style>
@endpush

@section('content')
<meta name="csrf-token" content="{{ csrf_token() }}">
<div id="card-transactions-root"></div>
@endsection

@push('scripts')
@include('partials.react-cdn')
<script src="https://unpkg.com/lucide@0.469.0?v={{ time() }}"></script>
@verbatim
<script type="text/babel">
const { useState, useRef, useEffect } = React;

const createIcon = (name) => {
    const _def=((n)=>{const a={'check-circle':'CircleCheck','alert-circle':'CircleAlert','alert-triangle':'TriangleAlert','clipboard-check':'ClipboardCheck','arrow-up-circle':'CircleArrowUp','arrow-down-circle':'CircleArrowDown'};if(a[n]&&lucide[a[n]])return lucide[a[n]];const p=n.split('-').map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join('');return lucide[p]||(lucide.icons&&lucide.icons[n])||null;})(name);
    const _c = s => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
    return ({ className = "w-5 h-5", ...props }) => {
        if (!_def) return null;
        const [, attrs, children = []] = _def;
        const sp = { className };
        Object.entries(attrs).forEach(([k, v]) => { sp[_c(k)] = v; });
        Object.assign(sp, props);
        return React.createElement("svg", sp, ...children.map(([tag, ca], i) => {
            const cp = { key: i };
            if (ca) Object.entries(ca).forEach(([k, v]) => { cp[_c(k)] = v; });
            return React.createElement(tag, cp);
        }));
    };
};

const CreditCard = createIcon('credit-card');
const Plus = createIcon('plus');
const Search = createIcon('search');
const Download = createIcon('download');
const Calendar = createIcon('calendar');
const X = createIcon('x');
const Edit = createIcon('edit');
const Trash2 = createIcon('trash-2');
const Receipt = createIcon('receipt');
const TrendingUp = createIcon('trending-up');
const TrendingDown = createIcon('trending-down');
const ShoppingBag = createIcon('shopping-bag');
const Coffee = createIcon('coffee');
const Car = createIcon('car');
const Utensils = createIcon('utensils');
const Building = createIcon('building');

function CardTransactionsManagement() {
    const [cards, setCards] = useState([]);
    const [transactions, setTransactions] = useState([]);
    const [stats, setStats] = useState({ total: 0, totalAmount: 0, approvedAmount: 0, cancelledAmount: 0 });
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    const [searchTerm, setSearchTerm] = useState('');
    const [filterCard, setFilterCard] = useState('all');
    const [filterCategory, setFilterCategory] = useState('all');
    const [filterStatus, setFilterStatus] = useState('all');
    const [dateRange, setDateRange] = useState({
        start: new Date(new Date().setDate(new Date().getDate() - 30)).toISOString().split('T')[0],
        end: new Date().toISOString().split('T')[0]
    });

    const [showModal, setShowModal] = useState(false);
    const [modalMode, setModalMode] = useState('add');
    const [editingTransaction, setEditingTransaction] = useState(null);

    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

    const initialFormState = {
        cardId: '',
        date: new Date().toISOString().split('T')[0],
        time: '',
        merchant: '',
        category: '식비',
        amount: '',
        approvalNo: '',
        status: 'approved',
        memo: ''
    };
    const [formData, setFormData] = useState(initialFormState);

    const categories = ['식비', '교통비', '운영비', '마케팅비', '사무용품', '도서/교육', '접대비', '장비구매', '기타'];

    const getCategoryIcon = (category) => {
        switch (category) {
            case '식비': return <Utensils className="w-4 h-4" />;
            case '교통비': return <Car className="w-4 h-4" />;
            case '마케팅비': return <TrendingUp className="w-4 h-4" />;
            case '접대비': return <Coffee className="w-4 h-4" />;
            case '사무용품':
            case '장비구매': return <ShoppingBag className="w-4 h-4" />;
            case '운영비': return <Building className="w-4 h-4" />;
            default: return <Receipt className="w-4 h-4" />;
        }
    };

    const getCategoryColor = (category) => {
        const colors = {
            '식비': 'bg-orange-100 text-orange-700',
            '교통비': 'bg-blue-100 text-blue-700',
            '운영비': 'bg-purple-100 text-purple-700',
            '마케팅비': 'bg-pink-100 text-pink-700',
            '사무용품': 'bg-gray-100 text-gray-700',
            '도서/교육': 'bg-emerald-100 text-emerald-700',
            '접대비': 'bg-amber-100 text-amber-700',
            '장비구매': 'bg-indigo-100 text-indigo-700',
            '기타': 'bg-slate-100 text-slate-700'
        };
        return colors[category] || 'bg-gray-100 text-gray-700';
    };

    const formatCurrency = (num) => num ? num.toLocaleString() : '0';
    const formatInputCurrency = (value) => {
        if (!value && value !== 0) return '';
        const num = String(value).replace(/[^\d-]/g, '');
        const isNegative = num.startsWith('-');
        const absNum = num.replace('-', '');
        if (!absNum) return isNegative ? '-' : '';
        return (isNegative ? '-' : '') + Number(absNum).toLocaleString();
    };
    const parseInputCurrency = (value) => String(value).replace(/[^\d-]/g, '');

    const fetchTransactions = async () => {
        setLoading(true);
        try {
            const params = new URLSearchParams({
                startDate: dateRange.start,
                endDate: dateRange.end,
            });
            const res = await fetch(`/finance/card-transactions/list?${params}`);
            const data = await res.json();
            if (data.success) {
                setTransactions(data.data);
                setStats(data.stats);
                if (data.cards) setCards(data.cards);
            }
        } catch (err) {
            console.error('거래내역 조회 실패:', err);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { fetchTransactions(); }, [dateRange.start, dateRange.end]);

    // 클라이언트 필터링
    const filteredTransactions = transactions.filter(tx => {
        const matchesSearch = tx.merchant.toLowerCase().includes(searchTerm.toLowerCase()) ||
                             (tx.memo || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                             (tx.approvalNo || '').includes(searchTerm);
        const matchesCard = filterCard === 'all' || tx.cardId === parseInt(filterCard);
        const matchesCategory = filterCategory === 'all' || tx.category === filterCategory;
        const matchesStatus = filterStatus === 'all' || tx.status === filterStatus;
        return matchesSearch && matchesCard && matchesCategory && matchesStatus;
    });

    const totalAmount = filteredTransactions.reduce((sum, tx) => sum + tx.amount, 0);
    const approvedAmount = filteredTransactions.filter(tx => tx.status === 'approved').reduce((sum, tx) => sum + tx.amount, 0);
    const cancelledAmount = filteredTransactions.filter(tx => tx.status === 'cancelled').reduce((sum, tx) => sum + Math.abs(tx.amount), 0);

    const categoryTotals = filteredTransactions
        .filter(tx => tx.status === 'approved' && tx.amount > 0)
        .reduce((acc, tx) => { acc[tx.category] = (acc[tx.category] || 0) + tx.amount; return acc; }, {});

    const handleAddTransaction = () => {
        setModalMode('add');
        setFormData({ ...initialFormState, cardId: cards.length > 0 ? cards[0].id : '' });
        setShowModal(true);
    };

    const handleEditTransaction = (transaction) => {
        setModalMode('edit');
        setEditingTransaction(transaction);
        setFormData({
            cardId: transaction.cardId,
            date: transaction.date,
            time: transaction.time || '',
            merchant: transaction.merchant,
            category: transaction.category || '기타',
            amount: transaction.amount,
            approvalNo: transaction.approvalNo || '',
            status: transaction.status,
            memo: transaction.memo || ''
        });
        setShowModal(true);
    };

    const handleSave = async () => {
        if (!formData.merchant || !formData.amount) { alert('가맹점명과 금액을 입력해주세요.'); return; }
        setSaving(true);
        try {
            const payload = {
                ...formData,
                cardId: parseInt(formData.cardId) || null,
                amount: parseInt(formData.amount) || 0,
                time: formData.time || null,
            };
            const url = modalMode === 'add' ? '/finance/card-transactions/store' : `/finance/card-transactions/${editingTransaction.id}`;
            const res = await fetch(url, {
                method: modalMode === 'add' ? 'POST' : 'PUT',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
                body: JSON.stringify(payload),
            });
            const data = await res.json();
            if (!res.ok) {
                const errors = data.errors ? Object.values(data.errors).flat().join('\n') : data.message;
                alert(errors || '저장에 실패했습니다.');
                return;
            }
            setShowModal(false);
            setEditingTransaction(null);
            fetchTransactions();
        } catch (err) {
            alert('저장에 실패했습니다.');
        } finally {
            setSaving(false);
        }
    };

    const handleDelete = async (id) => {
        if (!confirm('정말 삭제하시겠습니까?')) return;
        try {
            const res = await fetch(`/finance/card-transactions/${id}`, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': csrfToken },
            });
            if (res.ok) {
                if (showModal) { setShowModal(false); setEditingTransaction(null); }
                fetchTransactions();
            }
        } catch (err) {
            alert('삭제에 실패했습니다.');
        }
    };

    const handleDownload = () => {
        const rows = [
            ['법인카드 거래내역', `${dateRange.start} ~ ${dateRange.end}`],
            [],
            ['날짜', '시간', '카드', '가맹점', '카테고리', '금액', '승인번호', '상태', '메모'],
            ...filteredTransactions.map(tx => [
                tx.date, tx.time, cards.find(c => c.id === tx.cardId)?.cardName || '', tx.merchant, tx.category, tx.amount, tx.approvalNo, tx.status === 'approved' ? '승인' : '취소', tx.memo
            ]),
            [],
            ['총 사용금액', '', '', '', '', totalAmount]
        ];
        const csvContent = rows.map(row => row.join(',')).join('\n');
        const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `법인카드거래내역_${dateRange.start}_${dateRange.end}.csv`;
        link.click();
    };

    const groupedTransactions = filteredTransactions.reduce((groups, tx) => {
        const date = tx.date;
        if (!groups[date]) groups[date] = [];
        groups[date].push(tx);
        return groups;
    }, {});

    const formatDateDisplay = (dateStr) => {
        const date = new Date(dateStr);
        const days = ['일', '월', '화', '수', '목', '금', '토'];
        return `${date.getMonth() + 1}월 ${date.getDate()}일 (${days[date.getDay()]})`;
    };

    return (
        <div className="bg-gray-50 min-h-screen">
            <header className="bg-white border-b border-gray-200 rounded-t-xl mb-6">
                <div className="px-6 py-4">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-4">
                            <div className="p-2 bg-indigo-100 rounded-xl"><Receipt className="w-6 h-6 text-indigo-600" /></div>
                            <div><h1 className="text-xl font-bold text-gray-900">법인카드 거래내역</h1><p className="text-sm text-gray-500">Corporate Card Transactions</p></div>
                        </div>
                        <div className="flex items-center gap-3">
                            <button onClick={handleDownload} className="flex items-center gap-2 px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"><Download className="w-4 h-4" /><span className="text-sm">Excel</span></button>
                            <button onClick={handleAddTransaction} className="flex items-center gap-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg"><Plus className="w-4 h-4" /><span className="text-sm font-medium">거래 등록</span></button>
                        </div>
                    </div>
                </div>
            </header>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <div className="bg-white rounded-xl border border-gray-200 p-6">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-gray-500">조회 건수</span><Receipt className="w-5 h-5 text-gray-400" /></div>
                    <p className="text-2xl font-bold text-gray-900">{filteredTransactions.length}건</p>
                    <p className="text-xs text-gray-400 mt-1">승인 {filteredTransactions.filter(t => t.status === 'approved').length}건</p>
                </div>
                <div className="bg-white rounded-xl border border-indigo-200 p-6 bg-indigo-50/30">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-indigo-700">총 사용금액</span><CreditCard className="w-5 h-5 text-indigo-500" /></div>
                    <p className="text-2xl font-bold text-indigo-600">{formatCurrency(totalAmount)}원</p>
                </div>
                <div className="bg-white rounded-xl border border-emerald-200 p-6">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-emerald-700">승인 금액</span><TrendingUp className="w-5 h-5 text-emerald-500" /></div>
                    <p className="text-2xl font-bold text-emerald-600">{formatCurrency(approvedAmount)}원</p>
                </div>
                <div className="bg-white rounded-xl border border-rose-200 p-6">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-rose-700">취소 금액</span><TrendingDown className="w-5 h-5 text-rose-500" /></div>
                    <p className="text-2xl font-bold text-rose-600">{formatCurrency(cancelledAmount)}원</p>
                </div>
            </div>

            {Object.keys(categoryTotals).length > 0 && (
                <div className="bg-white rounded-xl border border-gray-200 p-4 mb-6">
                    <h3 className="text-sm font-medium text-gray-700 mb-3">카테고리별 사용현황</h3>
                    <div className="flex flex-wrap gap-2">
                        {Object.entries(categoryTotals).sort((a, b) => b[1] - a[1]).map(([cat, amount]) => (
                            <div key={cat} className={`flex items-center gap-2 px-3 py-2 rounded-lg ${getCategoryColor(cat)}`}>
                                {getCategoryIcon(cat)}<span className="text-sm font-medium">{cat}</span><span className="text-sm">{formatCurrency(amount)}원</span>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            <div className="bg-white rounded-xl border border-gray-200 p-4 mb-6">
                <div className="grid grid-cols-1 md:grid-cols-6 gap-4">
                    <div className="md:col-span-2 relative">
                        <Search className="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
                        <input type="text" placeholder="가맹점, 메모, 승인번호 검색..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500" />
                    </div>
                    <select value={filterCard} onChange={(e) => setFilterCard(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg">
                        <option value="all">전체 카드</option>
                        {cards.map(card => <option key={card.id} value={card.id}>{card.cardName}</option>)}
                    </select>
                    <select value={filterCategory} onChange={(e) => setFilterCategory(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg">
                        <option value="all">전체 카테고리</option>
                        {categories.map(cat => <option key={cat} value={cat}>{cat}</option>)}
                    </select>
                    <div className="flex items-center gap-2">
                        <input type="date" value={dateRange.start} onChange={(e) => setDateRange(prev => ({ ...prev, start: e.target.value }))} className="flex-1 px-2 py-2 border border-gray-300 rounded-lg text-sm" />
                        <span className="text-gray-400">~</span>
                        <input type="date" value={dateRange.end} onChange={(e) => setDateRange(prev => ({ ...prev, end: e.target.value }))} className="flex-1 px-2 py-2 border border-gray-300 rounded-lg text-sm" />
                    </div>
                    <div className="flex gap-1">
                        {['all', 'approved', 'cancelled'].map(s => (
                            <button key={s} onClick={() => setFilterStatus(s)} className={`flex-1 px-3 py-2 rounded-lg text-sm font-medium ${filterStatus === s ? (s === 'approved' ? 'bg-emerald-600 text-white' : s === 'cancelled' ? 'bg-rose-600 text-white' : 'bg-indigo-600 text-white') : 'bg-gray-100 text-gray-600'}`}>
                                {s === 'all' ? '전체' : s === 'approved' ? '승인' : '취소'}
                            </button>
                        ))}
                    </div>
                </div>
            </div>

            <div className="space-y-4">
                {loading ? (
                    <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
                        <div className="flex items-center justify-center gap-2 text-gray-400">
                            <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                            불러오는 중...
                        </div>
                    </div>
                ) : Object.entries(groupedTransactions).length === 0 ? (
                    <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
                        <Receipt className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                        <p className="text-gray-400">거래 내역이 없습니다.</p>
                    </div>
                ) : (
                    Object.entries(groupedTransactions).map(([date, txList]) => (
                        <div key={date} className="bg-white rounded-xl border border-gray-200 overflow-hidden">
                            <div className="px-6 py-3 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
                                <div className="flex items-center gap-2"><Calendar className="w-4 h-4 text-gray-400" /><span className="font-medium text-gray-700">{formatDateDisplay(date)}</span></div>
                                <span className="text-sm text-gray-500">{txList.length}건 / {formatCurrency(txList.reduce((s, t) => s + t.amount, 0))}원</span>
                            </div>
                            <div className="divide-y divide-gray-100">
                                {txList.map(tx => (
                                    <div key={tx.id} onClick={() => handleEditTransaction(tx)} className="px-6 py-4 hover:bg-gray-50 cursor-pointer">
                                        <div className="flex items-center justify-between">
                                            <div className="flex items-center gap-4">
                                                <div className={`p-2 rounded-lg ${getCategoryColor(tx.category)}`}>{getCategoryIcon(tx.category)}</div>
                                                <div>
                                                    <div className="flex items-center gap-2 mb-1">
                                                        <span className="font-medium text-gray-900">{tx.merchant}</span>
                                                        <span className={`px-2 py-0.5 rounded text-xs ${tx.status === 'approved' ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'}`}>{tx.status === 'approved' ? '승인' : '취소'}</span>
                                                    </div>
                                                    <div className="flex items-center gap-3 text-sm text-gray-500">
                                                        <span>{tx.time}</span>
                                                        <span>{cards.find(c => c.id === tx.cardId)?.cardName}</span>
                                                        <span className={`px-1.5 py-0.5 rounded text-xs ${getCategoryColor(tx.category)}`}>{tx.category}</span>
                                                        {tx.memo && <span className="text-gray-400">| {tx.memo}</span>}
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="flex items-center gap-4">
                                                <div className="text-right">
                                                    <p className={`text-lg font-bold ${tx.amount < 0 ? 'text-rose-600' : 'text-gray-900'}`}>{formatCurrency(tx.amount)}원</p>
                                                    {tx.approvalNo && <p className="text-xs text-gray-400">승인번호: {tx.approvalNo}</p>}
                                                </div>
                                                <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
                                                    <button onClick={() => handleEditTransaction(tx)} className="p-2 text-gray-400 hover:text-blue-500 hover:bg-blue-50 rounded-lg"><Edit className="w-4 h-4" /></button>
                                                    <button onClick={() => handleDelete(tx.id)} className="p-2 text-gray-400 hover:text-rose-500 hover:bg-rose-50 rounded-lg"><Trash2 className="w-4 h-4" /></button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    ))
                )}
            </div>

            {showModal && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-xl p-6 w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
                        <div className="flex items-center justify-between mb-6">
                            <h3 className="text-lg font-bold text-gray-900">{modalMode === 'add' ? '거래 등록' : '거래 수정'}</h3>
                            <button onClick={() => { setShowModal(false); setEditingTransaction(null); }} className="p-1 hover:bg-gray-100 rounded-lg"><X className="w-5 h-5 text-gray-500" /></button>
                        </div>
                        <div className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">카드</label>
                                    <select value={formData.cardId} onChange={(e) => setFormData(prev => ({ ...prev, cardId: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                        <option value="">선택</option>
                                        {cards.map(card => <option key={card.id} value={card.id}>{card.cardName}</option>)}
                                    </select>
                                </div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">카테고리</label>
                                    <select value={formData.category} onChange={(e) => setFormData(prev => ({ ...prev, category: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                        {categories.map(cat => <option key={cat} value={cat}>{cat}</option>)}
                                    </select>
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">날짜 *</label><input type="date" value={formData.date} onChange={(e) => setFormData(prev => ({ ...prev, date: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">시간</label><input type="time" value={formData.time} onChange={(e) => setFormData(prev => ({ ...prev, time: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">가맹점명 *</label><input type="text" value={formData.merchant} onChange={(e) => setFormData(prev => ({ ...prev, merchant: e.target.value }))} placeholder="가맹점명" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            <div className="grid grid-cols-2 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">금액 *</label><input type="text" value={formatInputCurrency(formData.amount)} onChange={(e) => setFormData(prev => ({ ...prev, amount: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /><p className="text-xs text-gray-400 mt-1">취소 시 음수(-) 입력</p></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">승인번호</label><input type="text" value={formData.approvalNo} onChange={(e) => setFormData(prev => ({ ...prev, approvalNo: e.target.value }))} placeholder="승인번호" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">상태</label>
                                <div className="flex gap-4">
                                    <label className="flex items-center gap-2 cursor-pointer"><input type="radio" name="status" value="approved" checked={formData.status === 'approved'} onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))} className="w-4 h-4 text-indigo-600" /><span className="text-sm">승인</span></label>
                                    <label className="flex items-center gap-2 cursor-pointer"><input type="radio" name="status" value="cancelled" checked={formData.status === 'cancelled'} onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))} className="w-4 h-4 text-indigo-600" /><span className="text-sm">취소</span></label>
                                </div>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">메모</label><input type="text" value={formData.memo} onChange={(e) => setFormData(prev => ({ ...prev, memo: e.target.value }))} placeholder="메모" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                        </div>
                        <div className="flex gap-3 mt-6">
                            {modalMode === 'edit' && <button onClick={() => handleDelete(editingTransaction.id)} className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg">삭제</button>}
                            <button onClick={() => { setShowModal(false); setEditingTransaction(null); }} className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">취소</button>
                            <button onClick={handleSave} disabled={saving} className="flex-1 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg disabled:opacity-50">{saving ? '저장 중...' : (modalMode === 'add' ? '등록' : '저장')}</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

const rootElement = document.getElementById('card-transactions-root');
if (rootElement) { ReactDOM.createRoot(rootElement).render(<CardTransactionsManagement />); }
</script>
@endverbatim
@endpush
