const { useState, useEffect, useMemo, Fragment } = React;

if (!firebase.apps.length) {
    firebase.initializeApp(FIREBASE_CONFIG);
}
const db = firebase.firestore();
const auth = firebase.auth();

const GlobalDialog = ({ dialog, setDialog }) => {
    if (!dialog) return null;
    const isConfirm = !!dialog.onConfirm;
    return (
        <div className="fixed inset-0 bg-slate-900/50 backdrop-blur-sm flex items-center justify-center z-[200] px-4">
            <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 text-center transform transition-all scale-100">
                {isConfirm ? (
                    <i className="fa-solid fa-triangle-exclamation text-4xl text-amber-500 mb-4"></i>
                ) : (
                    <i className="fa-solid fa-circle-exclamation text-4xl text-indigo-500 mb-4"></i>
                )}
                <h3 className="text-lg font-bold text-gray-800 mb-2">{isConfirm ? '確認操作' : '系統提示'}</h3>
                <p className="text-sm text-gray-600 mb-6 whitespace-pre-line">{dialog.message}</p>
                <div className="flex justify-center gap-3">
                    {isConfirm && (
                        <button onClick={() => setDialog(null)} className="flex-1 py-2.5 font-bold rounded-xl text-gray-600 bg-gray-100 hover:bg-gray-200 transition-colors">取消</button>
                    )}
                    <button onClick={() => { if(isConfirm) dialog.onConfirm(); setDialog(null); }} className={`flex-1 py-2.5 font-bold rounded-xl text-white transition-colors ${isConfirm ? 'bg-amber-500 hover:bg-amber-600' : 'bg-indigo-600 hover:bg-indigo-700'}`}>確定</button>
                </div>
            </div>
        </div>
    );
};

const CreateOrderForm = ({ orders, setActiveTab, showAlert }) => {
    const [customer, setCustomer] = useState({ name: '', gameId: '', paymentMethod: '銀行轉帳', notes: '' });
    const [subOrders, setSubOrders] = useState([{ 
        id: Date.now(), selectedProductIndex: 0, customName: '', price: PRODUCT_CATALOG[0].price, booster1: '無指定', booster2: '無指定', scheduledTime: '', orderNotes: ''
    }]);

    const handleAddSubOrder = () => setSubOrders([...subOrders, { id: Date.now(), selectedProductIndex: 0, customName: '', price: PRODUCT_CATALOG[0].price, booster1: '無指定', booster2: '無指定', scheduledTime: '', orderNotes: '' }]);

    const handleSubOrderChange = (index, field, value) => {
        const updated = [...subOrders];
        if (field === 'selectedProductIndex') {
            const product = PRODUCT_CATALOG[value];
            updated[index].selectedProductIndex = value;
            updated[index].price = product.price;
            if (!product.isCustom) updated[index].customName = '';
        } else {
            updated[index][field] = value;
        }
        setSubOrders(updated);
    };

    const removeSubOrder = (index) => setSubOrders(subOrders.filter((_, i) => i !== index));

    const totalAmount = useMemo(() => subOrders.reduce((sum, item) => sum + Number(item.price), 0), [subOrders]);

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!customer.name || !customer.gameId) {
            showAlert("請填寫客戶名稱與遊戲ID"); return;
        }
        try {
            await db.runTransaction(async (transaction) => {
                const counterRef = db.collection('system').doc('counter');
                const counterDoc = await transaction.get(counterRef);
                const d = new Date();
                const monthNames = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
                const currentMonthName = monthNames[d.getMonth()];
                
                let newCount = 1;
                if (counterDoc.exists) {
                    const data = counterDoc.data();
                    if (data.month === currentMonthName) newCount = (data.count || 0) + 1;
                }
                
                const nextNumStr = String(newCount).padStart(4, '0');
                const mainOrderId = `${currentMonthName}_${nextNumStr}`;
                const orderRef = db.collection('orders').doc(mainOrderId);
                
                const existingOrder = await transaction.get(orderRef);
                if (existingOrder.exists) throw new Error("單號衝突，請至系統資料管理校正計數器。");

                transaction.set(counterRef, { month: currentMonthName, count: newCount }, { merge: true });

                const finalSubOrders = subOrders.map((sub, i) => {
                    const product = PRODUCT_CATALOG[sub.selectedProductIndex];
                    return {
                        id: `${mainOrderId}_${String(i+1).padStart(2, '0')}`,
                        productName: product.isCustom ? sub.customName || '自訂方案' : product.name,
                        price: Number(sub.price),
                        booster1: sub.booster1,
                        booster1Status: sub.booster1 === '無指定' ? 'confirmed' : 'pending',
                        booster2: sub.booster2,
                        booster2Status: sub.booster2 === '無指定' ? 'confirmed' : 'pending',
                        scheduledTime: sub.scheduledTime,
                        orderNotes: sub.orderNotes || '',
                        status: '待收款'
                    };
                });

                const newOrder = {
                    id: mainOrderId, customerUid: auth.currentUser.uid, customerName: customer.name, contactId: '',
                    gameId: customer.gameId, paymentMethod: customer.paymentMethod, totalAmount: totalAmount,
                    paymentStatus: '待付款', orderNotes: customer.notes, createdAt: new Date().toISOString(),
                    createdBy: 'cs', subOrders: finalSubOrders
                };
                transaction.set(orderRef, newOrder);
            });
            setActiveTab('finance');
        } catch (error) { showAlert("建立訂單失敗：" + error.message); }
    };

    return (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 max-w-4xl mx-auto">
            <div className="mb-8 border-b pb-4">
                <h2 className="text-xl font-bold text-gray-800 flex items-center gap-2"><i className="fa-solid fa-plus text-indigo-600"></i> 新增主單</h2>
                <p className="text-gray-500 text-sm mt-1">建立客戶基本資料與所需的所有方案。確認收款後，系統會自動拆分成執行派單。</p>
            </div>
            <form onSubmit={handleSubmit} className="space-y-8">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 bg-gray-50 p-6 rounded-lg">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">客戶暱稱 *</label>
                        <input required type="text" value={customer.name} onChange={e => setCustomer({...customer, name: e.target.value})} className="w-full p-2 border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500" placeholder="例: 王先生"/>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">遊戲內 ID *</label>
                        <input required type="text" value={customer.gameId} onChange={e => setCustomer({...customer, gameId: e.target.value})} className="w-full p-2 border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500" placeholder="精確的遊戲ID"/>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">付款方式</label>
                        <select value={customer.paymentMethod} onChange={e => setCustomer({...customer, paymentMethod: e.target.value})} className="w-full p-2 border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500">
                            <option>銀行轉帳</option><option>8591物寶交易網</option><option>line pay</option><option>全家三連單</option>
                        </select>
                    </div>
                </div>

                <div>
                    <div className="flex justify-between items-center mb-4">
                        <h3 className="text-lg font-bold text-gray-800">選購方案 (子單)</h3>
                        <button type="button" onClick={handleAddSubOrder} className="text-sm bg-indigo-50 text-indigo-700 px-3 py-1.5 rounded hover:bg-indigo-100 flex items-center font-medium gap-1"><i className="fa-solid fa-plus"></i> 加入其他方案</button>
                    </div>
                    <div className="space-y-4">
                        {subOrders.map((sub, index) => {
                            const product = PRODUCT_CATALOG[sub.selectedProductIndex];
                            return (
                                <div key={sub.id} className="border border-gray-200 rounded-lg p-4 bg-white relative hover:border-indigo-300 transition-colors">
                                    {subOrders.length > 1 && <button type="button" onClick={() => removeSubOrder(index)} className="absolute top-2 right-2 text-red-400 hover:text-red-600"><i className="fa-solid fa-xmark"></i></button>}
                                    <div className="grid grid-cols-1 md:grid-cols-12 gap-4">
                                        <div className="col-span-1 md:col-span-4">
                                            <label className="block text-xs text-gray-500 mb-1">方案種類</label>
                                            <select value={sub.selectedProductIndex} onChange={(e) => handleSubOrderChange(index, 'selectedProductIndex', e.target.value)} className="w-full p-2 text-sm border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500">
                                                {PRODUCT_CATALOG.map((p, i) => <option key={i} value={i}>[{p.category}] {p.name}</option>)}
                                            </select>
                                        </div>
                                        {product.isCustom && (
                                            <div className="col-span-1 md:col-span-3">
                                                <label className="block text-xs text-gray-500 mb-1">自訂方案名稱</label>
                                                <input type="text" value={sub.customName} onChange={(e) => handleSubOrderChange(index, 'customName', e.target.value)} className="w-full p-2 text-sm border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500" placeholder="輸入陪玩時數或特定專案"/>
                                            </div>
                                        )}
                                        <div className="col-span-1 md:col-span-2">
                                            <label className="block text-xs text-gray-500 mb-1">金額 (NTD)</label>
                                            <input type="number" value={sub.price} onChange={(e) => handleSubOrderChange(index, 'price', e.target.value)} className="w-full p-2 text-sm border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500"/>
                                        </div>
                                        <div className="col-span-1 md:col-span-2 space-y-2">
                                            <div>
                                                <label className="block text-xs text-gray-500 mb-1">打手 1</label>
                                                <select value={sub.booster1} onChange={(e) => handleSubOrderChange(index, 'booster1', e.target.value)} className="w-full p-2 text-sm border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500">
                                                    {Object.entries(BOOSTER_GROUPS).map(([groupName, members]) => <optgroup key={groupName} label={groupName}>{members.map(b => <option key={b} value={b}>{b}</option>)}</optgroup>)}
                                                </select>
                                            </div>
                                            {(!product.name.includes('陪玩') && !product.name.includes('陪陪') && !product.name.includes('單人陪')) && (
                                                <div>
                                                    <label className="block text-xs text-gray-500 mb-1">打手 2</label>
                                                    <select value={sub.booster2} onChange={(e) => handleSubOrderChange(index, 'booster2', e.target.value)} className="w-full p-2 text-sm border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500">
                                                        {Object.entries(BOOSTER_GROUPS).map(([groupName, members]) => <optgroup key={groupName} label={groupName}>{members.map(b => <option key={b} value={b}>{b}</option>)}</optgroup>)}
                                                    </select>
                                                </div>
                                            )}
                                        </div>
                                        <div className="col-span-1 md:col-span-3">
                                            <label className="block text-xs text-gray-500 mb-1">預約執行時間</label>
                                            <input type="datetime-local" value={sub.scheduledTime} onChange={(e) => handleSubOrderChange(index, 'scheduledTime', e.target.value)} className="w-full p-2 text-sm border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500"/>
                                        </div>
                                        <div className="col-span-1 md:col-span-12 mt-2">
                                            <label className="block text-xs text-gray-500 mb-1">子單專屬備註 (選填)</label>
                                            <textarea value={sub.orderNotes} onChange={(e) => handleSubOrderChange(index, 'orderNotes', e.target.value)} className="w-full p-2 text-sm border border-gray-300 rounded focus:ring-indigo-500 focus:border-indigo-500" placeholder="針對此方案的特殊需求或注意事項..." rows="1"></textarea>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>

                <div className="border-t pt-6 mt-8 flex flex-col md:flex-row justify-between items-center">
                    <div className="text-xl font-bold text-gray-800 mb-4 md:mb-0">主單總金額: <span className="text-red-500 ml-2">${totalAmount.toLocaleString()} NTD</span></div>
                    <button type="submit" className="bg-indigo-600 text-white px-8 py-3 rounded-lg font-bold hover:bg-indigo-700 shadow-md transform hover:scale-105 transition-all">確認建單</button>
                </div>
            </form>
        </div>
    );
};

const FinanceMainOrders = ({ orders, currentTime, showAlert, showConfirm }) => {
    const [expandedRows, setExpandedRows] = useState({});
    const toggleRow = (orderId) => setExpandedRows(prev => ({ ...prev, [orderId]: !prev[orderId] }));

    const togglePaymentStatus = async (orderId, currentStatus) => {
        const newStatus = currentStatus === '待付款' ? '已收款' : '待付款';
        try { 
            const targetOrder = orders.find(o => o.id === orderId);
            if (!targetOrder) throw new Error("找不到訂單資料");
            
            const updatedSubs = targetOrder.subOrders.map(sub => {
                if (newStatus === '已收款' && sub.status === '待收款') return { ...sub, status: '進行中' };
                else if (newStatus === '待付款' && sub.status === '進行中') return { ...sub, status: '待收款' };
                return sub;
            });
            await db.collection('orders').doc(orderId).update({ paymentStatus: newStatus, subOrders: updatedSubs }); 
        } 
        catch (error) { showAlert("狀態更新失敗：" + error.message); }
    };

    const handleDeleteClick = (orderId) => {
        showConfirm(`確定要刪除這筆訂單嗎？\n主單號：${orderId}\n刪除後無法復原。`, async () => {
            try { await db.collection('orders').doc(orderId).delete(); showAlert('訂單已成功刪除'); } 
            catch (error) { showAlert("刪除失敗：" + error.message); }
        });
    };

    const activeOrders = useMemo(() => orders.filter(order => !isOrderFullyArchived(order, currentTime)), [orders, currentTime]);

    return (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div className="mb-6 flex justify-between items-center">
                <h2 className="text-xl font-bold text-gray-800 flex items-center gap-2"><i className="fa-solid fa-sack-dollar text-green-600"></i> 財務與主單管理</h2>
            </div>
            <div className="overflow-x-auto">
                <table className="min-w-full text-left border-collapse">
                    <thead>
                        <tr className="bg-gray-50 border-b border-gray-200 text-sm font-medium text-gray-500">
                            <th className="p-4 w-10"></th><th className="p-4">主單編號</th><th className="p-4">建立時間</th>
                            <th className="p-4">客戶資訊</th><th className="p-4">付款方式</th><th className="p-4">總金額</th>
                            <th className="p-4">金流狀態</th><th className="p-4 text-center">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {activeOrders.map(order => (
                            <Fragment key={order.id}>
                                <tr className="border-b border-gray-100 hover:bg-indigo-50/30">
                                    <td className="p-4 text-center">
                                        <button onClick={() => toggleRow(order.id)} className="text-gray-400 hover:text-indigo-600">
                                            {expandedRows[order.id] ? <i className="fa-solid fa-chevron-up"></i> : <i className="fa-solid fa-chevron-down"></i>}
                                        </button>
                                    </td>
                                    <td className="p-4 font-mono text-sm text-indigo-700 font-bold">{order.id}</td>
                                    <td className="p-4 text-sm text-gray-600">{new Date(order.createdAt).toLocaleString([], {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'})}</td>
                                    <td className="p-4"><div className="font-bold text-gray-800">{order.customerName}</div><div className="text-xs text-gray-500">ID: {order.gameId}</div></td>
                                    <td className="p-4 text-sm text-gray-600">{order.paymentMethod}</td>
                                    <td className="p-4 font-bold text-red-500">${order.totalAmount.toLocaleString()}</td>
                                    <td className="p-4"><span className={`px-3 py-1 rounded-full text-xs font-bold ${order.paymentStatus === '已收款' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'}`}>{order.paymentStatus}</span></td>
                                    <td className="p-4 text-center">
                                        <div className="flex justify-center gap-2">
                                            <button onClick={() => togglePaymentStatus(order.id, order.paymentStatus)} className={`text-xs px-3 py-1.5 rounded font-medium ${order.paymentStatus === '待付款' ? 'bg-indigo-600 text-white' : 'bg-gray-100 text-gray-600'}`}>
                                                {order.paymentStatus === '待付款' ? '確認收款' : '取消收款'}
                                            </button>
                                            {order.paymentStatus === '待付款' && (
                                                <button onClick={() => handleDeleteClick(order.id)} className="text-xs px-2.5 py-1.5 rounded bg-red-50 text-red-500 hover:bg-red-100"><i className="fa-solid fa-trash-can"></i></button>
                                            )}
                                        </div>
                                    </td>
                                </tr>
                                {expandedRows[order.id] && (
                                    <tr className="bg-slate-50 border-b border-gray-200">
                                        <td colSpan="8" className="p-4 px-12">
                                            <div className="bg-white p-4 rounded-lg border shadow-inner">
                                                <h4 className="text-sm font-bold text-slate-700 mb-3"><i className="fa-solid fa-list"></i> 子單明細</h4>
                                                <table className="min-w-full text-sm">
                                                    <tbody>
                                                        {order.subOrders.map(sub => (
                                                            <tr key={sub.id} className="border-b border-slate-50 last:border-0">
                                                                <td className="py-2 text-slate-500 font-mono text-xs">{sub.id}</td>
                                                                <td className="py-2 text-slate-700">{sub.productName}</td>
                                                                <td className="py-2 text-xs">1: {sub.booster1} {sub.booster1Status === 'pending' ? '(待確認)' : ''} {sub.booster1Status === 'rejected' ? '(已拒絕)' : ''} {sub.booster2 && sub.booster2!=='無指定' ? `| 2: ${sub.booster2}` : ''} {sub.booster2Status === 'pending' ? '(待確認)' : ''} {sub.booster2Status === 'rejected' ? '(已拒絕)' : ''}</td>
                                                                <td className="py-2 text-slate-600">{new Date(sub.scheduledTime).toLocaleString([], {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'})}</td>
                                                                <td className="py-2 font-bold text-indigo-600">{sub.status}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </td>
                                    </tr>
                                )}
                            </Fragment>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
};

const DispatchKanban = ({ orders, currentTime, showAlert }) => {
    const [searchQuery, setSearchQuery] = useState('');
    const [editingTask, setEditingTask] = useState(null);

    const vipOrderIds = useMemo(() => {
        const now = new Date();
        const thisMonthStr = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`;
        const spending = {};
        const vipOrders = new Set();
        const sortedOrders = [...orders].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));

        sortedOrders.forEach(o => {
            const isThisMonth = o.createdAt && o.createdAt.slice(0, 7) === thisMonthStr;
            if (!isThisMonth) return;
            let isVip = (spending[o.gameId] || 0) >= 5000;
            if (o.paymentStatus === '已收款') {
                spending[o.gameId] = (spending[o.gameId] || 0) + (Number(o.totalAmount) || 0);
                if (spending[o.gameId] >= 5000) isVip = true;
            }
            if (isVip) vipOrders.add(o.id);
        });
        return vipOrders;
    }, [orders]);

    const allSubs = useMemo(() => {
        const subs = [];
        const lowerSearch = searchQuery.toLowerCase();
        orders.forEach(order => {
            order.subOrders.forEach(sub => {
                const searchStr = `${order.id} ${order.customerName} ${order.gameId} ${sub.productName} ${sub.booster1} ${sub.booster2 || ''}`.toLowerCase();
                if (!lowerSearch || searchStr.includes(lowerSearch)) {
                    subs.push({ ...sub, mainOrderId: order.id, customerName: order.customerName, gameId: order.gameId, paymentMethod: order.paymentMethod, paymentStatus: order.paymentStatus, orderNotes: sub.orderNotes });
                }
            });
        });
        return subs;
    }, [orders, searchQuery]);

    const activeSubs = allSubs.filter(s => !isSubArchived(s, currentTime));
    const pending = activeSubs.filter(s => s.status === '待收款');
    const inProgress = activeSubs.filter(s => s.status === '進行中');
    const completed = activeSubs.filter(s => s.status === '已結單');

    const changeSubOrderStatus = async (subOrderId, mainOrderId, newStatus) => {
        const order = orders.find(o => o.id === mainOrderId);
        if(!order) return;
        const updatedSubs = order.subOrders.map(sub => {
            if (sub.id === subOrderId) return { ...sub, status: newStatus, completedAt: newStatus === '已結單' ? new Date().toISOString() : null };
            return sub;
        });
        try { await db.collection('orders').doc(mainOrderId).update({ subOrders: updatedSubs }); }
        catch(e) { showAlert("更新狀態失敗: " + e.message); }
    };

    const saveEditTask = async () => {
        if(!editingTask) return;
        const order = orders.find(o => o.id === editingTask.mainOrderId);
        const updatedSubs = order.subOrders.map(sub => {
            if (sub.id === editingTask.id) {
                return {
                    ...sub, scheduledTime: editingTask.scheduledTime, orderNotes: editingTask.orderNotes || '', 
                    booster1: editingTask.booster1,
                    booster1Status: sub.booster1 !== editingTask.booster1 ? (editingTask.booster1 === '無指定' ? 'confirmed' : 'pending') : (sub.booster1Status || 'confirmed'),
                    booster2: editingTask.booster2,
                    booster2Status: sub.booster2 !== editingTask.booster2 ? (editingTask.booster2 === '無指定' ? 'confirmed' : 'pending') : (sub.booster2Status || 'confirmed')
                };
            }
            return sub;
        });
        try { 
            await db.collection('orders').doc(order.id).update({ subOrders: updatedSubs, paymentMethod: editingTask.paymentMethod });
            setEditingTask(null);
        } catch(e) { showAlert("儲存失敗: " + e.message); }
    };

    const getBoosterTag = (boosterName, status, prefix) => {
        if (!boosterName || boosterName === '無指定') return <span className="px-2 py-0.5 rounded text-[10px] font-medium bg-orange-100 text-orange-700">{prefix}: 無指定</span>;
        if (status === 'confirmed') return <span className="px-2 py-0.5 rounded text-[10px] font-medium bg-blue-100 text-blue-700">{prefix}: {boosterName} (已確認)</span>;
        if (status === 'rejected') return <span className="px-2 py-0.5 rounded text-[10px] font-medium bg-red-100 text-red-700">{prefix}: {boosterName} (已拒絕)</span>;
        return <span className="px-2 py-0.5 rounded text-[10px] font-medium bg-yellow-100 text-yellow-700">{prefix}: {boosterName} (待確認)</span>;
    };

    const renderTaskCard = (task) => {
        const isSingleBoosterTask = task.productName.includes('陪玩') || task.productName.includes('陪陪') || task.productName.includes('單人陪');
        return (
        <div key={task.id} className="bg-white p-4 rounded-lg shadow-sm border border-gray-200 mb-3 hover:shadow-md transition-shadow">
            <div className="flex justify-between items-start mb-2">
                <div className="flex flex-col">
                    <span className="text-[10px] text-indigo-600 font-bold bg-indigo-50 px-1.5 py-0.5 rounded w-max mb-1">主單: {task.mainOrderId}</span>
                    <span className="text-[10px] font-mono text-gray-400">子單: {task.id}</span>
                </div>
                <div className="flex flex-col gap-1 items-end">
                    {getBoosterTag(task.booster1, task.booster1Status, '1')}
                    {!isSingleBoosterTask && getBoosterTag(task.booster2, task.booster2Status, '2')}
                </div>
            </div>
            <h4 className="font-bold text-gray-800 text-sm mb-1">{task.productName}</h4>
            <div className="text-xs text-gray-500 mb-2 flex items-center">
                <i className="fa-regular fa-user mr-1.5 text-gray-400"></i> {task.customerName} ({task.gameId})
                {vipOrderIds.has(task.mainOrderId) && <span className="ml-2 bg-gradient-to-r from-amber-400 to-yellow-500 text-white text-[9px] font-black px-1.5 py-0.5 rounded-full shadow-sm"><i className="fa-solid fa-crown"></i> VIP</span>}
            </div>
            <div className="flex flex-wrap gap-2 mb-3">
                <div className="text-xs text-indigo-600 bg-indigo-50 px-2 py-1 rounded"><i className="fa-regular fa-calendar"></i> {new Date(task.scheduledTime).toLocaleString([], {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'})}</div>
                <div className={`text-xs px-2 py-1 rounded ${task.paymentStatus === '已收款' ? 'text-emerald-600 bg-emerald-50' : 'text-red-500 bg-red-50 font-bold'}`}>
                    <i className="fa-solid fa-wallet"></i> {task.paymentStatus === '已收款' ? task.paymentMethod : '尚未付款'}
                </div>
            </div>
            
            {task.orderNotes && (
                <div className="text-xs text-amber-700 bg-amber-50 p-2 rounded-lg border border-amber-100 mb-3 shadow-inner">
                    <i className="fa-regular fa-comment-dots mr-1"></i> <span className="font-bold">備註：</span>{task.orderNotes}
                </div>
            )}
            
            <div className="flex gap-2 mt-2 pt-3 border-t border-gray-100">
                {task.status === '待收款' && <div className="flex-1 flex items-center justify-center text-[10px] text-gray-400 bg-gray-50 rounded font-medium border border-gray-100">待確認收款後轉入進行中</div>}
                {task.status === '進行中' && <button onClick={() => changeSubOrderStatus(task.id, task.mainOrderId, '已結單')} className="flex-1 bg-green-500 text-white text-xs py-1.5 rounded hover:bg-green-600 transition-colors"><i className="fa-solid fa-check"></i> 完成結單</button>}
                {task.status === '已結單' && (
                    <div className="flex-1 text-center text-xs text-green-600 font-medium py-1.5 leading-tight">
                        <div><i className="fa-regular fa-circle-check"></i> 訂單已完成</div>
                        {task.completedAt && <div className="text-[10px] text-gray-400 font-normal mt-0.5 scale-90">倒數 {Math.max(0, Math.ceil((ARCHIVE_DELAY_MS - (currentTime - new Date(task.completedAt).getTime())) / 60000))} 分鐘歸檔</div>}
                    </div>
                )}
                {task.status === '已結單' && <button onClick={() => changeSubOrderStatus(task.id, task.mainOrderId, '進行中')} className="px-3 py-1.5 text-amber-600 bg-amber-50 hover:bg-amber-500 hover:text-white border border-amber-200 rounded text-xs transition-colors" title="退回進行中"><i className="fa-solid fa-rotate-left"></i> 退回</button>}
                <button onClick={() => setEditingTask({...task})} className="px-2 py-1.5 text-gray-400 hover:text-indigo-600 border rounded text-xs transition-colors"><i className="fa-solid fa-pen-to-square"></i></button>
            </div>
        </div>
        );
    };

    return (
        <div>
            <div className="mb-6 flex flex-col sm:flex-row justify-between items-center bg-white p-4 rounded-xl shadow-sm border border-gray-100">
                <div><h2 className="text-xl font-bold text-gray-800"><i className="fa-solid fa-table-columns text-indigo-600"></i> 執行派單看板</h2></div>
                <div className="mt-4 sm:mt-0 relative w-full sm:w-64">
                     <i className="fa-solid fa-magnifying-glass absolute left-3 top-3 text-gray-400"></i>
                     <input type="text" placeholder="搜尋..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="w-full pl-9 p-2 text-sm border rounded-lg bg-gray-50 focus:ring-indigo-500"/>
                </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="bg-gray-50 rounded-xl p-4 border border-gray-200">
                    <h3 className="font-bold text-gray-700 mb-4 pb-2 border-b-2 border-yellow-300">待收款 <span className="float-right bg-gray-200 px-2 py-0.5 rounded-full text-xs">{pending.length}</span></h3>
                    <div className="space-y-1 max-h-[60vh] overflow-y-auto pr-1">{pending.map(renderTaskCard)}</div>
                </div>
                <div className="bg-gray-50 rounded-xl p-4 border border-gray-200">
                    <h3 className="font-bold text-gray-700 mb-4 pb-2 border-b-2 border-indigo-400">進行中 <span className="float-right bg-gray-200 px-2 py-0.5 rounded-full text-xs">{inProgress.length}</span></h3>
                    <div className="space-y-1 max-h-[60vh] overflow-y-auto pr-1">{inProgress.map(renderTaskCard)}</div>
                </div>
                <div className="bg-gray-50 rounded-xl p-4 border border-gray-200 opacity-80">
                    <h3 className="font-bold text-gray-700 mb-4 pb-2 border-b-2 border-green-400">已結單 <span className="float-right bg-gray-200 px-2 py-0.5 rounded-full text-xs">{completed.length}</span></h3>
                    <div className="space-y-1 max-h-[60vh] overflow-y-auto pr-1">{completed.map(renderTaskCard)}</div>
                </div>
            </div>

            {editingTask && (
                <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm flex items-center justify-center z-50 px-4">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-md p-6">
                        <h3 className="font-bold text-gray-800 mb-4"><i className="fa-solid fa-pen-to-square"></i> 修改派單資料</h3>
                        <div className="space-y-4">
                            <div className="pb-3 border-b border-gray-100">
                                <label className="block text-xs text-gray-500 mb-1">修改主單付款方式</label>
                                <select value={editingTask.paymentMethod} onChange={(e) => setEditingTask({...editingTask, paymentMethod: e.target.value})} className="w-full p-2 text-sm border rounded focus:ring-emerald-500 bg-emerald-50/50">
                                    <option value="銀行轉帳">銀行轉帳</option><option value="8591物寶交易網">8591物寶交易網</option><option value="line pay">LINE Pay</option><option value="全家三連單">全家三連單</option>
                                </select>
                            </div>
                            <div>
                                <label className="block text-xs text-gray-500 mb-1">修改指定打手 1</label>
                                <select value={editingTask.booster1} onChange={(e) => setEditingTask({...editingTask, booster1: e.target.value})} className="w-full p-2 text-sm border rounded focus:ring-indigo-500">
                                    {Object.entries(BOOSTER_GROUPS).map(([g, m]) => <optgroup key={g} label={g}>{m.map(b => <option key={b}>{b}</option>)}</optgroup>)}
                                </select>
                            </div>
                            {(!editingTask.productName.includes('陪玩') && !editingTask.productName.includes('陪陪') && !editingTask.productName.includes('單人陪')) && (
                                <div>
                                    <label className="block text-xs text-gray-500 mb-1">修改指定打手 2</label>
                                    <select value={editingTask.booster2} onChange={(e) => setEditingTask({...editingTask, booster2: e.target.value})} className="w-full p-2 text-sm border rounded focus:ring-indigo-500">
                                        {Object.entries(BOOSTER_GROUPS).map(([g, m]) => <optgroup key={g} label={g}>{m.map(b => <option key={b}>{b}</option>)}</optgroup>)}
                                    </select>
                                </div>
                            )}
                            <div>
                                <label className="block text-xs text-gray-500 mb-1">修改預約時間</label>
                                <input type="datetime-local" value={editingTask.scheduledTime} onChange={(e) => setEditingTask({...editingTask, scheduledTime: e.target.value})} className="w-full p-2 text-sm border rounded focus:ring-indigo-500"/>
                            </div>
                            <div>
                                <label className="block text-xs text-gray-500 mb-1">修改子單備註</label>
                                <textarea value={editingTask.orderNotes || ''} onChange={(e) => setEditingTask({...editingTask, orderNotes: e.target.value})} className="w-full p-2 text-sm border rounded focus:ring-indigo-500" rows="2"></textarea>
                            </div>
                        </div>
                        <div className="mt-6 flex justify-end gap-2">
                            <button onClick={() => setEditingTask(null)} className="px-4 py-2 bg-gray-100 rounded hover:bg-gray-200 transition-colors">取消</button>
                            <button onClick={saveEditTask} className="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700 transition-colors">儲存</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

const DailySchedule = ({ orders }) => {
    const today = new Date().toISOString().slice(0,10);
    const [selectedDate, setSelectedDate] = useState(today);
    
    const scheduleSubs = useMemo(() => {
        let subs = [];
        orders.forEach(order => {
            order.subOrders.forEach(sub => {
                if (sub.scheduledTime && sub.scheduledTime.startsWith(selectedDate)) {
                    subs.push({...sub, mainOrderId: order.id, customerName: order.customerName, gameId: order.gameId, paymentStatus: order.paymentStatus});
                }
            });
        });
        return subs.sort((a, b) => new Date(a.scheduledTime) - new Date(b.scheduledTime));
    }, [orders, selectedDate]);

    return (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div className="mb-6 flex justify-between items-end border-b pb-4 print:hidden">
                <h2 className="text-xl font-bold text-gray-800"><i className="fa-regular fa-calendar-days"></i> 每日排程檢視</h2>
                <div className="flex gap-3">
                    <input type="date" value={selectedDate} onChange={e => setSelectedDate(e.target.value)} className="p-2 border rounded"/>
                    <button onClick={() => window.print()} className="bg-indigo-600 text-white px-4 py-2 rounded font-bold hover:bg-indigo-700 transition-colors"><i className="fa-solid fa-print"></i> 輸出 PDF</button>
                </div>
            </div>
            <div className="print:block" id="printable-schedule">
                <h1 className="hidden print:block text-2xl font-bold text-center mb-4">排程表 ({selectedDate})</h1>
                <table className="min-w-full text-left border-collapse">
                    <thead>
                        <tr className="bg-gray-100 border-b-2 text-sm font-bold">
                            <th className="p-3">時間</th><th className="p-3">單號</th><th className="p-3">客戶資訊</th><th className="p-3">方案</th><th className="p-3">打手</th><th className="p-3">狀態</th>
                        </tr>
                    </thead>
                    <tbody>
                        {scheduleSubs.map((task) => (
                            <tr key={task.id} className="border-b text-sm hover:bg-gray-50 transition-colors">
                                <td className="p-3 font-bold text-indigo-700">{new Date(task.scheduledTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })}</td>
                                <td className="p-3 font-mono text-xs">{task.id}</td>
                                <td className="p-3">
                                    <div className="font-bold print:hidden">{task.customerName}</div>
                                    <div className="text-xs text-gray-500 print:hidden">{task.gameId}</div>
                                    <div className="hidden print:block font-bold text-black text-lg">{task.gameId}</div>
                                </td>
                                <td className="p-3">{task.productName}</td>
                                <td className="p-3 text-xs">{task.booster1} {task.booster2 && task.booster2!=='無指定'?`, ${task.booster2}`:''}</td>
                                <td className="p-3 font-bold">{task.status}</td>
                            </tr>
                        ))}
                        {scheduleSubs.length === 0 && <tr><td colSpan="6" className="text-center py-8 text-gray-400">本日無排程</td></tr>}
                    </tbody>
                </table>
            </div>
        </div>
    );
};

const HistoryOrders = ({ orders, currentTime }) => {
    const [searchTerm, setSearchTerm] = useState('');

    const archivedSubs = useMemo(() => {
        const subs = [];
        orders.forEach(order => {
            if (isOrderFullyArchived(order, currentTime)) {
                order.subOrders.forEach(sub => {
                    subs.push({...sub, mainOrderId: order.id, customerName: order.customerName, gameId: order.gameId});
                });
            }
        });
        return subs.sort((a, b) => new Date(b.completedAt || 0) - new Date(a.completedAt || 0));
    }, [orders, currentTime]);
    
    const filteredSubs = useMemo(() => {
        const lowerTerm = searchTerm.toLowerCase();
        if (!lowerTerm) return archivedSubs;
        return archivedSubs.filter(sub => {
            const searchStr = `${sub.mainOrderId} ${sub.id} ${sub.customerName} ${sub.gameId} ${sub.productName} ${sub.booster1} ${sub.booster2 || ''}`.toLowerCase();
            return searchStr.includes(lowerTerm);
        });
    }, [archivedSubs, searchTerm]);

    return (
        <div className="bg-white rounded-xl shadow-sm border p-6 opacity-90">
            <div className="mb-6 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <h2 className="text-xl font-bold text-gray-600"><i className="fa-solid fa-box-archive"></i> 歷史訂單紀錄 (已歸檔)</h2>
                <div className="relative w-full sm:w-64">
                     <i className="fa-solid fa-magnifying-glass absolute left-3 top-3 text-gray-400"></i>
                     <input type="text" placeholder="搜尋單號、客戶、方案或打手..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full pl-9 p-2 text-sm border rounded-lg bg-gray-50 focus:ring-indigo-500"/>
                </div>
            </div>
            <div className="overflow-x-auto">
                <table className="min-w-full text-left text-sm border-collapse">
                    <thead>
                        <tr className="bg-gray-50 border-b text-gray-500 font-bold">
                            <th className="p-3">完結時間</th><th className="p-3">單號</th><th className="p-3">客戶資訊</th>
                            <th className="p-3">方案內容</th><th className="p-3">負責打手</th><th className="p-3">金額</th>
                        </tr>
                    </thead>
                    <tbody>
                        {filteredSubs.map(sub => (
                            <tr key={sub.id} className="border-b hover:bg-gray-50 transition-colors">
                                <td className="p-3 text-gray-500 whitespace-nowrap">{new Date(sub.completedAt).toLocaleString([], {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'})}</td>
                                <td className="p-3 font-mono text-xs text-indigo-600">{sub.id}</td>
                                <td className="p-3"><div className="font-bold text-gray-700">{sub.customerName}</div><div className="text-xs text-gray-400">{sub.gameId}</div></td>
                                <td className="p-3 text-gray-700">{sub.productName}</td>
                                <td className="p-3 text-emerald-600 font-medium">{sub.booster1}{sub.booster2 && sub.booster2 !== '無指定' ? `、${sub.booster2}` : ''}</td>
                                <td className="p-3 font-bold text-gray-600">${sub.price}</td>
                            </tr>
                        ))}
                        {filteredSubs.length === 0 && <tr><td colSpan="6" className="text-center py-8 text-gray-400">找不到符合的歷史紀錄</td></tr>}
                    </tbody>
                </table>
            </div>
        </div>
    );
};

const CustomerRecords = ({ orders, showAlert }) => {
    const [selectedCustomer, setSelectedCustomer] = useState(null);
    const [remarkText, setRemarkText] = useState('');
    const [isSavingRemark, setIsSavingRemark] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    
    const customers = useMemo(() => {
        const customerMap = {};
        const now = new Date();
        const thisMonthStr = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`;
        const lastMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        const lastMonthStr = `${lastMonthDate.getFullYear()}-${String(lastMonthDate.getMonth()+1).padStart(2,'0')}`;

        orders.forEach(order => {
            const key = order.gameId;
            if (!customerMap[key]) {
                customerMap[key] = { name: order.customerName, gameId: order.gameId, history: [], thisMonthTotal: 0, lastMonthTotal: 0 };
            }
            const orderMonth = order.createdAt.slice(0, 7);
            if (order.paymentStatus === '已收款') {
                if (orderMonth === thisMonthStr) customerMap[key].thisMonthTotal += order.totalAmount;
                if (orderMonth === lastMonthStr) customerMap[key].lastMonthTotal += order.totalAmount;
            }
            order.subOrders.forEach(sub => {
                customerMap[key].history.push({...sub, orderDate: order.createdAt, mainId: order.id});
            });
        });
        return Object.values(customerMap);
    }, [orders]);

    useEffect(() => {
        if (selectedCustomer) {
            setRemarkText('載入中...');
            db.collection('customers').doc(selectedCustomer.gameId).get().then(doc => {
                if (doc.exists) setRemarkText(doc.data().remark || '');
                else setRemarkText('');
            }).catch(() => setRemarkText(''));
        }
    }, [selectedCustomer]);

    const handleSaveRemark = async () => {
        if (!selectedCustomer) return;
        setIsSavingRemark(true);
        try {
            await db.collection('customers').doc(selectedCustomer.gameId).set({ remark: remarkText }, { merge: true });
            showAlert('備註已成功儲存！');
        } catch (e) { showAlert('儲存失敗：' + e.message); }
        setIsSavingRemark(false);
    };

    if (selectedCustomer) {
        const isVip = selectedCustomer.thisMonthTotal >= 5000;
        return (
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 animate-fade-in-up">
                <button onClick={() => setSelectedCustomer(null)} className="mb-4 text-indigo-600 font-bold hover:underline transition-all"><i className="fa-solid fa-arrow-left"></i> 返回列表</button>
                <div className="flex gap-4 mb-6 flex-wrap">
                    <div className="flex-1 bg-gray-50 p-4 rounded-lg min-w-[200px] border border-gray-100 flex flex-col justify-center">
                        <h3 className="text-xl font-bold">{selectedCustomer.name} <span className="text-sm font-normal text-gray-500">({selectedCustomer.gameId})</span></h3>
                        {isVip && <span className="mt-1 inline-block w-max bg-gradient-to-r from-amber-400 to-yellow-500 text-white text-[10px] font-black px-2 py-0.5 rounded-full shadow-sm"><i className="fa-solid fa-crown"></i> 當月 VIP 客戶</span>}
                    </div>
                    <div className="bg-indigo-50 p-4 rounded-lg border border-indigo-100"><div className="text-indigo-600 text-sm font-bold">本月消費</div><div className="text-xl font-black text-indigo-800">${selectedCustomer.thisMonthTotal}</div></div>
                    <div className="bg-slate-50 p-4 rounded-lg border border-slate-200"><div className="text-slate-500 text-sm font-bold">上月消費</div><div className="text-xl font-black text-slate-700">${selectedCustomer.lastMonthTotal}</div></div>
                </div>

                <div className="mb-6 bg-yellow-50 p-4 rounded-lg border border-yellow-200 shadow-inner">
                    <div className="flex justify-between items-center mb-2">
                        <label className="font-bold text-yellow-800"><i className="fa-regular fa-comment-dots"></i> 客戶專屬備註 (自動存雲端)</label>
                        <button onClick={handleSaveRemark} disabled={isSavingRemark} className="bg-yellow-500 hover:bg-yellow-600 text-white px-3 py-1 rounded text-sm font-bold transition-colors">
                            {isSavingRemark ? '儲存中...' : '儲存備註'}
                        </button>
                    </div>
                    <textarea value={remarkText} onChange={(e) => setRemarkText(e.target.value)} placeholder="可在此紀錄客戶的特殊需求、黑名單紀錄、偏好打手等..." className="w-full p-2 border border-yellow-300 rounded focus:ring-yellow-500 focus:border-yellow-500 bg-white min-h-[80px] text-sm"></textarea>
                </div>

                <div className="overflow-x-auto">
                    <table className="min-w-full text-sm text-left">
                        <thead><tr className="bg-gray-100"><th className="p-3">預約時間</th><th className="p-3">單號</th><th className="p-3">方案</th><th className="p-3">金額</th><th className="p-3">打手</th></tr></thead>
                        <tbody>
                            {selectedCustomer.history.map((h, i) => (
                                <tr key={i} className="border-b hover:bg-gray-50 transition-colors">
                                    <td className="p-3 text-gray-600">{new Date(h.scheduledTime).toLocaleString([], {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'})}</td>
                                    <td className="p-3 font-mono text-xs text-indigo-600">{h.id}</td>
                                    <td className="p-3">{h.productName}</td>
                                    <td className="p-3 font-medium text-red-500">${h.price}</td>
                                    <td className="p-3">{h.booster1}{h.booster2 && h.booster2 !== '無指定' ? `、${h.booster2}` : ''}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        );
    }

    const filteredCustomers = customers.filter(c => {
        if(!searchTerm) return true;
        return c.name.toLowerCase().includes(searchTerm.toLowerCase()) || c.gameId.toLowerCase().includes(searchTerm.toLowerCase());
    });

    return (
        <div className="bg-white rounded-xl shadow-sm border p-6">
            <div className="mb-6 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <h2 className="text-xl font-bold"><i className="fa-solid fa-users text-indigo-600"></i> 客戶專屬紀錄 (CRM)</h2>
                <div className="relative w-full sm:w-64">
                     <i className="fa-solid fa-magnifying-glass absolute left-3 top-3 text-gray-400"></i>
                     <input type="text" placeholder="搜尋暱稱或遊戲 ID..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full pl-9 p-2 text-sm border rounded-lg bg-gray-50 focus:ring-indigo-500"/>
                </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {filteredCustomers.map(c => (
                    <div key={c.gameId} onClick={() => setSelectedCustomer(c)} className="p-4 border rounded-lg cursor-pointer hover:border-indigo-500 hover:shadow-md transition-all group bg-white relative overflow-hidden">
                        {c.thisMonthTotal >= 5000 && <div className="absolute top-0 right-0 bg-gradient-to-bl from-yellow-400 to-amber-500 text-white text-[9px] font-black px-2 py-1 rounded-bl-lg shadow-sm"><i className="fa-solid fa-crown"></i> VIP</div>}
                        <div className="font-bold text-lg group-hover:text-indigo-600 transition-colors pr-8">{c.name}</div>
                        <div className="text-gray-500 text-sm mb-2">{c.gameId}</div>
                        <div className="flex justify-between text-xs font-bold bg-gray-50 p-2 rounded">
                            <span className="text-indigo-600">本月: ${c.thisMonthTotal}</span><span className="text-slate-500">上月: ${c.lastMonthTotal}</span>
                        </div>
                    </div>
                ))}
                {filteredCustomers.length === 0 && <div className="col-span-full text-center py-10 text-gray-400">找不到符合的客戶資料</div>}
            </div>
        </div>
    );
};

const RevenueReport = ({ orders }) => {
    const { monthlyData, currentMonthRev } = useMemo(() => {
        const now = new Date();
        const currentMonthStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
        const months = [];
        for (let i = 11; i >= 0; i--) {
            const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
            months.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`);
        }

        const dataMap = {};
        months.forEach(m => dataMap[m] = 0);

        orders.forEach(o => {
            if (o.paymentStatus === '已收款') {
                o.subOrders.forEach(sub => {
                    if (sub.status === '已結單' && sub.completedAt) {
                        try {
                            const dateObj = new Date(sub.completedAt);
                            if (isNaN(dateObj.getTime())) return;
                            const m = `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}`;
                            if (dataMap[m] !== undefined) dataMap[m] += Number(sub.price) || 0;
                        } catch (e) {}
                    }
                });
            }
        });

        const finalData = months.map(m => ({ month: m.slice(5, 7) + '月', fullMonth: m, revenue: dataMap[m] }));
        return { monthlyData: finalData, currentMonthRev: dataMap[currentMonthStr] || 0 };
    }, [orders]);

    const maxRev = Math.max(...monthlyData.map(d => d.revenue), 100);
    const profit = currentMonthRev * 0.15;

    return (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
            <h2 className="text-xl font-bold text-gray-800 mb-6 flex items-center gap-2"><i className="fa-solid fa-chart-line text-indigo-600"></i> 營業額及利潤</h2>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
                <div className="bg-indigo-50 p-6 rounded-2xl border border-indigo-100 flex flex-col justify-center">
                    <div className="text-indigo-600 font-bold mb-1">本月總營業額</div>
                    <div className="text-4xl font-black text-indigo-800">${currentMonthRev.toLocaleString()}</div>
                </div>
                <div className="bg-emerald-50 p-6 rounded-2xl border border-emerald-100 flex flex-col justify-center">
                    <div className="text-emerald-600 font-bold mb-1">本月預估利潤 (15%)</div>
                    <div className="text-4xl font-black text-emerald-800">${profit.toLocaleString()}</div>
                </div>
            </div>

            <div>
                <h3 className="font-bold text-gray-600 mb-4 text-sm">過去 12 個月營收走勢</h3>
                <div className="h-64 w-full bg-gray-50 rounded-lg p-4 pb-2 border border-gray-100 flex items-end justify-between gap-1 md:gap-2">
                    {monthlyData.map((d, i) => {
                        const heightPct = (d.revenue / maxRev) * 100;
                        return (
                            <div key={i} className="relative flex flex-col items-center flex-1 group h-full">
                                <div className="absolute -top-8 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] bg-gray-800 text-white px-2 py-1 rounded whitespace-nowrap z-10 pointer-events-none">
                                    {d.fullMonth}: ${d.revenue.toLocaleString()}
                                </div>
                                <div className="w-full flex-1 flex items-end justify-center relative">
                                    <div className="w-full bg-indigo-200 rounded-t-sm group-hover:bg-indigo-400 transition-colors" style={{ height: `${Math.max(heightPct, 1)}%`, minHeight: '4px' }}></div>
                                </div>
                                <div className="text-[10px] text-gray-500 mt-2 font-bold h-4">{d.month}</div>
                            </div>
                        );
                    })}
                </div>
            </div>
        </div>
    );
};

const BoosterSalaryReport = ({ orders, showAlert, showConfirm }) => {
    const currentMonth = new Date().toISOString().slice(0, 7);
    const [selectedMonth, setSelectedMonth] = useState(currentMonth);
    const allBoosters = Object.entries(BOOSTER_GROUPS).filter(([g]) => g !== '系統預設').flatMap(([, m]) => m);
    const [selectedBooster, setSelectedBooster] = useState(allBoosters[0]);

    const [adjustDate, setAdjustDate] = useState(new Date().toISOString().slice(0, 10));
    const [adjustReason, setAdjustReason] = useState('');
    const [adjustAmount, setAdjustAmount] = useState('');
    const [adjustments, setAdjustments] = useState([]);

    useEffect(() => {
        const unsub = db.collection('salary_adjustments').onSnapshot(snap => {
            setAdjustments(snap.docs.map(doc => ({ id: doc.id, ...doc.data() })));
        });
        return unsub;
    }, []);

    const { relevantSubs, totalSalary } = useMemo(() => {
        let subs = [];
        let salarySum = 0;

        orders.forEach(order => {
            if (order.paymentStatus === '已收款') {
                order.subOrders.forEach(sub => {
                    if (sub.status === '已結單' && sub.completedAt && sub.completedAt.startsWith(selectedMonth)) {
                        const isB1 = sub.booster1 === selectedBooster;
                        const isB2 = sub.booster2 === selectedBooster;
                        if (isB1 || isB2) {
                            const count = (sub.booster1 && sub.booster1 !== '無指定' ? 1 : 0) + (sub.booster2 && sub.booster2 !== '無指定' && sub.booster2 !== sub.booster1 ? 1 : 0);
                            const netPool = sub.price * 0.85; 
                            const earned = count > 0 ? netPool / count : 0;
                            salarySum += earned;
                            subs.push({...sub, mainId: order.id, earned, count, type: 'order'});
                        }
                    }
                });
            }
        });

        adjustments.forEach(adj => {
            if(adj.booster === selectedBooster && adj.date.startsWith(selectedMonth)) {
                salarySum += Number(adj.amount);
                subs.push({
                    id: adj.id, completedAt: adj.date + 'T00:00:00Z', productName: `【加扣款】${adj.reason}`,
                    earned: Number(adj.amount), count: '-', type: 'adjustment'
                });
            }
        });

        subs.sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt));
        return { relevantSubs: subs, totalSalary: salarySum };
    }, [orders, adjustments, selectedMonth, selectedBooster]);

    const handleAddAdjustment = async (e) => {
        e.preventDefault();
        if(!adjustDate || !adjustReason || !adjustAmount) { showAlert('請填寫完整加扣薪資資訊'); return; }
        try {
            await db.collection('salary_adjustments').add({ booster: selectedBooster, date: adjustDate, reason: adjustReason, amount: Number(adjustAmount), createdAt: new Date().toISOString() });
            showAlert('加扣薪資紀錄已新增'); setAdjustReason(''); setAdjustAmount('');
        } catch(err) { showAlert('新增失敗: ' + err.message); }
    };

    const handleDeleteAdjustment = (id) => {
        showConfirm('確定要刪除這筆加扣薪資紀錄嗎？刪除後將重新計算薪資。', async () => {
            try { await db.collection('salary_adjustments').doc(id).delete(); showAlert('加扣紀錄已成功刪除'); } 
            catch(err) { showAlert('刪除失敗: ' + err.message); }
        });
    };

    return (
        <div className="bg-white rounded-xl shadow-sm border p-6">
            <div className="flex justify-between items-center mb-6 print:hidden">
                <h2 className="text-xl font-bold"><i className="fa-solid fa-hand-holding-dollar text-pink-500"></i> 打手薪資統計 (扣除 15% 抽成)</h2>
                <div className="flex gap-2">
                    <input type="month" value={selectedMonth} onChange={e => setSelectedMonth(e.target.value)} className="p-2 border rounded"/>
                    <select value={selectedBooster} onChange={e => setSelectedBooster(e.target.value)} className="p-2 border rounded font-bold text-pink-700">
                        {allBoosters.map(b => <option key={b}>{b}</option>)}
                    </select>
                    <button onClick={() => window.print()} className="bg-pink-600 text-white px-4 rounded font-bold hover:bg-pink-700 transition-colors"><i className="fa-solid fa-print"></i> 列印 PDF</button>
                </div>
            </div>
            
            <div className="print:block" id="printable-salary">
                <h1 className="hidden print:block text-2xl font-bold text-center mb-4">薪資明細 ({selectedBooster} / {selectedMonth})</h1>
                <div className="bg-pink-50 p-4 rounded-lg border border-pink-100 mb-6 flex justify-between items-center">
                    <div><div className="text-pink-600 font-bold">本月核算總薪資</div><div className="text-3xl font-black text-pink-700">${totalSalary.toFixed(1)}</div></div>
                    <div className="text-gray-500 font-bold">共完成 {relevantSubs.filter(s=>s.type==='order').length} 單</div>
                </div>
                <table className="min-w-full text-left text-sm border-collapse mb-8">
                    <thead><tr className="bg-gray-100"><th className="p-3">日期</th><th className="p-3">單號/類別</th><th className="p-3">項目</th><th className="p-3">平分人數</th><th className="p-3 text-right">實領金額</th></tr></thead>
                    <tbody>
                        {relevantSubs.map(t => (
                            <tr key={t.id} className="border-b hover:bg-gray-50">
                                <td className="p-3 text-gray-500">{t.type==='adjustment' ? t.completedAt.slice(0,10) : new Date(t.completedAt).toLocaleString([],{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'})}</td>
                                <td className="p-3 font-mono">{t.type==='adjustment' ? '-' : t.id}</td>
                                <td className={`p-3 ${t.type === 'adjustment' ? 'font-bold text-amber-700' : ''}`}>{t.productName}</td>
                                <td className="p-3">{t.count} {t.count !== '-' ? '人平分' : ''}</td>
                                <td className="p-3 text-right">
                                    <div className="flex items-center justify-end gap-2">
                                        <span className={`font-bold ${t.earned < 0 ? 'text-red-500' : (t.type === 'adjustment' ? 'text-emerald-600' : 'text-pink-600')}`}>
                                            {t.earned > 0 ? '+' : ''}${t.earned.toFixed(1)}
                                        </span>
                                        {t.type === 'adjustment' && (
                                            <button onClick={() => handleDeleteAdjustment(t.id)} className="text-gray-400 hover:text-red-500 print:hidden transition-colors" title="刪除此紀錄"><i className="fa-solid fa-trash-can"></i></button>
                                        )}
                                    </div>
                                </td>
                            </tr>
                        ))}
                        {relevantSubs.length === 0 && <tr><td colSpan="5" className="text-center py-8 text-gray-400">目前沒有紀錄</td></tr>}
                    </tbody>
                </table>
            </div>

            <div className="mt-8 pt-6 border-t border-gray-200 print:hidden">
                <h3 className="font-bold text-gray-700 mb-4"><i className="fa-solid fa-plus-minus text-amber-500"></i> 新增加扣薪資</h3>
                <form onSubmit={handleAddAdjustment} className="flex flex-wrap gap-4 items-end bg-gray-50 p-4 rounded-lg border border-gray-200">
                    <div><label className="block text-xs font-bold text-gray-500 mb-1">日期</label><input type="date" value={adjustDate} onChange={e=>setAdjustDate(e.target.value)} required className="p-2 border rounded text-sm w-40"/></div>
                    <div className="flex-grow"><label className="block text-xs font-bold text-gray-500 mb-1">事由</label><input type="text" value={adjustReason} onChange={e=>setAdjustReason(e.target.value)} required className="p-2 border rounded text-sm w-full" placeholder="輸入加扣款原因..."/></div>
                    <div><label className="block text-xs font-bold text-gray-500 mb-1">金額 (正數為加, 負數為扣)</label><input type="number" value={adjustAmount} onChange={e=>setAdjustAmount(e.target.value)} required className="p-2 border rounded text-sm w-32" placeholder="例: 100 或 -50"/></div>
                    <button type="submit" className="bg-amber-500 text-white font-bold py-2 px-6 rounded hover:bg-amber-600 transition-colors shadow-sm text-sm h-10">新增紀錄</button>
                </form>
            </div>
        </div>
    );
};

const DataManagement = ({ orders, showAlert, showConfirm }) => {
    const [localBackupFound, setLocalBackupFound] = useState(false);
    const [legacyData, setLegacyData] = useState([]);
    
    const [counterMonth, setCounterMonth] = useState('');
    const [counterVal, setCounterVal] = useState('');
    const [isLoadingCounter, setIsLoadingCounter] = useState(false);

    const oldOrdersToDelete = useMemo(() => {
        const now = new Date();
        const cutoffDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        const cutoffISO = cutoffDate.toISOString();
        return orders.filter(o => o.createdAt && o.createdAt < cutoffISO);
    }, [orders]);

    useEffect(() => {
        const data = localStorage.getItem('mimi_orders');
        if (data) {
            try { const parsed = JSON.parse(data); if(parsed.length > 0) { setLocalBackupFound(true); setLegacyData(parsed); } } catch(e) {}
        }

        const monthNames = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
        const currentMonthName = monthNames[new Date().getMonth()];
        setCounterMonth(currentMonthName);

        db.collection('system').doc('counter').get().then(doc => {
            if (doc.exists) {
                const data = doc.data();
                setCounterVal(data.count || 0);
                if (data.month) setCounterMonth(data.month);
            } else { setCounterVal(0); }
        }).catch(e => console.error("Counter fetch err", e));
    }, []);

    const handleDeleteOldOrders = async () => {
        const oldOrders = oldOrdersToDelete;
        if (oldOrders.length === 0) { showAlert(`目前沒有需要清理的舊訂單。`); return; }

        const now = new Date();
        const cutoffDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        const cutoffDisplay = `${cutoffDate.getFullYear()} 年 ${cutoffDate.getMonth() + 1} 月`;

        showConfirm(`系統偵測到 ${oldOrders.length} 筆建立於 ${cutoffDisplay} 以前的舊訂單。\n\n點擊「確定」將會：\n1. 自動下載一次完整資料庫備份檔。\n2. 永久刪除這些舊訂單。\n\n此操作無法復原，請謹慎操作！`, async () => {
            handleExport();
            setTimeout(async () => {
                try {
                    let batch = db.batch();
                    let count = 0;
                    for (const order of oldOrders) {
                        const docRef = db.collection('orders').doc(order.id);
                        batch.delete(docRef);
                        count++;
                        if (count >= 499) { await batch.commit(); batch = db.batch(); count = 0; }
                    }
                    if (count > 0) await batch.commit();
                    showAlert(`成功刪除 ${oldOrders.length} 筆舊訂單。`);
                } catch (error) { showAlert("刪除失敗：" + error.message); }
            }, 500);
        });
    };

    const handleUpdateCounter = async (e) => {
        e.preventDefault();
        setIsLoadingCounter(true);
        try {
            await db.collection('system').doc('counter').set({ month: counterMonth.toUpperCase(), count: Number(counterVal) }, { merge: true });
            showAlert(`單號計數器設定成功！\n目前設定為：${counterMonth.toUpperCase()} 月第 ${counterVal} 單。\n下一個訂單單號將為：${counterMonth.toUpperCase()}_${String(Number(counterVal) + 1).padStart(4, '0')}`);
        } catch(err) { showAlert("設定失敗：" + err.message); }
        setIsLoadingCounter(false);
    };

    const handleMigrate = () => {
        showConfirm(`確定要將本機的 ${legacyData.length} 筆資料強制覆蓋上傳到雲端嗎？\n這適合用在更換網址或救援資料時使用。`, async () => {
            try {
                const batch = db.batch();
                legacyData.forEach(order => { const docRef = db.collection('orders').doc(order.id); batch.set(docRef, order); });
                await batch.commit();
                showAlert("資料已經全部上傳到 Firebase 雲端。");
                localStorage.setItem('mimi_orders_migrated', JSON.stringify(legacyData)); localStorage.removeItem('mimi_orders'); setLocalBackupFound(false);
            } catch(error) { showAlert("上傳失敗: " + error.message); }
        });
    };

    const handleExport = () => {
        const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(orders, null, 2));
        const downloadAnchorNode = document.createElement('a');
        downloadAnchorNode.setAttribute("href", dataStr);
        downloadAnchorNode.setAttribute("download", "mimi_club_backup_" + new Date().toISOString().slice(0,10) + ".json");
        document.body.appendChild(downloadAnchorNode); downloadAnchorNode.click(); downloadAnchorNode.remove();
    };

    return (
        <div className="bg-white rounded-xl shadow-sm border p-6 space-y-6">
            <h2 className="text-xl font-bold mb-6"><i className="fa-solid fa-database text-blue-600"></i> 系統資料管理與校正</h2>
            
            <div className="bg-indigo-50 border border-indigo-200 p-6 rounded-xl shadow-inner">
                <h3 className="text-indigo-900 font-bold text-lg mb-2 flex items-center gap-2"><i className="fa-solid fa-calculator text-indigo-600"></i> 單號自動計數器校正</h3>
                <p className="text-sm text-indigo-700 mb-4">此處可手動校正雲端的單號計數器。官網顧客與客服端下單時，會讀取這個數字並自動加一。</p>
                <form onSubmit={handleUpdateCounter} className="flex flex-wrap items-end gap-4">
                    <div><label className="block text-xs font-bold text-indigo-800 mb-1">月份</label><input type="text" value={counterMonth} onChange={e=>setCounterMonth(e.target.value.toUpperCase())} required className="p-2 border rounded font-bold text-sm w-32 bg-white" placeholder="例: JULY"/></div>
                    <div><label className="block text-xs font-bold text-indigo-800 mb-1">當前最後一單的數字</label><input type="number" value={counterVal} onChange={e=>setCounterVal(e.target.value)} required className="p-2 border rounded font-bold text-sm w-40 bg-white" placeholder="例: 25"/></div>
                    <button type="submit" disabled={isLoadingCounter} className="bg-indigo-600 text-white font-bold px-6 py-2 rounded shadow hover:bg-indigo-700 transition-colors text-sm h-10">{isLoadingCounter ? '儲存中...' : '儲存並校正計數器'}</button>
                </form>
            </div>
            
            {localBackupFound && (
                <div className="bg-orange-50 border border-orange-200 p-6 rounded-lg shadow-inner">
                    <h3 className="text-orange-800 font-bold text-lg mb-2"><i className="fa-solid fa-triangle-exclamation"></i> 發現未同步的舊本機資料！</h3>
                    <p className="text-sm text-orange-700 mb-4">系統偵測到這個網址/瀏覽器內藏有 <strong>{legacyData.length}</strong> 筆未上雲端的舊訂單。若這是您之前輸入遺失的資料，請立即點擊下方按鈕將其推上雲端！</p>
                    <button onClick={handleMigrate} className="bg-orange-500 text-white px-6 py-2 rounded-lg font-bold shadow hover:bg-orange-600 transition-colors"><i className="fa-solid fa-cloud-arrow-up"></i> 強制將舊資料推上雲端</button>
                </div>
            )}

            <div className="bg-gray-50 border p-6 rounded-lg">
                <h3 className="font-bold text-gray-700 mb-2">下載雲端資料備份</h3>
                <p className="text-sm text-gray-500 mb-4">將所有 Firebase 資料下載為 JSON 檔案。</p>
                <button onClick={handleExport} className="bg-blue-600 text-white px-4 py-2 rounded-lg font-bold shadow hover:bg-blue-700 transition-colors"><i className="fa-solid fa-file-arrow-down"></i> 下載完整 JSON 備份檔</button>
            </div>

            {oldOrdersToDelete.length > 0 && (
                <div className="bg-red-50 border border-red-200 p-6 rounded-lg shadow-inner animate-fade-in">
                    <h3 className="font-bold text-red-800 mb-2"><i className="fa-solid fa-trash-can"></i> 清理舊訂單資料</h3>
                    <p className="text-sm text-red-700 mb-4">系統偵測到 {oldOrdersToDelete.length} 筆可被清理的舊訂單 (上上個月及更早)。為避免資料庫超過免費額度，建議定期清理。點擊按鈕後，系統會先強制下載備份檔才執行刪除。</p>
                    <button onClick={handleDeleteOldOrders} className="bg-red-600 text-white px-4 py-2 rounded-lg font-bold shadow hover:bg-red-700 transition-colors"><i className="fa-solid fa-eraser"></i> 清理 {oldOrdersToDelete.length} 筆舊訂單</button>
                </div>
            )}
        </div>
    );
};

function App() {
    const [user, setUser] = useState(null);
    const [activeTab, setActiveTab] = useState('create');
    const [orders, setOrders] = useState([]);
    const [currentTime, setCurrentTime] = useState(Date.now());
    const [dialog, setDialog] = useState(null);
    
    const showAlert = (message) => setDialog({ message });
    const showConfirm = (message, onConfirm) => setDialog({ message, onConfirm });

    useEffect(() => {
        const unsubscribeAuth = auth.onAuthStateChanged(u => {
            setUser(u);
        });
        return () => unsubscribeAuth();
    }, []);

    useEffect(() => {
        let unsubscribeOrders;
        if (user) {
            unsubscribeOrders = db.collection('orders').onSnapshot(snapshot => {
                const ordersData = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
                ordersData.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
                setOrders(ordersData);
            }, error => {
                console.error("雲端連線失敗:", error);
                if (error.code === 'permission-denied') {
                    auth.signOut();
                }
            });
        }
        const timer = setInterval(() => setCurrentTime(Date.now()), 60000);
        return () => { 
            if(unsubscribeOrders) unsubscribeOrders(); 
            clearInterval(timer); 
        };
    }, [user]);

    // 推播權限請求
    useEffect(() => {
        if (!user || user.email !== 'cs@mimiclub.com') return;

        const setupMessaging = async () => {
            try {
                const messaging = firebase.messaging();
                const permission = await Notification.requestPermission();
    
                if (permission === 'granted') {
                    const currentToken = await messaging.getToken({ 
                        vapidKey: 'BGZSDM27uLPzxRZDX98jtH9HT3-yWgc4sXTvQjuK4BE2zV43kYvxguqtZBX8V-ydDx8oR-wNb1ZiR66Mo5yLywc' 
                    });
        
                    if (currentToken) {
                        await db.collection('cs_tokens').doc('admin').set({
                            tokens: firebase.firestore.FieldValue.arrayUnion(currentToken),
                            updatedAt: firebase.firestore.FieldValue.serverTimestamp()
                        }, { merge: true }); 
                    }
                }
            } catch (error) {
                console.error('取得推播權限失敗:', error);
            }
        };

        setupMessaging();
        firebase.messaging().onMessage((payload) => {
            new Notification(payload.notification.title, {
                body: payload.notification.body,
                icon: 'https://media.mimiclub.org/網站圖檔資源/銀灰色平面金屬圖像.jpg',
                tag: 'mimi-task-alert'
            });
        });
    }, [user]);

    const handleLogin = async (e) => {
        e.preventDefault();
        const pwd = e.target.password.value;
        try {
            await auth.signInWithEmailAndPassword("cs@mimiclub.com", pwd);
        } catch (error) {
            showAlert("登入失敗：密碼錯誤或權限不足");
        }
    };

    const handleLogout = () => {
        auth.signOut();
    };

    if (!user || user.email !== 'cs@mimiclub.com') {
        return (
            <div className="flex flex-col items-center justify-center p-6 text-gray-800 pb-safe bg-[#d8d2c9]" style={{ minHeight: '100dvh' }}>
                <GlobalDialog dialog={dialog} setDialog={setDialog} />
                <div className="w-full max-w-sm bg-white text-gray-900 rounded-3xl p-8 shadow-2xl">
                    <div className="text-center mb-8">
                        <div className="relative w-24 h-24 mx-auto mb-4">
                            <div className="absolute inset-0 bg-gradient-to-tr from-[#d8d2c9] to-[#a39a8f] rounded-3xl flex items-center justify-center text-white text-3xl font-black shadow-lg -z-10">M</div>
                            <img 
                                src="https://media.mimiclub.org/網站圖檔資源/銀灰色平面金屬圖像.jpg" 
                                alt="Logo" 
                                referrerPolicy="no-referrer" 
                                className="w-24 h-24 object-cover rounded-3xl shadow-lg" 
                                onError={(e) => { e.target.style.display = 'none'; }} 
                            />
                        </div>
                        <h2 className="text-2xl font-black text-gray-800 tracking-wide">客服系統登入</h2>
                        <p className="text-xs text-gray-500 mt-1">最高權限存取通道</p>
                    </div>
                    <form onSubmit={handleLogin} className="space-y-4">
                        <div className="bg-gray-50 border border-gray-200 rounded-xl p-4 text-center font-bold text-gray-700 shadow-inner">
                            客服總控 (Admin)
                        </div>
                        <input name="password" type="password" placeholder="請輸入專屬密碼" className="w-full p-4 bg-gray-50 border border-gray-200 rounded-xl font-bold text-center focus:ring-2 focus:ring-[#a39a8f] outline-none transition-shadow" required />
                        <button type="submit" className="w-full bg-[#a39a8f] text-white font-bold py-4 rounded-xl shadow-md active:bg-[#8b8277] transition-colors mt-2">
                            登入系統
                        </button>
                    </form>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-[#f8f6f3] font-sans text-gray-800 antialiased">
            <GlobalDialog dialog={dialog} setDialog={setDialog} />
            
            <header className="bg-indigo-900 text-white p-4 shadow-md sticky top-0 z-10 print:hidden">
                <div className="max-w-7xl mx-auto flex justify-between items-center">
                    <div className="flex items-center space-x-3">
                        <img src="https://media.mimiclub.org/網站圖檔資源/銀灰色平面金屬圖像.jpg" alt="Logo" referrerPolicy="no-referrer" className="w-10 h-10 object-cover rounded-lg shadow-sm" onError={(e) => { e.target.style.display = 'none'; }} />
                        <h1 className="text-xl font-bold tracking-wider">MiMi Club 管理端系統</h1>
                    </div>
                    <button onClick={handleLogout} className="bg-indigo-800 hover:bg-indigo-700 text-white text-xs px-4 py-2 rounded-full font-bold transition-colors">
                        <i className="fa-solid fa-right-from-bracket"></i> 安全登出
                    </button>
                </div>
            </header>

            <div className="max-w-7xl mx-auto p-4 flex flex-col md:flex-row gap-6 mt-4">
                <aside className="w-full md:w-64 shrink-0 print:hidden">
                    <nav className="bg-white rounded-xl shadow-sm border border-gray-100 p-2 space-y-1 sticky top-24">
                        <button onClick={() => setActiveTab('create')} className={`w-full flex items-center p-3 rounded-lg transition-colors gap-3 ${activeTab === 'create' ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-gray-600 hover:bg-gray-50'}`}><i className="fa-solid fa-plus w-5"></i> 1. 新增客製訂單</button>
                        <button onClick={() => setActiveTab('finance')} className={`w-full flex items-center p-3 rounded-lg transition-colors gap-3 ${activeTab === 'finance' ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-gray-600 hover:bg-gray-50'}`}><i className="fa-solid fa-file-invoice-dollar w-5"></i> 2. 財務主單對帳</button>
                        <button onClick={() => setActiveTab('dispatch')} className={`w-full flex items-center p-3 rounded-lg transition-colors gap-3 ${activeTab === 'dispatch' ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-gray-600 hover:bg-gray-50'}`}><i className="fa-solid fa-table-columns w-5"></i> 3. 執行派單看板</button>
                        <div className="my-2 border-t border-gray-100"></div>
                        <button onClick={() => setActiveTab('schedule')} className={`w-full flex items-center p-3 rounded-lg transition-colors gap-3 ${activeTab === 'schedule' ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-gray-600 hover:bg-gray-50'}`}><i className="fa-regular fa-calendar-days w-5"></i> 4. 每日排程檢視</button>
                        <button onClick={() => setActiveTab('history')} className={`w-full flex items-center p-3 rounded-lg transition-colors gap-3 ${activeTab === 'history' ? 'bg-slate-100 text-slate-700 font-bold' : 'text-gray-500 hover:bg-gray-50'}`}><i className="fa-solid fa-box-archive w-5"></i> 5. 歷史訂單紀錄</button>
                        <button onClick={() => setActiveTab('crm')} className={`w-full flex items-center p-3 rounded-lg transition-colors gap-3 ${activeTab === 'crm' ? 'bg-indigo-50 text-indigo-700 font-bold' : 'text-gray-600 hover:bg-gray-50'}`}><i className="fa-solid fa-users w-5 text-indigo-600"></i> 6. 客戶專屬紀錄</button>
                        <div className="my-2 border-t border-gray-100"></div>
                        <button onClick={() => setActiveTab('revenue')} className={`w-full flex items-center p-3 rounded-lg transition-colors gap-3 ${activeTab === 'revenue' ? 'bg-emerald-50 text-emerald-700 font-bold' : 'text-gray-600 hover:bg-gray-50'}`}><i className="fa-solid fa-chart-line w-5 text-emerald-600"></i> 7. 營業額及利潤</button>
                        <button onClick={() => setActiveTab('salary')} className={`w-full flex items-center p-3 rounded-lg transition-colors gap-3 ${activeTab === 'salary' ? 'bg-pink-50 text-pink-700 font-bold' : 'text-gray-600 hover:bg-gray-50'}`}><i className="fa-solid fa-hand-holding-dollar w-5 text-pink-500"></i> 8. 打手薪資統計</button>
                        <div className="my-2 border-t border-gray-100"></div>
                        <button onClick={() => setActiveTab('data')} className={`w-full flex items-center p-3 rounded-lg transition-colors gap-3 ${activeTab === 'data' ? 'bg-blue-50 text-blue-700 font-bold' : 'text-gray-400 hover:bg-gray-50'}`}><i className="fa-solid fa-database w-5"></i> 9. 系統資料管理</button>
                    </nav>
                </aside>

                <main className="flex-1 min-w-0 pb-20 print:w-full print:m-0 print:p-0">
                    {activeTab === 'create' && <CreateOrderForm orders={orders} setActiveTab={setActiveTab} showAlert={showAlert} />}
                    {activeTab === 'finance' && <FinanceMainOrders orders={orders} currentTime={currentTime} showAlert={showAlert} showConfirm={showConfirm} />}
                    {activeTab === 'dispatch' && <DispatchKanban orders={orders} currentTime={currentTime} showAlert={showAlert} />}
                    {activeTab === 'schedule' && <DailySchedule orders={orders} />}
                    {activeTab === 'history' && <HistoryOrders orders={orders} currentTime={currentTime} />}
                    {activeTab === 'crm' && <CustomerRecords orders={orders} showAlert={showAlert} />}
                    {activeTab === 'revenue' && <RevenueReport orders={orders} />}
                    {activeTab === 'salary' && <BoosterSalaryReport orders={orders} showAlert={showAlert} showConfirm={showConfirm} />}
                    {activeTab === 'data' && <DataManagement orders={orders} showAlert={showAlert} showConfirm={showConfirm} />}
                </main>
            </div>
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);