@extends('layouts.app')

@section('title', '법인차량관리')

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

@section('content')
<div id="corporate-vehicles-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 Car = createIcon('car');
const Plus = createIcon('plus');
const Search = createIcon('search');
const Download = createIcon('download');
const X = createIcon('x');
const Gauge = createIcon('gauge');
const Loader = createIcon('loader-2');

function CorporateVehiclesManagement() {
    const [vehicles, setVehicles] = useState([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    const [searchTerm, setSearchTerm] = useState('');
    const [filterStatus, setFilterStatus] = useState('all');
    const [filterOwnership, setFilterOwnership] = useState('all');

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

    const types = ['승용차', '승합차', '화물차', 'SUV'];
    const ownershipTypes = [
        { value: 'corporate', label: '법인차량' },
        { value: 'rent', label: '렌트차량' },
        { value: 'lease', label: '리스차량' }
    ];

    const getOwnershipLabel = (type) => {
        const found = ownershipTypes.find(t => t.value === type);
        return found ? found.label : type;
    };

    const getOwnershipColor = (type) => {
        switch(type) {
            case 'corporate': return 'bg-blue-100 text-blue-700';
            case 'rent': return 'bg-purple-100 text-purple-700';
            case 'lease': return 'bg-orange-100 text-orange-700';
            default: return 'bg-gray-100 text-gray-700';
        }
    };

    const initialFormState = {
        plate_number: '',
        model: '',
        vehicle_type: '승용차',
        ownership_type: 'corporate',
        year: new Date().getFullYear(),
        driver: '',
        status: 'active',
        mileage: '',
        memo: '',
        purchase_date: '',
        purchase_price: '',
        contract_date: '',
        rent_company: '',
        rent_company_tel: '',
        rent_period: '',
        agreed_mileage: '',
        vehicle_price: '',
        residual_value: '',
        deposit: '',
        monthly_rent: '',
        monthly_rent_tax: '',
        insurance_company: '',
        insurance_company_tel: ''
    };
    const [formData, setFormData] = useState(initialFormState);

    const formatCurrency = (num) => num ? Number(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 loadVehicles = async () => {
        try {
            setLoading(true);
            const response = await fetch('/finance/corporate-vehicles/list');
            const result = await response.json();
            if (result.success) {
                setVehicles(result.data);
            }
        } catch (error) {
            console.error('Failed to load vehicles:', error);
        } finally {
            setLoading(false);
        }
    };

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

    const filteredVehicles = vehicles.filter(item => {
        const matchesSearch = item.model.toLowerCase().includes(searchTerm.toLowerCase()) ||
                             item.plate_number.includes(searchTerm) ||
                             (item.driver && item.driver.toLowerCase().includes(searchTerm.toLowerCase()));
        const matchesStatus = filterStatus === 'all' || item.status === filterStatus;
        const matchesOwnership = filterOwnership === 'all' || item.ownership_type === filterOwnership;
        return matchesSearch && matchesStatus && matchesOwnership;
    });

    const totalVehicles = vehicles.length;
    const activeVehicles = vehicles.filter(v => v.status === 'active').length;
    const corporateVehicles = vehicles.filter(v => v.ownership_type === 'corporate');
    const totalPurchaseValue = corporateVehicles.reduce((sum, v) => sum + (v.purchase_price || 0), 0);
    const rentLeaseVehicles = vehicles.filter(v => v.ownership_type === 'rent' || v.ownership_type === 'lease');
    const totalMonthlyRent = rentLeaseVehicles.reduce((sum, v) => sum + (v.monthly_rent || 0) + (v.monthly_rent_tax || 0), 0);

    const handleAdd = () => { setModalMode('add'); setFormData(initialFormState); setShowModal(true); };
    const handleEdit = (item) => {
        setModalMode('edit');
        setEditingItem(item);
        setFormData({
            plate_number: item.plate_number || '',
            model: item.model || '',
            vehicle_type: item.vehicle_type || '승용차',
            ownership_type: item.ownership_type || 'corporate',
            year: item.year || new Date().getFullYear(),
            driver: item.driver || '',
            status: item.status || 'active',
            mileage: item.mileage || '',
            memo: item.memo || '',
            purchase_date: item.purchase_date ? item.purchase_date.split('T')[0] : '',
            purchase_price: item.purchase_price || '',
            contract_date: item.contract_date ? item.contract_date.split('T')[0] : '',
            rent_company: item.rent_company || '',
            rent_company_tel: item.rent_company_tel || '',
            rent_period: item.rent_period || '',
            agreed_mileage: item.agreed_mileage || '',
            vehicle_price: item.vehicle_price || '',
            residual_value: item.residual_value || '',
            deposit: item.deposit || '',
            monthly_rent: item.monthly_rent || '',
            monthly_rent_tax: item.monthly_rent_tax || '',
            insurance_company: item.insurance_company || '',
            insurance_company_tel: item.insurance_company_tel || ''
        });
        setShowModal(true);
    };

    const handleSave = async () => {
        if (!formData.plate_number || !formData.model) {
            alert('차량번호와 모델은 필수입니다.');
            return;
        }

        setSaving(true);
        try {
            const payload = {
                ...formData,
                mileage: parseInt(formData.mileage) || 0,
                purchase_price: parseInt(formData.purchase_price) || 0,
                vehicle_price: parseInt(formData.vehicle_price) || 0,
                residual_value: parseInt(formData.residual_value) || 0,
                deposit: parseInt(formData.deposit) || 0,
                monthly_rent: parseInt(formData.monthly_rent) || 0,
                monthly_rent_tax: parseInt(formData.monthly_rent_tax) || 0,
            };

            const url = modalMode === 'add'
                ? '/finance/corporate-vehicles'
                : `/finance/corporate-vehicles/${editingItem.id}`;
            const method = modalMode === 'add' ? 'POST' : 'PUT';

            const response = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                },
                body: JSON.stringify(payload),
            });

            const result = await response.json();
            if (result.success) {
                await loadVehicles();
                setShowModal(false);
                setEditingItem(null);
            } else {
                alert(result.message || '저장에 실패했습니다.');
            }
        } catch (error) {
            console.error('Save error:', error);
            alert('저장 중 오류가 발생했습니다.');
        } finally {
            setSaving(false);
        }
    };

    const handleDelete = async (id) => {
        if (!confirm('정말 삭제하시겠습니까?')) return;

        try {
            const response = await fetch(`/finance/corporate-vehicles/${id}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                },
            });

            const result = await response.json();
            if (result.success) {
                await loadVehicles();
                setShowModal(false);
            } else {
                alert(result.message || '삭제에 실패했습니다.');
            }
        } catch (error) {
            console.error('Delete error:', error);
            alert('삭제 중 오류가 발생했습니다.');
        }
    };

    const handleDownload = () => {
        const rows = [['법인차량관리'], [], ['차량번호', '모델', '종류', '구분', '연식', '운전자', '취득가/월렌트료', '상태', '주행거리'],
            ...filteredVehicles.map(item => [
                item.plate_number, item.model, item.vehicle_type, getOwnershipLabel(item.ownership_type), item.year,
                item.driver,
                item.ownership_type === 'corporate' ? item.purchase_price : ((item.monthly_rent || 0) + (item.monthly_rent_tax || 0)),
                getStatusLabel(item.status), item.total_mileage || item.mileage
            ])];
        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 = '법인차량목록.csv'; link.click();
    };

    const getStatusColor = (status) => {
        const colors = { active: 'bg-emerald-100 text-emerald-700', maintenance: 'bg-amber-100 text-amber-700', disposed: 'bg-gray-100 text-gray-500' };
        return colors[status] || 'bg-gray-100 text-gray-700';
    };
    const getStatusLabel = (status) => {
        const labels = { active: '운행중', maintenance: '정비중', disposed: '처분' };
        return labels[status] || status;
    };

    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-blue-100 rounded-xl"><Car className="w-6 h-6 text-blue-600" /></div>
                        <div><h1 className="text-xl font-bold text-gray-900">법인차량관리</h1><p className="text-sm text-gray-500">Corporate Vehicles</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="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><Car className="w-5 h-5 text-gray-400" /></div>
                    <p className="text-2xl font-bold text-gray-900">{totalVehicles}대</p>
                    <p className="text-xs text-gray-400 mt-1">운행중 {activeVehicles}대</p>
                </div>
                <div className="bg-white rounded-xl border border-blue-200 p-6 bg-blue-50/30">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-blue-700">법인차량 취득가</span></div>
                    <p className="text-2xl font-bold text-blue-600">{formatCurrency(totalPurchaseValue)}원</p>
                    <p className="text-xs text-blue-400 mt-1">{corporateVehicles.length}대</p>
                </div>
                <div className="bg-white rounded-xl border border-purple-200 p-6 bg-purple-50/30">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-purple-700">월 렌트/리스료</span></div>
                    <p className="text-2xl font-bold text-purple-600">{formatCurrency(totalMonthlyRent)}원</p>
                    <p className="text-xs text-purple-400 mt-1">{rentLeaseVehicles.length}대</p>
                </div>
                <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><Gauge className="w-5 h-5 text-gray-400" /></div>
                    <p className="text-2xl font-bold text-gray-900">{formatCurrency(vehicles.reduce((sum, v) => sum + (v.total_mileage || v.mileage || 0), 0))}km</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-blue-500" />
                    </div>
                    <div className="flex gap-2">
                        {ownershipTypes.map(t => (
                            <button key={t.value} onClick={() => setFilterOwnership(filterOwnership === t.value ? 'all' : t.value)} className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${filterOwnership === t.value ? getOwnershipColor(t.value) : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>
                                {t.label}
                            </button>
                        ))}
                    </div>
                    <div className="flex gap-2">
                        {['all', 'active', 'maintenance'].map(status => (
                            <button key={status} onClick={() => setFilterStatus(status)} className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${filterStatus === status ? (status === 'active' ? 'bg-emerald-600 text-white' : status === 'maintenance' ? 'bg-amber-500 text-white' : 'bg-blue-600 text-white') : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>
                                {status === 'all' ? '전체' : getStatusLabel(status)}
                            </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-2">차량번호</div>
                    <div className="col-span-2">구분</div>
                    <div className="col-span-2">운전자</div>
                    <div className="col-span-2 text-right">취득가/월렌트료</div>
                    <div className="col-span-1 text-center">상태</div>
                </div>

                {/* 차량 목록 */}
                {loading ? (
                    <div className="text-center py-12 text-gray-400">
                        <div className="animate-spin w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full mx-auto mb-4"></div>
                        <p>차량 목록을 불러오는 중...</p>
                    </div>
                ) : filteredVehicles.length === 0 ? (
                    <div className="text-center py-12 text-gray-400">
                        <Car className="w-12 h-12 mx-auto mb-4 opacity-50" />
                        <p>등록된 차량이 없습니다.</p>
                        <button onClick={handleAdd} className="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm">차량 등록하기</button>
                    </div>
                ) : (
                    filteredVehicles.map(item => (
                        <div key={item.id} onClick={() => handleEdit(item)} className={`grid grid-cols-12 gap-4 px-4 py-3 border-b border-gray-100 cursor-pointer transition-colors hover:bg-blue-50 ${item.status !== 'active' ? 'opacity-60 bg-gray-50' : ''}`}>
                            {/* 차량 (모델 + 종류/연식) */}
                            <div className="col-span-3 flex items-center gap-2">
                                <div className={`p-1.5 rounded-lg ${item.status === 'active' ? 'bg-blue-100' : 'bg-gray-100'}`}>
                                    <Car className={`w-4 h-4 ${item.status === 'active' ? 'text-blue-600' : 'text-gray-400'}`} />
                                </div>
                                <div className="min-w-0">
                                    <p className="font-medium text-gray-900 truncate">{item.model}</p>
                                    <p className="text-xs text-gray-500">{item.vehicle_type} · {item.year}년</p>
                                </div>
                            </div>

                            {/* 차량번호 */}
                            <div className="col-span-2 flex items-center">
                                <p className="font-mono text-sm text-gray-700">{item.plate_number}</p>
                            </div>

                            {/* 구분 */}
                            <div className="col-span-2 flex items-center">
                                <span className={`px-2 py-0.5 rounded text-xs font-medium ${getOwnershipColor(item.ownership_type)}`}>
                                    {getOwnershipLabel(item.ownership_type)}
                                </span>
                            </div>

                            {/* 운전자 */}
                            <div className="col-span-2 flex items-center">
                                <p className="text-sm text-gray-900">{item.driver || '-'}</p>
                            </div>

                            {/* 취득가/월렌트료 */}
                            <div className="col-span-2 flex items-center justify-end">
                                {item.ownership_type === 'corporate' ? (
                                    <p className="text-sm font-medium text-gray-900">{formatCurrency(item.purchase_price)}원</p>
                                ) : (
                                    <p className="text-sm font-medium text-purple-600">{formatCurrency((item.monthly_rent || 0) + (item.monthly_rent_tax || 0))}원/월</p>
                                )}
                            </div>

                            {/* 상태 */}
                            <div className="col-span-1 flex items-center justify-center">
                                <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${getStatusColor(item.status)}`}>
                                    {getStatusLabel(item.status)}
                                </span>
                            </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)} 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><input type="text" value={formData.plate_number} onChange={(e) => setFormData(prev => ({ ...prev, plate_number: e.target.value }))} placeholder="12가 3456" 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><select value={formData.vehicle_type} onChange={(e) => setFormData(prev => ({ ...prev, vehicle_type: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">{types.map(t => <option key={t} value={t}>{t}</option>)}</select></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">구분 *</label><select value={formData.ownership_type} onChange={(e) => setFormData(prev => ({ ...prev, ownership_type: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">{ownershipTypes.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}</select></div>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">모델 *</label><input type="text" value={formData.model} onChange={(e) => setFormData(prev => ({ ...prev, model: 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="number" value={formData.year} onChange={(e) => setFormData(prev => ({ ...prev, year: parseInt(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">{formData.ownership_type === 'corporate' ? '취득일' : '계약일자'}</label><input type="date" value={formData.ownership_type === 'corporate' ? formData.purchase_date : formData.contract_date} onChange={(e) => setFormData(prev => ({ ...prev, [formData.ownership_type === 'corporate' ? 'purchase_date' : 'contract_date']: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            </div>

                            {/* 공통 필드 */}
                            <div className="border-t border-gray-200 pt-4 mt-2">
                                <div className="grid grid-cols-2 gap-4 mb-4">
                                    <div><label className="block text-sm font-medium text-gray-700 mb-1">{formData.ownership_type === 'rent' ? '렌트회사명' : formData.ownership_type === 'lease' ? '리스회사명' : '구매처'}</label><input type="text" value={formData.rent_company} onChange={(e) => setFormData(prev => ({ ...prev, rent_company: e.target.value }))} placeholder="회사명" 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">{formData.ownership_type === 'rent' ? '렌트기간' : formData.ownership_type === 'lease' ? '리스기간' : '계약기간'}</label><input type="text" value={formData.rent_period} onChange={(e) => setFormData(prev => ({ ...prev, rent_period: e.target.value }))} placeholder="예: 36개월" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div><label className="block text-sm font-medium text-gray-700 mb-1">{formData.ownership_type === 'corporate' ? '취득가' : formData.ownership_type === 'rent' ? '월 렌트료' : '월 리스료'} (공급가)</label><input type="text" value={formatInputCurrency(formData.ownership_type === 'corporate' ? formData.purchase_price : formData.monthly_rent)} onChange={(e) => setFormData(prev => ({ ...prev, [formData.ownership_type === 'corporate' ? 'purchase_price' : 'monthly_rent']: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
                                    <div><label className="block text-sm font-medium text-gray-700 mb-1">세액</label><input type="text" value={formatInputCurrency(formData.monthly_rent_tax)} onChange={(e) => setFormData(prev => ({ ...prev, monthly_rent_tax: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
                                </div>

                                {/* 상세 필드 */}
                                <div className="mt-4 pt-4 border-t border-gray-100 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><input type="text" value={formData.rent_company_tel} onChange={(e) => setFormData(prev => ({ ...prev, rent_company_tel: e.target.value }))} placeholder="연락처" 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={formData.agreed_mileage} onChange={(e) => setFormData(prev => ({ ...prev, agreed_mileage: e.target.value }))} placeholder="km" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></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.vehicle_price)} onChange={(e) => setFormData(prev => ({ ...prev, vehicle_price: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
                                        <div><label className="block text-sm font-medium text-gray-700 mb-1">추정잔존가액</label><input type="text" value={formatInputCurrency(formData.residual_value)} onChange={(e) => setFormData(prev => ({ ...prev, residual_value: parseInputCurrency(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.deposit)} onChange={(e) => setFormData(prev => ({ ...prev, deposit: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
                                        <div><label className="block text-sm font-medium text-gray-700 mb-1">최초 주행거리(km)</label><input type="text" value={formatInputCurrency(formData.mileage)} onChange={(e) => setFormData(prev => ({ ...prev, mileage: parseInputCurrency(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={formData.insurance_company} onChange={(e) => setFormData(prev => ({ ...prev, insurance_company: e.target.value }))} placeholder="보험사명" 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={formData.insurance_company_tel} onChange={(e) => setFormData(prev => ({ ...prev, insurance_company_tel: e.target.value }))} placeholder="연락처" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                                    </div>
                                </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.driver} onChange={(e) => setFormData(prev => ({ ...prev, driver: e.target.value }))} placeholder="운전자명" 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><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="active">운행중</option><option value="maintenance">정비중</option><option value="disposed">처분</option></select></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(editingItem.id)} className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg" disabled={saving}>삭제</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" disabled={saving}>취소</button>
                            <button onClick={handleSave} className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg flex items-center justify-center gap-2" disabled={saving}>
                                {saving && <Loader className="w-4 h-4 animate-spin" />}
                                {modalMode === 'add' ? '등록' : '저장'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

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