@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="vat-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 Calculator = createIcon('calculator');
const Plus = createIcon('plus');
const Search = createIcon('search');
const Download = createIcon('download');
const X = createIcon('x');
const Edit = createIcon('edit');
const Trash2 = createIcon('trash-2');
const FileText = createIcon('file-text');
const TrendingUp = createIcon('trending-up');
const TrendingDown = createIcon('trending-down');
const RefreshCw = createIcon('refresh-cw');

function VatManagement() {
    const [vatRecords, setVatRecords] = useState([]);
    const [stats, setStats] = useState({ salesSupply: 0, salesVat: 0, purchaseSupply: 0, purchaseVat: 0, hometaxSalesSupply: 0, hometaxSalesVat: 0, hometaxPurchaseSupply: 0, hometaxPurchaseVat: 0, manualPurchaseSupply: 0, manualPurchaseVat: 0, exemptSupply: 0, cardPurchaseSupply: 0, cardPurchaseVat: 0, total: 0 });
    const [periods, setPeriods] = useState([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    const [searchTerm, setSearchTerm] = useState('');
    const now = new Date();
    const month = now.getMonth();
    const currentPeriodCode = month < 3 ? '1P' : month < 6 ? '1C' : month < 9 ? '2P' : '2C';
    const [filterPeriod, setFilterPeriod] = useState(`${now.getFullYear()}-${currentPeriodCode}`);
    const [filterType, setFilterType] = useState('all');
    const [filterTaxType, setFilterTaxType] = useState('all');
    const [filterStatus, setFilterStatus] = useState('all');

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

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

    // 기본 기간 옵션 (1P/1C/2P/2C 형식)
    const defaultPeriods = (() => {
        const y = now.getFullYear();
        const list = [];
        for (let i = 0; i <= 2; i++) {
            list.push(`${y - i}-1P`, `${y - i}-1C`, `${y - i}-2P`, `${y - i}-2C`);
        }
        return list;
    })();
    const allPeriods = [...new Set([...periods, ...defaultPeriods])].sort().reverse();

    const initialFormState = {
        period: filterPeriod,
        type: 'sales',
        taxType: 'taxable',
        partnerName: '',
        invoiceNo: '',
        invoiceDate: now.toISOString().split('T')[0],
        supplyAmount: '',
        vatAmount: '',
        totalAmount: '',
        status: 'pending',
        memo: ''
    };
    const [formData, setFormData] = useState(initialFormState);

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

    const handleSupplyAmountChange = (value) => {
        const supply = parseInt(parseInputCurrency(value)) || 0;
        const taxType = formData.taxType;
        const vat = taxType === 'taxable' ? Math.floor(supply * 0.1) : 0;
        const total = supply + vat;
        setFormData(prev => ({
            ...prev,
            supplyAmount: value,
            vatAmount: vat.toString(),
            totalAmount: total.toString()
        }));
    };

    const handleTaxTypeChange = (newTaxType) => {
        const supply = parseInt(parseInputCurrency(formData.supplyAmount)) || 0;
        const vat = newTaxType === 'taxable' ? Math.floor(supply * 0.1) : 0;
        const total = supply + vat;
        setFormData(prev => ({
            ...prev,
            taxType: newTaxType,
            vatAmount: vat.toString(),
            totalAmount: total.toString()
        }));
    };

    const fetchRecords = async (period) => {
        setLoading(true);
        try {
            const params = new URLSearchParams({ period: period || filterPeriod });
            const res = await fetch(`/finance/vat/list?${params}`);
            const data = await res.json();
            if (data.success) {
                setVatRecords(data.data);
                setStats(data.stats);
                if (data.periods && data.periods.length > 0) {
                    setPeriods(data.periods);
                }
            }
        } catch (err) {
            console.error('부가세 조회 실패:', err);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { fetchRecords(filterPeriod); }, [filterPeriod]);

    const filteredRecords = vatRecords.filter(item => {
        const matchesSearch = item.partnerName.toLowerCase().includes(searchTerm.toLowerCase());
        const matchesTaxType = filterTaxType === 'all' || item.taxType === filterTaxType;
        if (!matchesSearch || !matchesTaxType) return false;

        if (filterType === 'all') return true;
        if (filterType === 'electronic_sales') return item.source === 'hometax' && item.type === 'sales' && item.taxType !== 'exempt';
        if (filterType === 'paper_sales') return item.source === 'manual' && item.type === 'sales' && item.taxType !== 'exempt';
        if (filterType === 'electronic_purchase') return item.source === 'hometax' && item.type === 'purchase' && item.taxType !== 'exempt';
        if (filterType === 'paper_purchase') return item.source === 'manual' && item.type === 'purchase' && item.taxType !== 'exempt';
        if (filterType === 'exempt_purchase') return item.taxType === 'exempt';
        if (filterType === 'purchase_card') return item.source === 'card';
        return true;
    });

    const salesVat = stats.salesVat || 0;
    const purchaseVat = stats.purchaseVat || 0;
    const salesSupply = stats.salesSupply || 0;
    const purchaseSupply = stats.purchaseSupply || 0;
    const hometaxSalesSupply = stats.hometaxSalesSupply || 0;
    const hometaxSalesVat = stats.hometaxSalesVat || 0;
    const hometaxPurchaseSupply = stats.hometaxPurchaseSupply || 0;
    const hometaxPurchaseVat = stats.hometaxPurchaseVat || 0;
    const manualPurchaseSupply = stats.manualPurchaseSupply || 0;
    const manualPurchaseVat = stats.manualPurchaseVat || 0;
    const exemptSupply = stats.exemptSupply || 0;
    const cardPurchaseSupply = stats.cardPurchaseSupply || 0;
    const cardPurchaseVat = stats.cardPurchaseVat || 0;
    const netVat = salesVat - purchaseVat;

    // 확정 기간일 때 예정 환급세액만 차감 (납부세액은 차감하지 않음)
    const isConfirmedPeriod = filterPeriod.endsWith('C');
    const preliminaryVat = stats.preliminaryVat; // 양수=납부, 음수=환급, null=예정아님
    // 예정 기간이 환급(음수)일 때만 차감 표시
    const hasPreliminary = isConfirmedPeriod && preliminaryVat !== null && preliminaryVat !== undefined && preliminaryVat < 0;
    const preliminaryDeduction = hasPreliminary ? Math.abs(preliminaryVat) : 0;
    const finalNetVat = netVat - preliminaryDeduction;

    const handleAdd = () => { setModalMode('add'); setFormData({ ...initialFormState, period: filterPeriod }); setShowModal(true); };
    const handleEdit = (item) => {
        if (item.isCardTransaction || item.isHometax) return;
        setModalMode('edit');
        setEditingItem(item);
        setFormData({
            ...item,
            supplyAmount: item.supplyAmount.toString(),
            vatAmount: item.vatAmount.toString(),
            totalAmount: item.totalAmount.toString()
        });
        setShowModal(true);
    };
    const handleSave = async () => {
        if (!formData.partnerName || !formData.supplyAmount) { alert('필수 항목을 입력해주세요.'); return; }
        setSaving(true);
        try {
            const payload = {
                ...formData,
                supplyAmount: parseInt(parseInputCurrency(formData.supplyAmount)) || 0,
                vatAmount: parseInt(parseInputCurrency(formData.vatAmount)) || 0,
                totalAmount: parseInt(parseInputCurrency(formData.totalAmount)) || 0,
            };
            const url = modalMode === 'add' ? '/finance/vat/store' : `/finance/vat/${editingItem.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);
            setEditingItem(null);
            fetchRecords(filterPeriod);
        } catch (err) {
            console.error('저장 실패:', err);
            alert('저장에 실패했습니다.');
        } finally {
            setSaving(false);
        }
    };
    const handleDelete = async (id) => {
        if (!confirm('정말 삭제하시겠습니까?')) return;
        try {
            const res = await fetch(`/finance/vat/${id}`, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': csrfToken },
            });
            if (res.ok) {
                setShowModal(false);
                fetchRecords(filterPeriod);
            }
        } catch (err) {
            console.error('삭제 실패:', err);
            alert('삭제에 실패했습니다.');
        }
    };

    const handleDownload = () => {
        const rows = [['부가세 관리', getPeriodLabel(filterPeriod)], [], ['구분', '세금구분', '거래처', '작성일자', '공급가액', '부가세', '합계', '상태'],
            ...filteredRecords.map(item => [getTypeLabel(item.type, item.isCardTransaction, item.source), getTaxTypeLabel(item.taxType), item.partnerName, item.invoiceDate, item.supplyAmount, item.vatAmount, item.totalAmount, getStatusLabel(item.status)])];
        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 = `부가세관리_${filterPeriod}.csv`; link.click();
    };

    const getTypeLabel = (type, isCard = false, source = 'manual') => {
        if (source === 'hometax' && type === 'sales') return '매출(전자)';
        if (source === 'hometax' && type === 'purchase') return '매입(전자)';
        if (source === 'card' || isCard) return '매입(신용카드)';
        if (source === 'manual') {
            return type === 'sales' ? '매출(종이)' : '매입(종이)';
        }
        const labels = { 'sales': '매출', 'purchase': '매입' };
        return labels[type] || type;
    };

    const getTaxTypeLabel = (taxType) => {
        const labels = { 'taxable': '과세', 'zero_rated': '영세', 'exempt': '면세' };
        return labels[taxType] || taxType;
    };

    const getTaxTypeStyle = (taxType) => {
        const styles = {
            'taxable': 'bg-blue-100 text-blue-700',
            'zero_rated': 'bg-teal-100 text-teal-700',
            'exempt': 'bg-gray-100 text-gray-600'
        };
        return styles[taxType] || 'bg-gray-100 text-gray-700';
    };

    const getStatusLabel = (status) => {
        const labels = { 'pending': '미신고', 'filed': '신고완료', 'paid': '납부완료' };
        return labels[status] || status;
    };

    const getStatusStyle = (status) => {
        const styles = {
            'pending': 'bg-amber-100 text-amber-700',
            'filed': 'bg-blue-100 text-blue-700',
            'paid': 'bg-emerald-100 text-emerald-700'
        };
        return styles[status] || 'bg-gray-100 text-gray-700';
    };

    const getTypeStyle = (type, isCard = false, source = 'manual') => {
        if (source === 'card' || isCard) return 'bg-purple-100 text-purple-700';
        if (source === 'hometax' && type === 'sales') return 'bg-emerald-100 text-emerald-700';
        if (source === 'hometax' && type === 'purchase') return 'bg-pink-100 text-pink-700';
        if (source === 'manual' && type === 'sales') return 'bg-emerald-50 text-emerald-600 border border-emerald-200';
        if (source === 'manual' && type === 'purchase') return 'bg-pink-50 text-pink-600 border border-pink-200';
        const styles = {
            'sales': 'bg-emerald-50 text-emerald-600',
            'purchase': 'bg-pink-50 text-pink-600'
        };
        return styles[type] || 'bg-gray-100 text-gray-700';
    };

    const getPeriodLabel = (period) => {
        const [year, code] = period.split('-');
        const labels = { '1P': '1기 예정', '1C': '1기 확정', '2P': '2기 예정', '2C': '2기 확정' };
        return `${year}년 ${labels[code] || code}`;
    };

    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 flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <div className="p-2 bg-indigo-100 rounded-xl"><Calculator 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">VAT Management</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={handleAdd} className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg"><Plus className="w-4 h-4" /><span className="text-sm font-medium">수동 등록</span></button>
                    </div>
                </div>
            </header>

            {/* 기간 선택 및 요약 */}
            <div className="bg-white rounded-xl border border-gray-200 p-6 mb-6">
                <div className="flex flex-wrap items-center gap-6">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">신고기간</label>
                        <select value={filterPeriod} onChange={(e) => setFilterPeriod(e.target.value)} className="px-4 py-2 pr-10 border border-gray-300 rounded-lg text-lg font-medium min-w-[200px]">
                            {allPeriods.map(p => <option key={p} value={p}>{getPeriodLabel(p)}</option>)}
                        </select>
                    </div>
                    <div className="flex-1 grid grid-cols-1 md:grid-cols-4 gap-4">
                        <div className="bg-emerald-50 rounded-lg p-4">
                            <div className="flex items-center gap-2 mb-1"><TrendingUp className="w-4 h-4 text-emerald-600" /><span className="text-sm text-emerald-700">매출세액</span></div>
                            <p className="text-xl font-bold text-emerald-600">{formatCurrency(salesVat)}원</p>
                            <p className="text-xs text-gray-500">공급가액: {formatCurrency(salesSupply)}원</p>
                        </div>
                        <div className="bg-pink-50 rounded-lg p-4">
                            <div className="flex items-center gap-2 mb-1"><TrendingDown className="w-4 h-4 text-pink-600" /><span className="text-sm text-pink-700">매입세액</span></div>
                            <p className="text-xl font-bold text-pink-600">{formatCurrency(purchaseVat)}원</p>
                            <p className="text-xs text-gray-500">공급가액: {formatCurrency(purchaseSupply)}원</p>
                        </div>
                        <div className={`rounded-lg p-4 ${(hasPreliminary ? finalNetVat : netVat) >= 0 ? 'bg-amber-50' : 'bg-blue-50'}`}>
                            <div className="flex items-center gap-2 mb-1"><Calculator className={`w-4 h-4 ${(hasPreliminary ? finalNetVat : netVat) >= 0 ? 'text-amber-600' : 'text-blue-600'}`} /><span className={`text-sm ${(hasPreliminary ? finalNetVat : netVat) >= 0 ? 'text-amber-700' : 'text-blue-700'}`}>{(hasPreliminary ? finalNetVat : netVat) >= 0 ? '납부세액' : '환급세액'}</span></div>
                            <p className={`text-xl font-bold ${(hasPreliminary ? finalNetVat : netVat) >= 0 ? 'text-amber-600' : 'text-blue-600'}`}>{formatCurrency(Math.abs(hasPreliminary ? finalNetVat : netVat))}원</p>
                            {hasPreliminary && preliminaryDeduction > 0 && (
                                <p className="text-xs text-gray-500">예정 차감 전: {formatCurrency(Math.abs(netVat))}원</p>
                            )}
                        </div>
                        <div className="flex items-center">
                        </div>
                    </div>
                </div>
            </div>

            {/* 요약 테이블 */}
            <div className="bg-white rounded-xl border border-gray-200 mb-6 overflow-hidden">
                <div className="px-6 py-3 bg-gray-50 border-b border-gray-200">
                    <h3 className="font-medium text-gray-900">{getPeriodLabel(filterPeriod)} 부가세 요약</h3>
                </div>
                <table className="w-full">
                    <thead className="bg-gray-100">
                        <tr>
                            <th className="px-6 py-2 text-left text-xs font-semibold text-gray-600">구분</th>
                            <th className="px-6 py-2 text-right text-xs font-semibold text-gray-600">공급가액</th>
                            <th className="px-6 py-2 text-right text-xs font-semibold text-gray-600">세액</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr className="border-b border-gray-100">
                            <td className="px-6 py-3 text-sm">매출(전자세금계산서)</td>
                            <td className="px-6 py-3 text-sm text-right">{formatCurrency(hometaxSalesSupply)}원</td>
                            <td className="px-6 py-3 text-sm text-right text-emerald-600 font-medium">{formatCurrency(hometaxSalesVat)}원</td>
                        </tr>
                        <tr className="border-b border-gray-100">
                            <td className="px-6 py-3 text-sm">매입(전자세금계산서)</td>
                            <td className="px-6 py-3 text-sm text-right">{formatCurrency(hometaxPurchaseSupply)}원</td>
                            <td className="px-6 py-3 text-sm text-right text-pink-600 font-medium">({formatCurrency(hometaxPurchaseVat)}원)</td>
                        </tr>
                        <tr className="border-b border-gray-100 bg-pink-50/30">
                            <td className="px-6 py-3 text-sm">매입(종이세금계산서)</td>
                            <td className="px-6 py-3 text-sm text-right">{formatCurrency(manualPurchaseSupply)}원</td>
                            <td className="px-6 py-3 text-sm text-right text-pink-600 font-medium">({formatCurrency(manualPurchaseVat)}원)</td>
                        </tr>
                        <tr className="border-b border-gray-100 bg-gray-50/50">
                            <td className="px-6 py-3 text-sm text-gray-600">매입(계산서)</td>
                            <td className="px-6 py-3 text-sm text-right text-gray-600">{formatCurrency(exemptSupply)}원</td>
                            <td className="px-6 py-3 text-sm text-right text-gray-400">-</td>
                        </tr>
                        <tr className="border-b border-gray-100 bg-purple-50/50">
                            <td className="px-6 py-3 text-sm text-purple-700">매입(신용카드)</td>
                            <td className="px-6 py-3 text-sm text-right text-purple-600">{formatCurrency(cardPurchaseSupply)}원</td>
                            <td className="px-6 py-3 text-sm text-right text-purple-600 font-medium">({formatCurrency(cardPurchaseVat)}원)</td>
                        </tr>
                        {hasPreliminary && preliminaryDeduction > 0 && (
                            <>
                                <tr className="border-b border-gray-200 bg-gray-50/50">
                                    <td className="px-6 py-3 text-sm font-medium">
                                        {netVat >= 0 ? '납부세액(확정 자체)' : '환급세액(확정 자체)'}
                                    </td>
                                    <td className="px-6 py-3 text-sm text-right">-</td>
                                    <td className={`px-6 py-3 text-sm text-right font-medium ${netVat >= 0 ? 'text-amber-600' : 'text-blue-600'}`}>
                                        {formatCurrency(Math.abs(netVat))}원
                                    </td>
                                </tr>
                                <tr className="border-b border-gray-200 bg-indigo-50/50">
                                    <td className="px-6 py-3 text-sm text-indigo-700 font-medium">
                                        예정신고 미환급세액
                                    </td>
                                    <td className="px-6 py-3 text-sm text-right">-</td>
                                    <td className="px-6 py-3 text-sm text-right text-indigo-600 font-medium">
                                        ({formatCurrency(preliminaryDeduction)}원)
                                    </td>
                                </tr>
                            </>
                        )}
                        <tr className="bg-gray-50 font-bold">
                            <td className="px-6 py-3 text-sm">
                                {hasPreliminary
                                    ? (finalNetVat >= 0 ? '최종 납부세액' : '최종 환급세액')
                                    : (netVat >= 0 ? '납부세액' : '환급세액')}
                            </td>
                            <td className="px-6 py-3 text-sm text-right">-</td>
                            <td className={`px-6 py-3 text-sm text-right ${(hasPreliminary ? finalNetVat : netVat) >= 0 ? 'text-amber-600' : 'text-blue-600'}`}>
                                {formatCurrency(Math.abs(hasPreliminary ? finalNetVat : netVat))}원
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div className="bg-white rounded-xl border border-gray-200 p-4 mb-6">
                <div className="flex flex-wrap items-center justify-center gap-3">
                    <div className="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="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 w-64" />
                    </div>
                    <select value={filterType} onChange={(e) => setFilterType(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg">
                        <option value="all">전체 유형</option>
                        <option value="electronic_sales">매출(전자세금계산서)</option>
                        <option value="electronic_purchase">매입(전자세금계산서)</option>
                        <option value="paper_purchase">매입(종이세금계산서)</option>
                        <option value="exempt_purchase">매입(계산서)</option>
                        <option value="purchase_card">매입(신용카드)</option>
                    </select>
                    <select value={filterTaxType} onChange={(e) => setFilterTaxType(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg">
                        <option value="all">전체 세금구분</option>
                        <option value="taxable">과세</option>
                        <option value="zero_rated">영세</option>
                        <option value="exempt">면세</option>
                    </select>
                    <button onClick={() => { setSearchTerm(''); setFilterType('all'); setFilterTaxType('all'); }} className="flex items-center gap-2 px-3 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">
                        <RefreshCw className="w-4 h-4" /><span className="text-sm">초기화</span>
                    </button>
                </div>
            </div>

            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
                <table className="w-full">
                    <thead className="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">구분</th>
                            <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">세금구분</th>
                            <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">거래처</th>
                            <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">작성일자</th>
                            <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600">공급가액</th>
                            <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600">부가세</th>
                            <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600">합계</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                        {loading ? (
                            <tr><td colSpan="7" className="px-6 py-12 text-center text-gray-400"><div className="flex items-center justify-center gap-2"><svg className="animate-spin h-5 w-5 text-gray-400" 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></td></tr>
                        ) : filteredRecords.length === 0 ? (
                            <tr><td colSpan="7" className="px-6 py-12 text-center text-gray-400">데이터가 없습니다.</td></tr>
                        ) : filteredRecords.map(item => {
                            const isReadOnly = item.isCardTransaction || item.isHometax;
                            const rowBg = item.source === 'card' ? 'bg-purple-50/40'
                                : item.source === 'hometax' && item.type === 'sales' ? 'bg-emerald-50/40'
                                : item.source === 'hometax' && item.type === 'purchase' ? 'bg-pink-50/40'
                                : '';
                            return (
                            <tr key={item.id} onClick={() => handleEdit(item)} className={`hover:bg-gray-50 ${rowBg} ${isReadOnly ? 'cursor-default' : 'cursor-pointer'}`}>
                                <td className="px-6 py-4"><span className={`px-2 py-1 rounded text-xs font-medium ${getTypeStyle(item.type, item.isCardTransaction, item.source)}`}>{getTypeLabel(item.type, item.isCardTransaction, item.source)}</span></td>
                                <td className="px-6 py-4"><span className={`px-2 py-1 rounded text-xs font-medium ${getTaxTypeStyle(item.taxType)}`}>{getTaxTypeLabel(item.taxType)}</span></td>
                                <td className="px-6 py-4 text-sm font-medium text-gray-900">{item.partnerName}</td>
                                <td className="px-6 py-4 text-sm text-gray-600">{item.invoiceDate}</td>
                                <td className="px-6 py-4 text-sm font-medium text-right text-gray-900">{formatCurrency(item.supplyAmount)}원</td>
                                <td className="px-6 py-4 text-sm text-right text-gray-600">{formatCurrency(item.vatAmount)}원</td>
                                <td className="px-6 py-4 text-sm font-bold text-right text-indigo-600">{formatCurrency(item.totalAmount)}원</td>
                            </tr>
                            );
                        })}
                    </tbody>
                </table>
            </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)} 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-3 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">신고기간 *</label><select value={formData.period} onChange={(e) => setFormData(prev => ({ ...prev, period: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">{allPeriods.map(p => <option key={p} value={p}>{getPeriodLabel(p)}</option>)}</select></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">구분 *</label><select value={formData.type} onChange={(e) => setFormData(prev => ({ ...prev, type: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg"><option value="sales">매출</option><option value="purchase">매입</option></select></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">세금구분</label><select value={formData.taxType} onChange={(e) => handleTaxTypeChange(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-lg"><option value="taxable">과세</option><option value="zero_rated">영세</option><option value="exempt">면세</option></select></div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">거래처 *</label>
                                <input type="text" value={formData.partnerName} onChange={(e) => setFormData(prev => ({ ...prev, partnerName: 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="date" value={formData.invoiceDate} onChange={(e) => setFormData(prev => ({ ...prev, invoiceDate: 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="text" value={formatInputCurrency(formData.supplyAmount)} onChange={(e) => handleSupplyAmountChange(e.target.value)} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></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={formatInputCurrency(formData.vatAmount)} readOnly className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right bg-gray-50" /></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">합계금액</label><input type="text" value={formatInputCurrency(formData.totalAmount)} readOnly className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right bg-gray-50" /></div>
                            </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.status} onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg"><option value="pending">미신고</option><option value="filed">신고완료</option><option value="paid">납부완료</option></select></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>
                        <div className="flex gap-3 mt-6">
                            {modalMode === 'edit' && <button onClick={() => handleDelete(editingItem.id)} className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg">삭제</button>}
                            <button onClick={() => setShowModal(false)} 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-blue-600 hover:bg-blue-700 text-white rounded-lg disabled:opacity-50">{saving ? '저장 중...' : (modalMode === 'add' ? '등록' : '저장')}</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

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