@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="partners-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 Building2 = createIcon('building-2');
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 Phone = createIcon('phone');
const Mail = createIcon('mail');
const ScanLine = createIcon('scan-line');
const Upload = createIcon('upload');
const FileText = createIcon('file-text');
const Loader = createIcon('loader');

function PartnersManagement() {
    const [partners, setPartners] = useState([]);
    const [stats, setStats] = useState({ total: 0, sales: 0, purchase: 0, active: 0 });
    const [loading, setLoading] = useState(true);

    const [searchTerm, setSearchTerm] = useState('');
    const [filterTradeType, setFilterTradeType] = useState('all');
    const [filterType, setFilterType] = useState('all');
    const [filterCategory, setFilterCategory] = useState('all');

    const [showModal, setShowModal] = useState(false);
    const [modalMode, setModalMode] = useState('add');
    const [editingItem, setEditingItem] = useState(null);
    const [saving, setSaving] = useState(false);
    const [ocrLoading, setOcrLoading] = useState(false);
    const fileInputRef = useRef(null);

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

    const initialFormState = {
        name: '',
        tradeType: 'sales',
        type: '',
        category: '',
        bizNo: '',
        ceo: '',
        bankAccount: '',
        contact: '',
        email: '',
        address: '',
        manager: '',
        managerPhone: '',
        status: 'active',
        memo: ''
    };
    const [formData, setFormData] = useState(initialFormState);

    const fetchPartners = async () => {
        setLoading(true);
        try {
            const res = await fetch('/finance/partners/list');
            const data = await res.json();
            if (data.success) {
                setPartners(data.data);
                setStats(data.stats);
            }
        } catch (err) {
            console.error('거래처 조회 실패:', err);
        } finally {
            setLoading(false);
        }
    };

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

    const filteredPartners = partners.filter(item => {
        const matchesSearch = item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                             (item.ceo || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                             (item.manager || '').toLowerCase().includes(searchTerm.toLowerCase());
        const matchesTradeType = filterTradeType === 'all' || item.tradeType === filterTradeType;
        const matchesType = filterType === 'all' || item.type === filterType;
        const matchesCategory = filterCategory === 'all' || item.category === filterCategory;
        return matchesSearch && matchesTradeType && matchesType && matchesCategory;
    });

    const handleAdd = () => { setModalMode('add'); setFormData(initialFormState); setShowModal(true); };
    const handleEdit = (item) => {
        setModalMode('edit');
        setEditingItem(item);
        const safeItem = {};
        Object.keys(initialFormState).forEach(key => { safeItem[key] = item[key] ?? ''; });
        setFormData(safeItem);
        setShowModal(true);
    };
    const handleSave = async () => {
        if (!formData.name) { alert('거래처명을 입력해주세요.'); return; }
        setSaving(true);
        try {
            const url = modalMode === 'add' ? '/finance/partners/store' : `/finance/partners/${editingItem.id}`;
            const res = await fetch(url, {
                method: modalMode === 'add' ? 'POST' : 'PUT',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
                body: JSON.stringify(formData),
            });
            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);
            fetchPartners();
        } catch (err) {
            console.error('저장 실패:', err);
            alert('저장에 실패했습니다.');
        } finally {
            setSaving(false);
        }
    };
    const handleDelete = async (id) => {
        if (!confirm('정말 삭제하시겠습니까?')) return;
        try {
            const res = await fetch(`/finance/partners/${id}`, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': csrfToken },
            });
            if (res.ok) {
                setShowModal(false);
                fetchPartners();
            }
        } catch (err) {
            console.error('삭제 실패:', err);
            alert('삭제에 실패했습니다.');
        }
    };

    const handleOcrUpload = (file) => {
        if (!file || !file.type.startsWith('image/')) {
            alert('이미지 파일만 업로드 가능합니다.');
            return;
        }
        if (file.size > 10 * 1024 * 1024) {
            alert('파일 크기는 10MB 이하만 가능합니다.');
            return;
        }
        setOcrLoading(true);
        const reader = new FileReader();
        reader.onload = async (e) => {
            try {
                const res = await fetch('/finance/partners/ocr', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
                    body: JSON.stringify({ image: e.target.result }),
                });
                const data = await res.json();
                if (data.ok && data.data) {
                    const d = data.data;
                    setFormData(prev => ({
                        ...prev,
                        name: d.name || prev.name,
                        bizNo: d.bizNo || prev.bizNo,
                        ceo: d.ceo || prev.ceo,
                        type: d.type || prev.type,
                        category: d.category || prev.category,
                        contact: d.contact || prev.contact,
                        email: d.email || prev.email,
                        address: d.address || prev.address,
                        manager: d.manager || prev.manager,
                    }));
                } else {
                    alert(data.message || 'OCR 처리에 실패했습니다.');
                }
            } catch (err) {
                console.error('OCR 실패:', err);
                alert('OCR 처리에 실패했습니다.');
            } finally {
                setOcrLoading(false);
                if (fileInputRef.current) fileInputRef.current.value = '';
            }
        };
        reader.readAsDataURL(file);
    };

    const handleDownload = () => {
        const rows = [['거래처 관리'], [], ['고유번호', '거래구분', '거래처명', '대표자', '업태', '종목', '사업자번호', '주소', '연락처', '이메일', '담당자', '상태'],
            ...filteredPartners.map(item => [item.id, item.tradeType === 'purchase' ? '매입' : '매출', item.name, item.ceo || '', item.type || '', item.category || '', item.bizNo, item.address || '', item.contact, item.email, item.manager, item.status === 'active' ? '활성' : '비활성'])];
        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();
    };


    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-emerald-100 rounded-xl"><Building2 className="w-6 h-6 text-emerald-600" /></div>
                        <div><h1 className="text-xl font-bold text-gray-900">거래처 관리</h1><p className="text-sm text-gray-500">Partners / Vendors</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><Building2 className="w-5 h-5 text-gray-400" /></div>
                    <p className="text-2xl font-bold text-gray-900">{stats.total}개</p>
                </div>
                <div className="bg-white rounded-xl border border-blue-200 p-6">
                    <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">{stats.sales}개</p>
                </div>
                <div className="bg-white rounded-xl border border-amber-200 p-6">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-amber-700">매입</span></div>
                    <p className="text-2xl font-bold text-amber-600">{stats.purchase}개</p>
                </div>
                <div className="bg-white rounded-xl border border-emerald-200 p-6">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-emerald-700">활성</span></div>
                    <p className="text-2xl font-bold text-emerald-600">{stats.active}개</p>
                </div>
            </div>

            <div className="bg-white rounded-xl border border-gray-200 p-4 mb-6">
                <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
                    <div className="md:col-span-2 relative">
                        <Search className="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
                        <input type="text" placeholder="거래처명, 대표자, 담당자 검색..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500" />
                    </div>
                    <div className="flex gap-1">
                        {[{v:'all',l:'전체'},{v:'sales',l:'매출'},{v:'purchase',l:'매입'}].map(o => (
                            <button key={o.v} onClick={() => setFilterTradeType(o.v)} className={`flex-1 px-3 py-2 rounded-lg text-sm font-medium ${filterTradeType === o.v ? (o.v === 'sales' ? 'bg-blue-600 text-white' : o.v === 'purchase' ? 'bg-orange-600 text-white' : 'bg-gray-800 text-white') : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>{o.l}</button>
                        ))}
                    </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>{[...new Set(partners.map(p => p.type).filter(Boolean))].map(t => <option key={t} value={t}>{t}</option>)}</select>
                    <select value={filterCategory} onChange={(e) => setFilterCategory(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg"><option value="all">전체 종목</option>{[...new Set(partners.map(p => p.category).filter(Boolean))].map(c => <option key={c} value={c}>{c}</option>)}</select>
                </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-4 py-3 text-center text-xs font-semibold text-gray-600 w-20">고유번호</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-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-center text-xs font-semibold text-gray-600">상태</th>
                            <th className="px-6 py-3 text-center text-xs font-semibold text-gray-600">관리</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                        {loading ? (
                            <tr><td colSpan="8" 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>
                        ) : filteredPartners.length === 0 ? (
                            <tr><td colSpan="8" className="px-6 py-12 text-center text-gray-400">데이터가 없습니다.</td></tr>
                        ) : filteredPartners.map(item => (
                            <tr key={item.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => handleEdit(item)}>
                                <td className="px-4 py-4 text-center"><span className="text-sm font-mono font-medium text-gray-700">{item.id}</span></td>
                                <td className="px-6 py-4"><div className="flex items-center gap-2"><span className={`px-1.5 py-0.5 rounded text-[10px] font-bold ${item.tradeType === 'purchase' ? 'bg-amber-100 text-amber-700' : 'bg-blue-100 text-blue-700'}`}>{item.tradeType === 'purchase' ? '매입' : '매출'}</span><p className="text-sm font-medium text-gray-900">{item.name}</p></div>{item.bizNo && <p className="text-xs text-gray-400 ml-7">{item.bizNo}</p>}</td>
                                <td className="px-6 py-4"><span className="text-sm text-gray-900">{item.ceo || '-'}</span></td>
                                <td className="px-6 py-4">{item.type && <span className="px-2 py-1 bg-blue-50 text-blue-700 rounded text-xs font-medium">{item.type}</span>}{item.category && <p className="text-xs text-gray-400 mt-1">{item.category}</p>}</td>
                                <td className="px-6 py-4">{item.contact && <p className="text-sm text-gray-600">{item.contact}</p>}{item.email && <p className="text-xs text-gray-400">{item.email}</p>}</td>
                                <td className="px-6 py-4"><p className="text-sm text-gray-900">{item.manager}</p>{item.managerPhone && <p className="text-xs text-gray-400">{item.managerPhone}</p>}</td>
                                <td className="px-6 py-4 text-center"><span className={`px-2 py-1 rounded-full text-xs font-medium ${item.status === 'active' ? 'bg-emerald-100 text-emerald-700' : 'bg-gray-100 text-gray-500'}`}>{item.status === 'active' ? '활성' : '비활성'}</span></td>
                                <td className="px-6 py-4 text-center" onClick={(e) => e.stopPropagation()}>
                                    <button onClick={() => handleEdit(item)} className="p-1 text-gray-400 hover:text-blue-500"><Edit className="w-4 h-4" /></button>
                                    <button onClick={() => handleDelete(item.id)} className="p-1 text-gray-400 hover:text-rose-500"><Trash2 className="w-4 h-4" /></button>
                                </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>
                        {modalMode === 'add' && (
                            <div
                                className={`mb-4 border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-colors ${ocrLoading ? 'border-blue-400 bg-blue-50' : 'border-gray-300 hover:border-blue-400 hover:bg-blue-50'}`}
                                onClick={() => !ocrLoading && fileInputRef.current?.click()}
                                onDragOver={(e) => { e.preventDefault(); e.stopPropagation(); }}
                                onDrop={(e) => { e.preventDefault(); e.stopPropagation(); if (!ocrLoading && e.dataTransfer.files[0]) handleOcrUpload(e.dataTransfer.files[0]); }}
                            >
                                <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={(e) => e.target.files[0] && handleOcrUpload(e.target.files[0])} />
                                {ocrLoading ? (
                                    <div className="flex flex-col items-center gap-2">
                                        <svg className="animate-spin h-8 w-8 text-blue-500" 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>
                                        <p className="text-sm text-blue-600 font-medium">AI가 사업자등록증을 분석 중입니다...</p>
                                    </div>
                                ) : (
                                    <div className="flex flex-col items-center gap-2">
                                        <FileText className="w-8 h-8 text-gray-400" />
                                        <p className="text-sm text-gray-600 font-medium">사업자등록증 이미지를 드래그하거나 클릭하여 업로드하세요</p>
                                        <p className="text-xs text-gray-400">자동으로 거래처 정보가 입력됩니다</p>
                                    </div>
                                )}
                            </div>
                        )}
                        <div className="space-y-4">
                            {modalMode === 'edit' && editingItem && (
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">고유번호</label><input type="text" value={editingItem.id} readOnly className="w-full px-3 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-500 font-mono cursor-not-allowed" /></div>
                            )}
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">거래 구분 *</label>
                                <div className="flex gap-4">
                                    <label className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg border-2 cursor-pointer transition-all ${formData.tradeType === 'sales' ? 'border-blue-500 bg-blue-50 text-blue-700' : 'border-gray-200 bg-white text-gray-500 hover:border-gray-300'}`}>
                                        <input type="radio" name="tradeType" value="sales" checked={formData.tradeType === 'sales'} onChange={(e) => setFormData(prev => ({ ...prev, tradeType: e.target.value }))} className="hidden" />
                                        <span className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${formData.tradeType === 'sales' ? 'border-blue-500' : 'border-gray-300'}`}>{formData.tradeType === 'sales' && <span className="w-2 h-2 rounded-full bg-blue-500"></span>}</span>
                                        <span className="text-sm font-medium">매출</span>
                                    </label>
                                    <label className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg border-2 cursor-pointer transition-all ${formData.tradeType === 'purchase' ? 'border-amber-500 bg-amber-50 text-amber-700' : 'border-gray-200 bg-white text-gray-500 hover:border-gray-300'}`}>
                                        <input type="radio" name="tradeType" value="purchase" checked={formData.tradeType === 'purchase'} onChange={(e) => setFormData(prev => ({ ...prev, tradeType: e.target.value }))} className="hidden" />
                                        <span className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${formData.tradeType === 'purchase' ? 'border-amber-500' : 'border-gray-300'}`}>{formData.tradeType === 'purchase' && <span className="w-2 h-2 rounded-full bg-amber-500"></span>}</span>
                                        <span className="text-sm font-medium">매입</span>
                                    </label>
                                </div>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">거래처명 *</label><input type="text" value={formData.name} onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))} placeholder="거래처명" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            <div className="grid grid-cols-2 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">사업자번호</label><input type="text" value={formData.bizNo} onChange={(e) => setFormData(prev => ({ ...prev, bizNo: e.target.value }))} placeholder="123-45-67890" 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.ceo} onChange={(e) => setFormData(prev => ({ ...prev, ceo: e.target.value }))} placeholder="대표자명" 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={formData.type} onChange={(e) => setFormData(prev => ({ ...prev, type: 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.category} onChange={(e) => setFormData(prev => ({ ...prev, category: e.target.value }))} placeholder="소프트웨어 개발, 블라인드 등" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">주소</label><input type="text" value={formData.address} onChange={(e) => setFormData(prev => ({ ...prev, address: e.target.value }))} placeholder="사업장 소재지" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            <div className="grid grid-cols-2 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">연락처</label><input type="text" value={formData.contact} onChange={(e) => setFormData(prev => ({ ...prev, contact: e.target.value }))} placeholder="02-1234-5678" 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="email" value={formData.email} onChange={(e) => setFormData(prev => ({ ...prev, email: e.target.value }))} placeholder="email@company.com" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">계좌번호</label><input type="text" value={formData.bankAccount} onChange={(e) => setFormData(prev => ({ ...prev, bankAccount: e.target.value }))} placeholder="000-000000-00000" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            <div className="grid grid-cols-2 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">담당자</label><input type="text" value={formData.manager} onChange={(e) => setFormData(prev => ({ ...prev, manager: 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.managerPhone} onChange={(e) => setFormData(prev => ({ ...prev, managerPhone: e.target.value }))} placeholder="010-1234-5678" 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><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="inactive">비활성</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 flex items-center gap-2"><span>🗑️</span> 삭제</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('partners-root');
if (rootElement) { ReactDOM.createRoot(rootElement).render(<PartnersManagement />); }
</script>
@endverbatim
@endpush
