@extends('layouts.app')

@section('title', '법인카드 등록/조회')

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

@section('content')
<div id="corporate-cards-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;

// Lucide 아이콘 래핑
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 Edit = createIcon('edit');
const Trash2 = createIcon('trash-2');
const X = createIcon('x');
const Building = createIcon('building');
const Calendar = createIcon('calendar');
const DollarSign = createIcon('dollar-sign');
const CheckCircle = createIcon('check-circle');
const XCircle = createIcon('x-circle');


function CorporateCardsManagement() {
    // 카드 목록 데이터
    const [cards, setCards] = useState([]);
    const [loading, setLoading] = useState(true);

    const [searchTerm, setSearchTerm] = useState('');
    const [filterStatus, setFilterStatus] = useState('all');
    const [showModal, setShowModal] = useState(false);
    const [modalMode, setModalMode] = useState('add'); // 'add' or 'edit'
    const [editingCard, setEditingCard] = useState(null);

    // 요약 데이터
    const [summaryData, setSummaryData] = useState(null);
    const [showPrepaymentModal, setShowPrepaymentModal] = useState(false);
    const [prepaymentItems, setPrepaymentItems] = useState([
        { date: new Date().toISOString().slice(0, 10), amount: '', description: '' }
    ]);

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

    // 새 카드 폼 초기값
    const initialFormState = {
        cardName: '',
        cardCompany: '삼성카드',
        cardNumber: '',
        cardType: 'credit',
        paymentDay: 15,
        creditLimit: '',
        cardHolderName: '',
        actualUser: '',
        expiryDate: '',
        cvc: '',
        status: 'active',
        memo: ''
    };
    const [formData, setFormData] = useState(initialFormState);

    // 초기 데이터 로드
    useEffect(() => {
        fetchCards();
    }, []);

    const fetchCards = async () => {
        try {
            setLoading(true);
            const [cardsRes, summaryRes] = await Promise.all([
                fetch('/finance/corporate-cards/list'),
                fetch('/finance/corporate-cards/summary'),
            ]);
            const cardsResult = await cardsRes.json();
            const summaryResult = await summaryRes.json();
            if (cardsResult.success) {
                setCards(cardsResult.data);
            }
            if (summaryResult.success) {
                setSummaryData(summaryResult.data);
            }
        } catch (error) {
            console.error('데이터 로드 실패:', error);
        } finally {
            setLoading(false);
        }
    };

    // 결제 항목 추가
    const addPrepaymentItem = () => {
        setPrepaymentItems(prev => [...prev, {
            date: new Date().toISOString().slice(0, 10),
            amount: '',
            description: ''
        }]);
    };

    // 결제 항목 삭제
    const removePrepaymentItem = (index) => {
        if (prepaymentItems.length <= 1) return;
        setPrepaymentItems(prev => prev.filter((_, i) => i !== index));
    };

    // 결제 항목 수정
    const updatePrepaymentItem = (index, field, value) => {
        setPrepaymentItems(prev => prev.map((item, i) =>
            i === index ? { ...item, [field]: value } : item
        ));
    };

    // 결제 내역 저장
    const handleSavePrepayment = async () => {
        try {
            const items = prepaymentItems
                .filter(item => item.amount && parseInt(parseInputCurrency(item.amount)) > 0)
                .map(item => ({
                    date: item.date,
                    amount: parseInt(parseInputCurrency(item.amount)),
                    description: item.description,
                }));

            const response = await fetch('/finance/corporate-cards/prepayment', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken,
                },
                body: JSON.stringify({ items }),
            });
            const result = await response.json();
            if (result.success) {
                setSummaryData(prev => ({
                    ...prev,
                    prepaidAmount: result.data.amount,
                    prepaidItems: result.data.items,
                }));
                setShowPrepaymentModal(false);
            } else {
                alert(result.message || '저장에 실패했습니다.');
            }
        } catch (error) {
            console.error('결제 내역 저장 실패:', error);
            alert('저장 중 오류가 발생했습니다.');
        }
    };

    // 결제 내역 수정 모달 열기
    const openPrepaymentModal = () => {
        const items = summaryData?.prepaidItems;
        if (items && items.length > 0) {
            setPrepaymentItems(items.map(item => ({
                date: item.date,
                amount: String(item.amount),
                description: item.description || '',
            })));
        } else {
            setPrepaymentItems([{
                date: new Date().toISOString().slice(0, 10),
                amount: '',
                description: ''
            }]);
        }
        setShowPrepaymentModal(true);
    };

    // 날짜 포맷 (M/D(요일))
    const formatPaymentDate = (dateStr) => {
        if (!dateStr) return '-';
        const date = new Date(dateStr);
        const days = ['일', '월', '화', '수', '목', '금', '토'];
        return `${date.getMonth() + 1}/${date.getDate()}(${days[date.getDay()]})`;
    };

    // 카드사 목록
    const cardCompanies = ['삼성카드', '현대카드', '국민카드', '신한카드', '롯데카드', 'BC카드', '하나카드', '우리카드', 'NH농협카드'];

    // 금액 포맷
    const formatCurrency = (num) => {
        if (!num) return '0';
        return num.toLocaleString();
    };

    // 입력용 금액 포맷 (3자리 콤마)
    const formatInputCurrency = (value) => {
        if (!value && value !== 0) return '';
        const num = String(value).replace(/[^\d]/g, '');
        if (!num) return '';
        return Number(num).toLocaleString();
    };

    // 입력값에서 숫자만 추출
    const parseInputCurrency = (value) => {
        return String(value).replace(/[^\d]/g, '');
    };

    // 결제 합계 계산
    const prepaymentTotal = prepaymentItems.reduce(
        (sum, item) => sum + (parseInt(parseInputCurrency(item.amount)) || 0), 0
    );

    // 카드번호 포맷
    const formatCardNumber = (num) => {
        if (!num) return '';
        return num.replace(/(.{4})/g, '$1-').slice(0, -1);
    };

    // 필터링된 카드 목록
    const filteredCards = cards.filter(card => {
        const matchesSearch = card.cardName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                            card.cardCompany.toLowerCase().includes(searchTerm.toLowerCase()) ||
                            card.actualUser.toLowerCase().includes(searchTerm.toLowerCase()) ||
                            (card.cardHolderName && card.cardHolderName.toLowerCase().includes(searchTerm.toLowerCase()));
        const matchesStatus = filterStatus === 'all' || card.status === filterStatus;
        return matchesSearch && matchesStatus;
    });

    // 카드 추가 모달 열기
    const handleAddCard = () => {
        setModalMode('add');
        setFormData(initialFormState);
        setShowModal(true);
    };

    // 카드 수정 모달 열기
    const handleEditCard = (card) => {
        setModalMode('edit');
        setEditingCard(card);
        setFormData({
            cardName: card.cardName,
            cardCompany: card.cardCompany,
            cardNumber: card.cardNumber,
            cardType: card.cardType,
            paymentDay: card.paymentDay,
            creditLimit: card.creditLimit,
            cardHolderName: card.cardHolderName || '',
            actualUser: card.actualUser || '',
            expiryDate: card.expiryDate || '',
            cvc: card.cvc || '',
            status: card.status,
            memo: card.memo
        });
        setShowModal(true);
    };

    // 카드 저장
    const handleSaveCard = async () => {
        if (!formData.cardName || !formData.cardNumber || !formData.cardHolderName || !formData.actualUser) {
            alert('필수 항목을 입력해주세요.');
            return;
        }

        try {
            if (modalMode === 'add') {
                const response = await fetch('/finance/corporate-cards/store', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                    },
                    body: JSON.stringify({
                        ...formData,
                        creditLimit: parseInt(formData.creditLimit) || 0,
                    }),
                });
                const result = await response.json();
                if (result.success) {
                    setCards(prev => [...prev, result.data]);
                } else {
                    alert(result.message || '저장에 실패했습니다.');
                    return;
                }
            } else {
                const response = await fetch(`/finance/corporate-cards/${editingCard.id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                    },
                    body: JSON.stringify({
                        ...formData,
                        creditLimit: parseInt(formData.creditLimit) || 0,
                    }),
                });
                const result = await response.json();
                if (result.success) {
                    setCards(prev => prev.map(card =>
                        card.id === editingCard.id ? result.data : card
                    ));
                } else {
                    alert(result.message || '수정에 실패했습니다.');
                    return;
                }
            }

            setShowModal(false);
            setEditingCard(null);
        } catch (error) {
            console.error('저장 실패:', error);
            alert('저장 중 오류가 발생했습니다.');
        }
    };

    // 카드 비활성화 (소프트 삭제)
    const handleDeactivateCard = async (id) => {
        if (confirm('카드를 비활성화하시겠습니까?\n(목록에서 숨겨지지만 데이터는 유지됩니다)')) {
            try {
                const response = await fetch(`/finance/corporate-cards/${id}/deactivate`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': csrfToken,
                    },
                });
                const result = await response.json();
                if (result.success) {
                    setCards(prev => prev.map(card =>
                        card.id === id ? { ...card, status: 'inactive' } : card
                    ));
                    if (showModal) {
                        setShowModal(false);
                        setEditingCard(null);
                    }
                }
            } catch (error) {
                console.error('비활성화 실패:', error);
                alert('비활성화 중 오류가 발생했습니다.');
            }
        }
    };

    // 카드 영구삭제
    const handlePermanentDeleteCard = async (id) => {
        if (confirm('⚠️ 카드를 영구 삭제하시겠습니까?\n\n이 작업은 되돌릴 수 없습니다.')) {
            try {
                const response = await fetch(`/finance/corporate-cards/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': csrfToken,
                    },
                });
                const result = await response.json();
                if (result.success) {
                    setCards(prev => prev.filter(card => card.id !== id));
                    if (showModal) {
                        setShowModal(false);
                        setEditingCard(null);
                    }
                }
            } catch (error) {
                console.error('삭제 실패:', error);
                alert('삭제 중 오류가 발생했습니다.');
            }
        }
    };

    // 사용률 계산
    const getUsagePercent = (usage, limit) => {
        if (!limit) return 0;
        return Math.round((usage / limit) * 100);
    };

    // 사용률 색상
    const getUsageColor = (percent) => {
        if (percent >= 80) return 'bg-red-500';
        if (percent >= 50) return 'bg-yellow-500';
        return 'bg-emerald-500';
    };

    // 카드번호로 바로빌 원본 사용금액 조회 (하이픈 제거 매칭)
    const getRawCardUsage = (cardNumber) => {
        if (!summaryData?.cardUsages || !cardNumber) return 0;
        const normalized = cardNumber.replace(/-/g, '');
        return summaryData.cardUsages[normalized] || 0;
    };

    // 선결제 스마트 배분: 1단계 한도초과 우선 차감 → 2단계 잔여 비율 배분
    const cardDeductions = (() => {
        const totalRaw = summaryData?.billingUsage || 0;
        const prepaid = summaryData?.prepaidAmount || 0;
        if (totalRaw <= 0 || prepaid <= 0) return {};

        const activeCards = cards
            .filter(c => c.status === 'active')
            .map(c => ({
                key: c.cardNumber.replace(/-/g, ''),
                raw: getRawCardUsage(c.cardNumber),
                limit: c.cardType === 'credit' ? c.creditLimit : 0,
            }))
            .filter(c => c.raw > 0);

        if (activeCards.length === 0) return {};

        let remaining = Math.min(prepaid, totalRaw);
        const result = {};
        activeCards.forEach(c => result[c.key] = 0);

        // 1단계: 한도 초과 카드에 초과분만큼 우선 차감
        for (const card of activeCards) {
            if (remaining <= 0) break;
            if (card.limit > 0 && card.raw > card.limit) {
                const excess = card.raw - card.limit;
                const deduct = Math.min(excess, remaining);
                result[card.key] += deduct;
                remaining -= deduct;
            }
        }

        // 2단계: 잔여 금액을 현재 사용액 비율로 배분
        if (remaining > 0) {
            const withCurrent = activeCards
                .map(c => ({ ...c, current: c.raw - result[c.key] }))
                .filter(c => c.current > 0);
            const totalCurrent = withCurrent.reduce((sum, c) => sum + c.current, 0);

            if (totalCurrent > 0) {
                let distributed = 0;
                for (let i = 0; i < withCurrent.length; i++) {
                    const card = withCurrent[i];
                    let deduct;
                    if (i === withCurrent.length - 1) {
                        deduct = remaining - distributed;
                    } else {
                        deduct = Math.round(remaining * (card.current / totalCurrent));
                    }
                    deduct = Math.min(deduct, card.current);
                    result[card.key] += deduct;
                    distributed += deduct;
                }
            }
        }

        return result;
    })();

    // 선결제 차감된 카드별 사용금액
    const getCardBillingUsage = (cardNumber) => {
        const raw = getRawCardUsage(cardNumber);
        if (!raw) return 0;
        const normalized = cardNumber.replace(/-/g, '');
        return Math.max(0, raw - (cardDeductions[normalized] || 0));
    };

    // 선결제 차감 후 실제 사용금액
    const effectiveUsage = Math.max(0, (summaryData?.billingUsage || 0) - (summaryData?.prepaidAmount || 0));

    // 총 한도 및 사용액
    const totalLimit = cards.filter(c => c.status === 'active' && c.cardType === 'credit').reduce((sum, c) => sum + c.creditLimit, 0);
    const totalUsage = cards.filter(c => c.status === 'active').reduce((sum, c) => sum + c.currentUsage, 0);

    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-violet-100 rounded-xl">
                                <CreditCard className="w-6 h-6 text-violet-600" />
                            </div>
                            <div>
                                <h1 className="text-xl font-bold text-gray-900">법인카드 등록/조회</h1>
                                <p className="text-sm text-gray-500">Corporate Card Management</p>
                            </div>
                        </div>
                        <div className="flex items-center gap-2">
                            <button
                                onClick={handleAddCard}
                                className="flex items-center gap-2 px-4 py-2 bg-violet-600 hover:bg-violet-700 text-white rounded-lg transition-colors"
                            >
                                <Plus className="w-4 h-4" />
                                <span className="text-sm font-medium">카드 등록</span>
                            </button>
                        </div>
                    </div>
                </div>
            </header>

            {/* 요약 카드 */}
            <div className="grid grid-cols-2 lg:grid-cols-6 gap-4 mb-6">
                {/* 1. 등록 카드 */}
                <div className="bg-white rounded-xl border border-gray-200 p-4">
                    <div className="flex items-center justify-between mb-2">
                        <span className="text-xs text-gray-500">등록 카드</span>
                        <CreditCard className="w-4 h-4 text-gray-400" />
                    </div>
                    <p className="text-xl font-bold text-gray-900">{cards.length}장</p>
                    <p className="text-xs text-gray-400 mt-1">활성 {cards.filter(c => c.status === 'active').length}장</p>
                </div>
                {/* 2. 총 한도 */}
                <div className="bg-white rounded-xl border border-gray-200 p-4">
                    <div className="flex items-center justify-between mb-2">
                        <span className="text-xs text-gray-500">총 한도</span>
                        <DollarSign className="w-4 h-4 text-gray-400" />
                    </div>
                    <p className="text-xl font-bold text-gray-900">{formatCurrency(totalLimit)}원</p>
                    <p className="text-xs text-gray-400 mt-1">신용카드 기준</p>
                </div>
                {/* 3. 매월결제일 */}
                <div className="bg-white rounded-xl border border-blue-200 p-4 bg-blue-50/30">
                    <div className="flex items-center justify-between mb-2">
                        <span className="text-xs text-blue-700">매월결제일</span>
                        <Calendar className="w-4 h-4 text-blue-500" />
                    </div>
                    <p className="text-xl font-bold text-blue-600">
                        {summaryData?.paymentDate ? formatPaymentDate(summaryData.paymentDate) : '-'}
                    </p>
                    <p className="text-xs text-blue-400 mt-1">
                        {summaryData?.isAdjusted
                            ? `${summaryData.paymentDay}일→휴일조정`
                            : summaryData?.paymentDay ? `매월 ${summaryData.paymentDay}일` : '-'}
                    </p>
                </div>
                {/* 4. 사용금액 (청구기간) */}
                <div className="bg-white rounded-xl border border-violet-200 p-4 bg-violet-50/30">
                    <div className="flex items-center justify-between mb-2">
                        <span className="text-xs text-violet-700">사용금액</span>
                        <CreditCard className="w-4 h-4 text-violet-500" />
                    </div>
                    <p className="text-xl font-bold text-violet-600">
                        {summaryData ? formatCurrency(effectiveUsage) : '0'}원
                    </p>
                    <p className="text-xs text-violet-400 mt-1">
                        {summaryData?.billingPeriod
                            ? (summaryData.prepaidAmount > 0
                                ? `${formatCurrency(summaryData.billingUsage)}-${formatCurrency(summaryData.prepaidAmount)} 결제반영`
                                : `${summaryData.billingPeriod.start.slice(5).replace('-','/')}~${summaryData.billingPeriod.end.slice(5).replace('-','/')} 기준`)
                            : '-'}
                    </p>
                </div>
                {/* 5. 결제 */}
                <div className="bg-white rounded-xl border border-amber-200 p-4 bg-amber-50/30">
                    <div className="flex items-center justify-between mb-2">
                        <span className="text-xs text-amber-700">결제</span>
                        <button
                            onClick={openPrepaymentModal}
                            className="text-xs px-1.5 py-0.5 bg-amber-100 hover:bg-amber-200 text-amber-700 rounded transition-colors"
                        >
                            수정
                        </button>
                    </div>
                    <p className="text-xl font-bold text-amber-600">
                        {summaryData ? formatCurrency(summaryData.prepaidAmount) : '0'}원
                    </p>
                    <p className="text-xs text-amber-400 mt-1 truncate">
                        {summaryData?.prepaidItems?.length > 0 ? `${summaryData.prepaidItems.length}건` : '미입력'}
                    </p>
                </div>
                {/* 6. 잔여 한도 */}
                <div className="bg-white rounded-xl border border-emerald-200 p-4 bg-emerald-50/30">
                    <div className="flex items-center justify-between mb-2">
                        <span className="text-xs text-emerald-700">잔여 한도</span>
                        <DollarSign className="w-4 h-4 text-emerald-500" />
                    </div>
                    <p className="text-xl font-bold text-emerald-600">
                        {formatCurrency(totalLimit - effectiveUsage)}원
                    </p>
                    <p className="text-xs text-emerald-400 mt-1">한도-사용금액</p>
                </div>
            </div>

            {/* 검색 및 필터 */}
            <div className="bg-white rounded-xl border border-gray-200 p-4 mb-6">
                <div className="flex flex-col md:flex-row gap-4">
                    <div className="flex-1 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-violet-500 focus:border-violet-500"
                        />
                    </div>
                    <div className="flex gap-2">
                        <button
                            onClick={() => setFilterStatus('all')}
                            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                                filterStatus === 'all' ? 'bg-violet-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                            }`}
                        >
                            전체
                        </button>
                        <button
                            onClick={() => setFilterStatus('active')}
                            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                                filterStatus === 'active' ? 'bg-emerald-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                            }`}
                        >
                            활성
                        </button>
                        <button
                            onClick={() => setFilterStatus('inactive')}
                            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                                filterStatus === 'inactive' ? 'bg-gray-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                            }`}
                        >
                            비활성
                        </button>
                    </div>
                </div>
            </div>

            {/* 카드 목록 - 간소화된 한줄 형태 */}
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
                {/* 헤더 */}
                <div className="grid grid-cols-12 gap-4 px-4 py-3 bg-gray-50 border-b border-gray-200 text-sm font-medium text-gray-600">
                    <div className="col-span-3">카드명</div>
                    <div className="col-span-3">카드번호</div>
                    <div className="col-span-2">실사용자</div>
                    <div className="col-span-3">사용현황</div>
                    <div className="col-span-1 text-center">상태</div>
                </div>

                {/* 카드 목록 */}
                {filteredCards.map(card => (
                    <div
                        key={card.id}
                        onClick={() => handleEditCard(card)}
                        className={`grid grid-cols-12 gap-4 px-4 py-3 border-b border-gray-100 cursor-pointer transition-colors hover:bg-violet-50 ${
                            card.status !== 'active' ? 'opacity-60 bg-gray-50' : ''
                        }`}
                    >
                        {/* 카드명 + 카드사 */}
                        <div className="col-span-3 flex items-center gap-2">
                            <div className={`p-1.5 rounded-lg ${card.status === 'active' ? 'bg-violet-100' : 'bg-gray-100'}`}>
                                <CreditCard className={`w-4 h-4 ${card.status === 'active' ? 'text-violet-600' : 'text-gray-400'}`} />
                            </div>
                            <div className="min-w-0">
                                <p className="font-medium text-gray-900 truncate">{card.cardName}</p>
                                <p className="text-xs text-gray-500">{card.cardCompany}</p>
                            </div>
                        </div>

                        {/* 카드번호 */}
                        <div className="col-span-3 flex items-center">
                            <p className="font-mono text-sm text-gray-700">{card.cardNumber}</p>
                        </div>

                        {/* 실사용자 */}
                        <div className="col-span-2 flex items-center">
                            <p className="text-sm text-gray-900">{card.actualUser || '-'}</p>
                        </div>

                        {/* 사용현황 */}
                        <div className="col-span-3 flex items-center gap-2">
                            {(() => {
                                const billingUsage = getCardBillingUsage(card.cardNumber);
                                if (card.cardType === 'debit') {
                                    return billingUsage > 0 ? (
                                        <div className="flex-1">
                                            <div className="flex items-center justify-between text-xs">
                                                <span className="text-gray-500">{formatCurrency(billingUsage)}원</span>
                                                <span className="px-1.5 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded">체크</span>
                                            </div>
                                        </div>
                                    ) : (
                                        <span className="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-medium rounded">체크카드</span>
                                    );
                                }
                                if (card.creditLimit > 0) {
                                    const pct = getUsagePercent(billingUsage, card.creditLimit);
                                    return (
                                        <div className="flex-1">
                                            <div className="flex items-center justify-between text-xs mb-1">
                                                <span className="text-gray-500">{formatCurrency(billingUsage)}원</span>
                                                <span className="text-gray-400">{pct}%</span>
                                            </div>
                                            <div className="w-full bg-gray-200 rounded-full h-1.5">
                                                <div
                                                    className={`h-1.5 rounded-full ${getUsageColor(pct)}`}
                                                    style={{ width: `${Math.min(pct, 100)}%` }}
                                                ></div>
                                            </div>
                                        </div>
                                    );
                                }
                                return billingUsage > 0 ? (
                                    <span className="text-xs text-gray-500">{formatCurrency(billingUsage)}원</span>
                                ) : (
                                    <span className="px-2 py-0.5 bg-violet-100 text-violet-700 text-xs font-medium rounded">신용카드</span>
                                );
                            })()}
                        </div>

                        {/* 상태 */}
                        <div className="col-span-1 flex items-center justify-center">
                            <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                                card.status === 'active' ? 'bg-emerald-100 text-emerald-700' : 'bg-gray-100 text-gray-500'
                            }`}>
                                {card.status === 'active' ? '활성' : '비활성'}
                            </span>
                        </div>
                    </div>
                ))}

                {loading && (
                    <div className="text-center py-12 text-gray-400">
                        <div className="animate-spin w-8 h-8 border-4 border-violet-500 border-t-transparent rounded-full mx-auto mb-4"></div>
                        <p>카드 목록을 불러오는 중...</p>
                    </div>
                )}

                {!loading && filteredCards.length === 0 && (
                    <div className="text-center py-12 text-gray-400">
                        <CreditCard className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>등록된 카드가 없습니다.</p>
                    </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); setEditingCard(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>
                                <label className="block text-sm font-medium text-gray-700 mb-1">카드명 *</label>
                                <input
                                    type="text"
                                    value={formData.cardName}
                                    onChange={(e) => setFormData(prev => ({ ...prev, cardName: e.target.value }))}
                                    placeholder="예: 업무용 법인카드"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500"
                                />
                            </div>

                            <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.cardCompany}
                                        onChange={(e) => setFormData(prev => ({ ...prev, cardCompany: e.target.value }))}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500"
                                    >
                                        {cardCompanies.map(company => (
                                            <option key={company} value={company}>{company}</option>
                                        ))}
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">카드종류</label>
                                    <select
                                        value={formData.cardType}
                                        onChange={(e) => setFormData(prev => ({ ...prev, cardType: e.target.value }))}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500"
                                    >
                                        <option value="credit">신용카드</option>
                                        <option value="debit">체크카드</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="text"
                                        value={formData.cardNumber}
                                        onChange={(e) => setFormData(prev => ({ ...prev, cardNumber: e.target.value }))}
                                        placeholder="1234-5678-9012-3456"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500 font-mono"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">이용자명 *</label>
                                    <input
                                        type="text"
                                        value={formData.cardHolderName}
                                        onChange={(e) => setFormData(prev => ({ ...prev, cardHolderName: e.target.value }))}
                                        placeholder="카드 명의자 (법인명)"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-3 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">유효기간(년도/월)</label>
                                    <input
                                        type="text"
                                        value={formData.expiryDate}
                                        onChange={(e) => {
                                            let val = e.target.value.replace(/[^\d]/g, '');
                                            if (val.length > 4) val = val.slice(0, 4);
                                            if (val.length >= 2) val = val.slice(0, 2) + '/' + val.slice(2);
                                            setFormData(prev => ({ ...prev, expiryDate: val }));
                                        }}
                                        placeholder="YY/MM"
                                        maxLength={5}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500 font-mono text-center"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">CVC</label>
                                    <input
                                        type="text"
                                        value={formData.cvc}
                                        onChange={(e) => {
                                            const val = e.target.value.replace(/[^\d]/g, '').slice(0, 3);
                                            setFormData(prev => ({ ...prev, cvc: val }));
                                        }}
                                        placeholder="3자리"
                                        maxLength={3}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500 font-mono text-center"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">상태</label>
                                    <select
                                        value={formData.status}
                                        onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500"
                                    >
                                        <option value="active">활성</option>
                                        <option value="inactive">비활성</option>
                                    </select>
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">실사용자 *</label>
                                <input
                                    type="text"
                                    value={formData.actualUser}
                                    onChange={(e) => setFormData(prev => ({ ...prev, actualUser: e.target.value }))}
                                    placeholder="실제 카드 사용자명"
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500"
                                />
                            </div>

                            {formData.cardType === 'credit' && (
                                <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.paymentDay}
                                            onChange={(e) => setFormData(prev => ({ ...prev, paymentDay: parseInt(e.target.value) }))}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500"
                                        >
                                            {[1, 5, 10, 14, 15, 20, 25, 27].map(day => (
                                                <option key={day} value={day}>매월 {day}일</option>
                                            ))}
                                        </select>
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">사용한도</label>
                                        <input
                                            type="text"
                                            value={formatInputCurrency(formData.creditLimit)}
                                            onChange={(e) => setFormData(prev => ({ ...prev, creditLimit: parseInputCurrency(e.target.value) }))}
                                            placeholder="0"
                                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500 text-right"
                                        />
                                    </div>
                                </div>
                            )}

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">메모</label>
                                <textarea
                                    value={formData.memo}
                                    onChange={(e) => setFormData(prev => ({ ...prev, memo: e.target.value }))}
                                    placeholder="카드 용도나 특이사항..."
                                    rows={2}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500 resize-none"
                                />
                            </div>
                        </div>

                        <div className="flex gap-3 mt-6">
                            {modalMode === 'edit' && (
                                <>
                                    <button
                                        onClick={() => handleDeactivateCard(editingCard.id)}
                                        className="px-4 py-2 bg-gray-500 hover:bg-gray-600 text-white rounded-lg flex items-center gap-2"
                                        title="비활성화 (데이터 유지)"
                                    >
                                        <span>🚫</span> 비활성화
                                    </button>
                                    <button
                                        onClick={() => handlePermanentDeleteCard(editingCard.id)}
                                        className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg flex items-center gap-2"
                                        title="영구삭제 (복구불가)"
                                    >
                                        <span>🗑️</span> 영구삭제
                                    </button>
                                </>
                            )}
                            <button
                                onClick={() => { setShowModal(false); setEditingCard(null); }}
                                className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 flex items-center justify-center gap-2"
                            >
                                <span>✕</span> 취소
                            </button>
                            <button
                                onClick={handleSaveCard}
                                className="flex-1 px-4 py-2 bg-violet-600 hover:bg-violet-700 text-white rounded-lg flex items-center justify-center gap-2"
                            >
                                <span>✓</span> {modalMode === 'add' ? '등록' : '저장'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
            {/* 결제 내역 수정 모달 */}
            {showPrepaymentModal && (
                <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-3xl mx-4 max-h-[90vh] overflow-y-auto">
                        <div className="flex items-center justify-between mb-4">
                            <h3 className="text-lg font-bold text-gray-900">결제 내역 수정</h3>
                            <button
                                onClick={() => setShowPrepaymentModal(false)}
                                className="p-1 hover:bg-gray-100 rounded-lg"
                            >
                                <X className="w-5 h-5 text-gray-500" />
                            </button>
                        </div>

                        {/* 항목 헤더 */}
                        <div className="flex gap-3 mb-2 text-xs font-medium text-gray-500">
                            <div style={{width: '160px', flexShrink: 0}}>날짜</div>
                            <div style={{width: '130px', flexShrink: 0}}>금액</div>
                            <div className="flex-1">내용</div>
                            <div style={{width: '32px', flexShrink: 0}}></div>
                        </div>

                        {/* 항목 리스트 */}
                        <div className="space-y-2">
                            {prepaymentItems.map((item, index) => (
                                <div key={index} className="flex gap-3 items-start">
                                    <div style={{width: '160px', flexShrink: 0}}>
                                        <input
                                            type="date"
                                            value={item.date}
                                            onChange={(e) => updatePrepaymentItem(index, 'date', e.target.value)}
                                            className="w-full px-2 py-1.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 text-sm"
                                        />
                                    </div>
                                    <div style={{width: '130px', flexShrink: 0}}>
                                        <input
                                            type="text"
                                            value={formatInputCurrency(item.amount)}
                                            onChange={(e) => updatePrepaymentItem(index, 'amount', parseInputCurrency(e.target.value))}
                                            placeholder="0"
                                            className="w-full px-2 py-1.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 text-sm text-right"
                                        />
                                    </div>
                                    <div className="flex-1">
                                        <input
                                            type="text"
                                            value={item.description}
                                            onChange={(e) => updatePrepaymentItem(index, 'description', e.target.value)}
                                            placeholder="결제 내용"
                                            maxLength={200}
                                            className="w-full px-2 py-1.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 text-sm"
                                        />
                                    </div>
                                    <div style={{width: '32px', flexShrink: 0}} className="flex items-center justify-center pt-1">
                                        <button
                                            onClick={() => removePrepaymentItem(index)}
                                            disabled={prepaymentItems.length <= 1}
                                            className={`p-1 rounded transition-colors ${prepaymentItems.length <= 1 ? 'text-gray-300 cursor-not-allowed' : 'text-red-400 hover:text-red-600 hover:bg-red-50'}`}
                                            title="항목 삭제"
                                        >
                                            <Trash2 className="w-4 h-4" />
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>

                        {/* 항목 추가 버튼 */}
                        <button
                            onClick={addPrepaymentItem}
                            className="mt-3 flex items-center gap-1 text-sm text-amber-600 hover:text-amber-700 font-medium"
                        >
                            <Plus className="w-4 h-4" />
                            항목 추가
                        </button>

                        {/* 합계 */}
                        <div className="mt-4 pt-3 border-t border-gray-200 flex items-center justify-between">
                            <span className="text-sm font-medium text-gray-700">합계</span>
                            <span className="text-lg font-bold text-amber-600">{formatCurrency(prepaymentTotal)}원</span>
                        </div>

                        {/* 버튼 */}
                        <div className="flex gap-3 mt-5">
                            <button
                                onClick={() => setShowPrepaymentModal(false)}
                                className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                            >
                                취소
                            </button>
                            <button
                                onClick={handleSavePrepayment}
                                className="flex-1 px-4 py-2 bg-amber-500 hover:bg-amber-600 text-white rounded-lg"
                            >
                                저장
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

// React 앱 마운트
const rootElement = document.getElementById('corporate-cards-root');
if (rootElement) {
    ReactDOM.createRoot(rootElement).render(<CorporateCardsManagement />);
}
</script>
@endverbatim
@endpush
