/* Mereka v2 — Finance: Withdraw + Expert Finances (all-transactions) + host.
   Faithful port of WithdrawPage.tsx & AllTransactionsPage.tsx. */

/* ===================== Expert Finances (all transactions) ===================== */
function FinAllTransactions({ currency = 'RM', onNavigateToWithdraw }) {
  const [searchQuery, setSearchQuery] = useState('');
  const [selected, setSelected] = useState(null);
  const filtered = FIN_TRANSACTIONS.filter(t => t.description.toLowerCase().includes(searchQuery.toLowerCase()) || (t.vendor || '').toLowerCase().includes(searchQuery.toLowerCase()));
  const cols = 'grid grid-cols-1 lg:grid-cols-[110px_150px_130px_1.8fr_1.2fr_120px_130px] gap-4';
  return (
    <div className="space-y-8">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div><h1 className="text-2xl font-bold text-gray-900">Expert Finances</h1><p className="text-gray-500 text-sm mt-1">Unified view of all your earnings and expenses across every hub.</p></div>
        {onNavigateToWithdraw && <button className="h-10 px-6 bg-black hover:bg-gray-800 text-white font-bold rounded-full" onClick={onNavigateToWithdraw}>Withdraw Funds</button>}
      </div>
      <div className="bg-white rounded-[24px] overflow-hidden" style={{ boxShadow: '0 4px 30px rgba(0,0,0,0.04)' }}>
        <div className="p-8">
          <div className="flex flex-col gap-6 mb-8">
            <div className="flex flex-col lg:flex-row lg:items-end justify-between gap-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 flex-1">
                <div className="space-y-2"><label className="text-[12px] font-medium text-gray-500">Date range</label><FSelect value="all-time" onValueChange={() => {}} rightIcon={<FIcon name="calendar" size={16} />} triggerClassName="h-11" options={[{ value: 'all-time', label: 'All time' }, { value: 'last-7', label: 'Last 7 days' }, { value: 'last-30', label: 'Last 30 days' }]} /></div>
                <div className="space-y-2"><label className="text-[12px] font-medium text-gray-500">Hub</label><FSelect value="all" onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'all', label: 'All Hubs' }, ...FIN_HUBS.map(h => ({ value: h.id, label: h.name }))]} /></div>
                <div className="space-y-2"><label className="text-[12px] font-medium text-gray-500">Status</label><FSelect value="all" onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'all', label: 'All' }, { value: 'completed', label: 'Completed' }, { value: 'on-hold', label: 'On Hold' }]} /></div>
                <div className="space-y-2"><label className="text-[12px] font-medium text-gray-500">Type</label><FSelect value="all" onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'all', label: 'All' }, { value: 'earning', label: 'Earnings' }, { value: 'expense', label: 'Spendings' }, { value: 'withdrawal', label: 'Withdrawals' }]} /></div>
              </div>
              <div className="flex items-center gap-3"><button onClick={() => finToast.success('CSV exported')} className="h-11 px-6 bg-black hover:bg-gray-800 text-white font-bold rounded-full">CSV Export</button></div>
            </div>
            <div className="relative group max-w-xl"><FIcon name="search" size={20} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-black transition-colors" /><input placeholder="Search by description or vendor..." value={searchQuery} onChange={e => setSearchQuery(e.target.value)} className="w-full pl-12 h-14 bg-gray-50/50 border border-gray-100 rounded-2xl focus:bg-white focus:outline-none focus:border-gray-200 transition-all text-sm placeholder:text-gray-400" /></div>
          </div>
          <div className="border border-gray-100 rounded-[20px] overflow-x-auto bg-white">
            <div className="min-w-[1100px]">
              <div className={`${cols} px-6 py-5 bg-white items-center border-b border-gray-100/60`}>
                <div className="text-[11px] font-bold text-gray-400 uppercase tracking-[0.15em]">Date</div>
                <div className="text-[11px] font-bold text-gray-400 uppercase tracking-[0.15em] text-center">Hub</div>
                <div className="text-[11px] font-bold text-gray-400 uppercase tracking-[0.15em]">Type</div>
                <div className="text-[11px] font-bold text-gray-400 uppercase tracking-[0.15em]">Description</div>
                <div className="text-[11px] font-bold text-gray-400 uppercase tracking-[0.15em]">Vendor</div>
                <div className="text-[11px] font-bold text-gray-400 uppercase tracking-[0.15em] text-right">Amount</div>
                <div className="text-[11px] font-bold text-gray-400 uppercase tracking-[0.15em] text-right pr-4">Status</div>
              </div>
              <div className="divide-y divide-gray-50">
                {filtered.map(t => (
                  <div key={t.id} onClick={() => setSelected(t)} className={`${cols} px-6 py-7 items-center hover:bg-gray-50/50 transition-colors cursor-pointer group`}>
                    <div className="text-[13px] font-medium text-gray-900">{finDate(t.date)}</div>
                    <div className="flex justify-center"><div className="bg-white border border-gray-100 text-gray-600 font-bold px-4 py-2 text-[11px] rounded-full whitespace-nowrap" style={{ boxShadow: '0 1px 2px rgba(0,0,0,0.02)' }}>{FIN_HUBS.find(h => h.id === t.hubId)?.name || 'Unknown'}</div></div>
                    <div className="flex flex-col gap-1.5">
                      <div className="flex items-center gap-1.5"><span className={`text-[11px] font-bold uppercase tracking-wider h-5 inline-flex items-center px-2 rounded-md w-fit ${t.type === 'earning' ? 'bg-green-50 text-green-700' : ''}${t.type === 'expense' ? 'bg-red-50 text-red-700' : ''}${t.type === 'withdrawal' ? 'bg-blue-50 text-blue-700' : ''}`}>{t.type === 'earning' ? 'Earning' : t.type === 'expense' ? 'Spending' : 'Withdrawal'}</span>{t.mainType === 'REFUND' && <span className="text-[11px] font-bold uppercase bg-orange-50 text-orange-700 h-5 inline-flex items-center px-2 rounded-md">Refund</span>}</div>
                      <span className="text-[13px] text-gray-700 font-bold leading-tight">{t.subType}</span>
                    </div>
                    <div className="text-[14px] font-bold text-gray-900 truncate pr-4">{t.description}</div>
                    <div className="flex items-center gap-2 min-w-0"><FAvatar src={t.vendorAvatar} fallback="V" className="w-8 h-8 rounded-full border border-gray-100 flex-shrink-0" /><span className="text-[14px] font-bold text-gray-900 truncate">{t.vendor}</span></div>
                    <div className={`text-[15px] font-bold text-right ${t.type === 'earning' ? 'text-green-600' : 'text-gray-900'}`}>{t.type === 'earning' ? '+RM ' : 'RM '}{finNum(t.net != null ? t.net : Math.abs(t.gross || 0))}</div>
                    <div className="flex justify-end pr-2"><span className={`border-none text-[11px] font-bold h-6 px-3 rounded-md uppercase inline-flex items-center gap-1.5 w-fit ${t.status === 'completed' || t.status === 'succeeded' ? 'bg-[#E6F4EA] text-[#1E8E3E]' : ''}${t.status === 'on hold' || t.status === 'pending' ? 'bg-[#FEF7E0] text-[#B06000]' : ''}${t.status === 'failed' ? 'bg-[#FCE8E6] text-[#D93025]' : ''}`}>{t.status === 'on hold' ? 'ON HOLD' : (t.status === 'completed' || t.status === 'succeeded' ? 'COMPLETED' : t.status.toUpperCase())}{(t.status === 'on hold' || t.status === 'pending') && <FIcon name="alertCircle" size={12} />}</span></div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
      <FModal open={!!selected} onClose={() => setSelected(null)} panelClassName="max-w-md overflow-hidden">
        {selected && <FinTransactionDetail transaction={selected} currency={currency} onClose={() => setSelected(null)} onWithdraw={() => { setSelected(null); if (onNavigateToWithdraw) onNavigateToWithdraw(); }} onConfirmSplit={() => {}} />}
      </FModal>
    </div>
  );
}

/* ===================== Withdraw page ===================== */
function FinWithdraw({ onBack, currency = 'RM', mode = 'admin' }) {
  const [selectedUser, setSelectedUser] = useState(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isBulkOpen, setIsBulkOpen] = useState(false);
  const [withdrawAmount, setWithdrawAmount] = useState('');
  const [selectedCard, setSelectedCard] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [hubFeePercent, setHubFeePercent] = useState('0');
  const [bulkFees, setBulkFees] = useState({});
  const [expertBulkCards, setExpertBulkCards] = useState({});

  const handleWithdrawClick = (item) => {
    setSelectedUser(item);
    setWithdrawAmount(item.balance.toString());
    setHubFeePercent('0');
    const pool = mode === 'expert' ? FIN_BANK_ACCOUNTS : (item.cards || []);
    const def = pool.find(c => c.isDefault) || pool[0];
    setSelectedCard(def?.id || '');
    setIsDialogOpen(true);
  };

  const filteredUsers = FIN_USERS.filter(u => u.name.toLowerCase().includes(searchQuery.toLowerCase()) || u.email.toLowerCase().includes(searchQuery.toLowerCase()) || u.department.toLowerCase().includes(searchQuery.toLowerCase()));
  const totalAvailable = mode === 'admin' ? FIN_USERS.reduce((a, u) => a + u.balance, 0) : FIN_EXPERT_HUB_BALANCES.reduce((a, h) => a + h.balance, 0);
  const activeCount = mode === 'admin' ? FIN_USERS.filter(u => u.balance > 0).length : FIN_EXPERT_HUB_BALANCES.filter(h => h.balance > 0).length;

  const singleAmount = parseFloat(withdrawAmount) || 0;
  const singleFeePercent = parseFloat(hubFeePercent) || 0;
  const singleFeeAmount = (singleAmount * singleFeePercent) / 100;
  const singleNet = singleAmount - singleFeeAmount;

  const usersWithBalance = FIN_USERS.filter(u => u.balance > 0);
  const hubsWithBalance = FIN_EXPERT_HUB_BALANCES.filter(h => h.balance > 0);
  const bulkItems = mode === 'admin' ? usersWithBalance : hubsWithBalance;
  let totalGross = 0, totalFee = 0, totalNet = 0;
  bulkItems.forEach(item => { const id = mode === 'admin' ? item.id : item.hubId; const g = item.balance; const f = (g * (bulkFees[id] || 0)) / 100; totalGross += g; totalFee += f; totalNet += g - f; });

  const openBulk = () => {
    if (mode === 'admin') { const f = {}; FIN_USERS.forEach(u => f[u.id] = 0); setBulkFees(f); }
    else { const f = {}, c = {}; FIN_EXPERT_HUB_BALANCES.forEach(h => { f[h.hubId] = 15; const def = FIN_BANK_ACCOUNTS.find(x => x.isDefault) || FIN_BANK_ACCOUNTS[0]; c[h.hubId] = def?.id || ''; }); setBulkFees(f); setExpertBulkCards(c); }
    setIsBulkOpen(true);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <button className="h-10 w-10 p-0 rounded-full flex items-center justify-center hover:bg-gray-100 transition-all -ml-2" onClick={onBack}><FIcon name="arrowLeft" size={24} className="text-gray-700" /></button>
        <div><h1 className="text-2xl font-bold text-gray-900">{mode === 'expert' ? 'Expert Payout' : 'Withdraw Funds'}</h1><p className="text-gray-500 text-sm">{mode === 'expert' ? 'Withdraw your earnings across all assigned hubs.' : 'Manage payouts and withdrawals for hub members.'}</p></div>
      </div>

      {/* Overview cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-black text-white border border-black rounded-xl p-6"><div className="text-gray-400 text-sm">Total Withdrawable</div><div className="text-3xl font-bold mt-1">{currency} {totalAvailable.toFixed(2)}</div><div className="text-sm text-gray-400 flex items-center gap-1 mt-3"><FIcon name="building2" size={12} /> From {activeCount} active {mode === 'expert' ? 'hubs' : 'members'}</div></div>
        <div className="bg-white border border-gray-200 rounded-xl p-6"><div className="text-gray-500 text-sm">Pending Requests</div><div className="text-3xl font-bold mt-1">12</div><div className="text-sm text-gray-500 mt-3">Requires approval</div></div>
        <div className="bg-white border border-gray-200 rounded-xl p-6"><div className="text-gray-500 text-sm">Processed Today</div><div className="text-3xl font-bold mt-1">{currency} 4,500</div><div className="text-sm text-green-600 flex items-center gap-1 mt-3"><FIcon name="check" size={12} /> All systems operational</div></div>
      </div>

      {/* Toolbar */}
      <div className="space-y-4">
        <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
          <div className="flex items-center gap-2 w-full sm:w-auto">
            <div className="relative w-full sm:w-80"><FIcon name="search" size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" /><input placeholder={mode === 'expert' ? 'Search hubs...' : 'Search members...'} value={searchQuery} onChange={e => setSearchQuery(e.target.value)} className="w-full pl-9 h-11 bg-white border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-gray-400" /></div>
            <button className="h-11 w-11 p-0 rounded-full flex items-center justify-center border border-gray-200 hover:bg-gray-50"><FIcon name="filter" size={18} className="text-gray-500" /></button>
          </div>
          <div className="flex gap-3 w-full sm:w-auto">
            <button onClick={() => finToast.success('Report exported')} className="h-11 px-6 font-bold rounded-full gap-2 inline-flex items-center border border-gray-200 hover:bg-gray-50"><FIcon name="download" size={18} /> Export Report</button>
            <button onClick={openBulk} className="h-11 px-6 bg-black hover:bg-gray-800 text-white font-bold rounded-full gap-2 inline-flex items-center"><FIcon name="dollarSign" size={16} /> Bulk Withdraw</button>
          </div>
        </div>

        {/* Member / hub list */}
        <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
          <div className="px-6 py-5 border-b flex justify-between items-center bg-gray-50/30"><h2 className="text-sm font-bold text-gray-900 uppercase tracking-wider px-1">{mode === 'expert' ? 'Hub Balances' : 'Member List'}</h2><span className="font-bold bg-white border border-gray-200 rounded px-2 py-0.5 text-xs">{activeCount} Active</span></div>
          <div className="overflow-x-auto">
            <table className="w-full min-w-[760px]">
              <thead className="bg-gray-50/50"><tr>
                <th className="w-[250px] text-left text-[12px] font-bold text-gray-500 uppercase py-4 px-6">{mode === 'expert' ? 'Hub' : 'Member'}</th>
                <th className="text-left text-[12px] font-bold text-gray-500 uppercase py-4">{mode === 'expert' ? 'Status' : 'Department'}</th>
                <th className="text-left text-[12px] font-bold text-gray-500 uppercase py-4">{mode === 'expert' ? 'Linked Account' : 'Default Bank Account'}</th>
                <th className="text-right text-[12px] font-bold text-gray-500 uppercase py-4">Available Balance</th>
                <th className="w-[120px] py-4 px-6"></th>
              </tr></thead>
              <tbody>
                {(mode === 'expert' ? FIN_EXPERT_HUB_BALANCES : filteredUsers).map(item => {
                  const def = mode === 'expert' ? FIN_BANK_ACCOUNTS[0] : (item.cards?.find(c => c.isDefault) || item.cards?.[0]);
                  return (
                    <tr key={item.hubId || item.id} className="group hover:bg-gray-50/50 transition-colors border-t border-gray-100">
                      <td className="py-4 px-6"><div className="flex items-center gap-3">{mode === 'expert' ? <div className="p-2.5 bg-gray-100 rounded-xl group-hover:bg-white transition-colors border border-transparent group-hover:border-gray-100"><FIcon name="building2" size={20} className="text-gray-500" /></div> : <FAvatar src={item.avatar} fallback={item.name.charAt(0)} className="h-10 w-10 rounded-full border-2 border-transparent shadow-sm font-bold" />}<div><div className="font-bold text-gray-900 leading-tight">{item.hubName || item.name}</div><div className="text-[12px] text-gray-500 mt-0.5">{mode === 'expert' ? 'Hub Assignment' : item.email}</div></div></div></td>
                      <td className="py-4"><span className="font-bold text-[11px] bg-gray-100/80 px-2 h-5 inline-flex items-center rounded">{mode === 'expert' ? 'Active' : item.department}</span></td>
                      <td className="py-4">{def ? <div className="flex items-center gap-2 text-[12px] font-medium text-gray-600"><FIcon name="creditCard" size={14} className="text-gray-400" /><span className="font-bold text-gray-700">{def.bankName}</span><span className="text-gray-400">•••• {def.last4}</span></div> : <span className="text-[12px] text-red-500 font-bold flex items-center gap-1"><FIcon name="alertCircle" size={12} /> Not Set</span>}</td>
                      <td className="text-right font-mono font-bold text-gray-900 py-4">{currency} {finNum(item.balance)}</td>
                      <td className="py-4 px-6"><button className="w-full h-9 rounded-full font-bold text-[12px] border border-gray-200 hover:bg-black hover:text-white hover:border-black transition-all shadow-sm disabled:opacity-40 disabled:hover:bg-white disabled:hover:text-gray-900" onClick={() => handleWithdrawClick(item)} disabled={item.balance <= 0}>Withdraw</button></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* Single withdraw dialog */}
      <FModal open={isDialogOpen} onClose={() => setIsDialogOpen(false)} panelClassName="sm:max-w-[440px] overflow-hidden rounded-[24px]">
        <div className="p-6 pb-2"><h3 className="text-xl font-bold tracking-tight text-gray-900">Withdraw Funds</h3><p className="text-gray-500 text-[13px] mt-1">{mode === 'expert' ? `Confirm your withdrawal from ${selectedUser?.hubName}.` : `Process a withdrawal for ${selectedUser?.name}.`}</p></div>
        {selectedUser && (
          <div className="px-6 py-4 space-y-5">
            <div className="flex items-center gap-4"><label className="w-24 text-left text-gray-500 text-[13px] font-medium">Source</label><div className="flex-1 flex items-center gap-2.5 px-3 py-2 bg-gray-50/50 rounded-xl border border-gray-100/50"><div className="p-1.5 bg-white rounded-lg shadow-sm border border-gray-100"><FIcon name="building2" size={16} className="text-gray-400" /></div><span className="text-[13px] font-bold text-gray-900 tracking-tight">{selectedUser.hubName || selectedUser.name}</span></div></div>
            <div className="flex items-center gap-4"><label className="w-24 text-left text-gray-500 text-[13px] font-medium">To Account</label><div className="flex-1"><FSelect value={selectedCard} onValueChange={setSelectedCard} leftIcon={<FIcon name="creditCard" size={16} />} triggerClassName="h-11" options={(mode === 'expert' ? FIN_BANK_ACCOUNTS : (selectedUser.cards || [])).map(c => ({ value: c.id, label: `${c.bankName} •••• ${c.last4}` }))} /></div></div>
            <div className="flex flex-col gap-1.5">
              <div className="flex items-center gap-4"><label className="w-24 text-left text-gray-500 text-[13px] font-medium">Amount</label><div className="flex-1 relative"><span className="absolute left-4 top-1/2 -translate-y-1/2 text-[13px] font-bold text-gray-400 uppercase pointer-events-none">{currency}</span><input type="number" value={withdrawAmount} onChange={e => setWithdrawAmount(e.target.value)} className="w-full h-11 pl-12 pr-4 rounded-xl bg-gray-50/50 border border-gray-100/50 focus:outline-none focus:border-black text-[15px] font-bold tracking-tight" /></div></div>
              <div className="flex justify-end pr-1"><span className="text-[11px] font-bold text-gray-400/80 uppercase tracking-wider">Max: {currency} {selectedUser.balance.toFixed(2)}</span></div>
            </div>
            <div className="h-px bg-gray-100/80 my-2" />
            <div className="flex items-center gap-4"><label className="w-24 text-left text-gray-500 text-[13px] font-medium">Hub Fee (%)</label><div className="flex-1 relative"><input type="number" min="0" max="100" value={hubFeePercent} onChange={e => setHubFeePercent(e.target.value)} disabled={mode === 'expert'} className="w-full h-11 rounded-xl bg-gray-50/50 border border-gray-100/50 focus:outline-none focus:border-black text-right pr-8 pl-3 text-[14px] font-bold disabled:opacity-60" /><span className="absolute right-4 top-1/2 -translate-y-1/2 text-[12px] font-bold text-gray-400">%</span></div></div>
            <div className="bg-[#FBFCFD] border border-gray-100/80 rounded-2xl p-5 space-y-3.5">
              <div className="flex justify-between items-center px-0.5"><span className="text-[13px] font-medium text-gray-500/90">Gross Amount</span><div className="flex items-center gap-1.5"><span className="text-[12px] font-bold text-gray-400">{currency}</span><span className="text-[14px] font-bold text-gray-900 font-mono">{finNum(singleAmount)}</span></div></div>
              <div className="flex justify-between items-center px-0.5"><span className="text-[13px] font-medium text-red-500/80">Hub Fee ({hubFeePercent}%)</span><div className="flex items-center gap-1.5"><span className="text-[12px] font-bold text-red-400">-{currency}</span><span className="text-[14px] font-bold text-red-500 font-mono">{finNum(singleFeeAmount)}</span></div></div>
              <div className="h-px bg-gray-100/60" />
              <div className="flex justify-between items-center px-0.5 pt-0.5"><span className="text-[14px] font-bold text-green-600">Net Payout</span><div className="flex items-center gap-1.5"><span className="text-[12px] font-bold text-green-500/80">{currency}</span><span className="text-[16px] font-bold text-green-600 font-mono">{finNum(singleNet)}</span></div></div>
            </div>
          </div>
        )}
        <div className="p-6 pt-2 flex items-center justify-between gap-3">
          <button className="flex-1 h-12 px-6 font-bold rounded-full border border-gray-200 text-gray-600 hover:bg-gray-50" onClick={() => setIsDialogOpen(false)}>Cancel</button>
          <button onClick={() => { setIsDialogOpen(false); finToast.success('Withdrawal confirmed', { description: `${currency} ${finNum(singleNet)} is on its way.` }); }} className="flex-[1.5] h-12 px-6 bg-black hover:bg-gray-800 text-white font-bold rounded-full shadow-lg">Confirm Withdrawal</button>
        </div>
      </FModal>

      {/* Bulk withdraw dialog */}
      <FModal open={isBulkOpen} onClose={() => setIsBulkOpen(false)} panelClassName="max-w-[min(1800px,90vw)] w-[95vw] overflow-hidden">
        <div className="flex flex-col max-h-[90vh]">
          <div className="p-6 pb-2"><h3 className="text-lg font-bold">Process Bulk Withdrawal</h3><p className="text-sm text-gray-500 mt-1">{mode === 'admin' ? 'Review payouts and set hub fees for each expert.' : 'Review payouts and applied hub commissions across all your hub assignments.'}</p></div>
          <div className="flex-1 overflow-y-auto px-6 py-4 space-y-6 scrollbar-thin">
            <div className="bg-gray-50 border border-gray-100 rounded-xl p-5 flex items-center justify-between flex-wrap gap-3">
              <div className="flex items-center gap-4"><div className="p-3.5 bg-white rounded-xl border border-gray-200"><FIcon name="building2" size={24} className="text-gray-600" /></div><div><div className="text-[11px] text-gray-500 font-bold uppercase tracking-[0.1em] mb-1">{mode === 'admin' ? 'Withdraw From: Hub Bank Account' : 'TOTAL EXPERT PAYOUT'}</div><div className="flex items-center gap-2"><span className="text-lg font-bold text-gray-900 tracking-tight">{mode === 'admin' ? 'STRIPE TEST BANK' : 'All Hub Earnings'}</span>{mode === 'admin' && <span className="bg-green-100 text-green-700 h-4 inline-flex items-center px-1.5 text-[11px] rounded font-medium">Default</span>}</div>{mode === 'admin' && <div className="text-xs text-gray-500">****6000 • Creative Hub KL Admin</div>}</div></div>
              <div className="text-right"><div className="text-[11px] text-gray-500 font-bold uppercase tracking-[0.1em] mb-1">TOTAL GROSS PAYOUT</div><div className="text-xl font-bold text-gray-900 font-mono">{currency} {finNum(totalGross)}</div></div>
            </div>
            <div className="border rounded-lg overflow-x-auto">
              <table className="w-full min-w-[820px]">
                <thead className="bg-gray-50"><tr>
                  <th className="min-w-[200px] text-left text-[12px] font-bold text-gray-500 uppercase py-3 px-4">{mode === 'admin' ? 'Expert' : 'Hub'}</th>
                  <th className="text-left text-[12px] font-bold text-gray-500 uppercase py-3 px-4">Bank Account</th>
                  <th className="text-right text-[12px] font-bold text-gray-500 uppercase py-3 px-4">Gross Amount</th>
                  <th className="w-[120px] text-left text-[12px] font-bold text-gray-500 uppercase py-3 px-4">Hub Fee (%)</th>
                  <th className="text-right text-[12px] font-bold text-gray-500 uppercase py-3 px-4">Fee Amount</th>
                  <th className="text-right text-[12px] font-bold text-gray-500 uppercase py-3 px-4">Net Payout</th>
                  <th className="w-[100px]"></th>
                </tr></thead>
                <tbody>
                  {bulkItems.map(item => {
                    const id = mode === 'admin' ? item.id : item.hubId;
                    const g = item.balance; const feeP = bulkFees[id] || 0; const fee = (g * feeP) / 100; const net = g - fee;
                    let def; if (mode === 'admin') def = item.cards.find(c => c.isDefault) || item.cards[0]; else def = FIN_BANK_ACCOUNTS.find(c => c.id === expertBulkCards[id]) || FIN_BANK_ACCOUNTS[0];
                    return (
                      <tr key={id} className="border-t border-gray-100">
                        <td className="py-3 px-4">{mode === 'admin' ? <div className="flex items-center gap-2"><FAvatar fallback={item.name.charAt(0)} className="w-8 h-8 rounded-full" /><div><div className="font-medium text-sm leading-tight">{item.name}</div><div className="text-[12px] text-gray-500">{item.email}</div></div></div> : <div className="flex items-center gap-2"><div className="p-1.5 bg-gray-100 rounded"><FIcon name="building2" size={14} className="text-gray-500" /></div><div className="font-medium text-sm">{item.hubName}</div></div>}</td>
                        <td className="py-3 px-4">{mode === 'admin' ? (def ? <div className="text-[12px] text-gray-600"><div className="font-medium">{def.bankName}</div><div className="text-gray-400">•••• {def.last4}</div></div> : <span className="text-[12px] text-red-500 font-medium">No Bank Account</span>) : <FSelect className="w-[180px]" value={expertBulkCards[id]} onValueChange={v => setExpertBulkCards(p => ({ ...p, [id]: v }))} triggerClassName="h-8 text-[12px]" options={FIN_BANK_ACCOUNTS.map(c => ({ value: c.id, label: `${c.bankName} •••• ${c.last4}` }))} />}</td>
                        <td className="text-right font-mono text-sm py-3 px-4">{currency} {g.toFixed(2)}</td>
                        <td className="py-3 px-4"><div className="relative"><input type="number" min="0" max="100" value={bulkFees[id] || 0} disabled={mode === 'expert'} onChange={e => setBulkFees(p => ({ ...p, [id]: Math.min(100, Math.max(0, parseFloat(e.target.value) || 0)) }))} className={`h-8 w-full rounded-md border border-gray-200 px-3 pr-6 text-right text-xs font-bold focus:outline-none focus:border-black ${mode === 'expert' ? 'bg-gray-50' : 'bg-white'}`} /><span className="absolute right-2 top-1/2 -translate-y-1/2 text-[11px] text-gray-400 font-bold">%</span></div></td>
                        <td className="text-right font-mono text-sm text-red-500 py-3 px-4">- {currency} {fee.toFixed(2)}</td>
                        <td className="text-right font-mono font-bold text-green-600 text-sm py-3 px-4">{currency} {net.toFixed(2)}</td>
                        <td className="py-3 px-4"><button className="h-9 px-4 text-xs font-bold gap-1 rounded-full hover:bg-black hover:text-white transition-all disabled:opacity-40" onClick={() => handleWithdrawClick(item)} disabled={!def}>Withdraw</button></td>
                      </tr>
                    );
                  })}
                </tbody>
                <tfoot className="bg-gray-50/50"><tr>
                  <td colSpan={2} className="text-sm font-bold text-gray-900 px-6 py-5 uppercase tracking-[0.05em]">Total ({bulkItems.length} Items)</td>
                  <td className="text-right font-bold text-gray-900 text-sm py-5 px-4 font-mono">{currency} {finNum(totalGross)}</td>
                  <td className="text-center text-[11px] text-gray-400 font-bold py-5">Avg: {totalGross > 0 ? ((totalFee / totalGross) * 100).toFixed(1) : '0.0'}%</td>
                  <td className="text-right text-red-600 font-bold text-sm py-5 px-4 font-mono">- {currency} {finNum(totalFee)}</td>
                  <td className="text-right text-green-700 text-lg font-bold py-5 px-4 font-mono" colSpan={2}>{currency} {finNum(totalNet)}</td>
                </tr></tfoot>
              </table>
            </div>
            <div className="flex items-start gap-4 bg-amber-50/40 p-5 rounded-xl text-amber-900 text-sm border border-amber-100/50"><FIcon name="alertCircle" size={20} className="mt-0.5 flex-shrink-0 text-amber-600" /><p className="leading-relaxed font-medium">Funds will be transferred to the selected bank accounts. Please verify all net payout amounts before confirming.</p></div>
          </div>
          <div className="p-6 pt-2 border-t bg-gray-50/50 flex justify-end gap-2"><button className="h-11 px-6 font-bold rounded-full border border-gray-200 hover:bg-white" onClick={() => setIsBulkOpen(false)}>Cancel</button><button onClick={() => { setIsBulkOpen(false); finToast.success('Bulk payout confirmed', { description: `${currency} ${finNum(totalNet)} across ${bulkItems.length} payouts.` }); }} className="h-11 px-6 bg-black hover:bg-gray-800 text-white font-bold rounded-full">Confirm Bulk Payout</button></div>
        </div>
      </FModal>
    </div>
  );
}

/* ===================== Host (inside dashboard shell) ===================== */
function FinanceDashPage() {
  const [view, setView] = useState('finance'); // finance | withdraw | all-transactions
  const [withdrawMode, setWithdrawMode] = useState('admin');
  const currency = 'RM';
  const goWithdraw = (m) => { setWithdrawMode(m); setView('withdraw'); };

  return (
    <DashShell active="/app/dashboard/finance">
      {view !== 'withdraw' && (
        <div className="flex justify-end mb-6">
          <div className="inline-flex items-center bg-gray-100 rounded-full p-1">
            <button onClick={() => setView('finance')} className={`px-4 h-9 rounded-full text-sm font-bold transition-colors ${view === 'finance' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}>Hub Finances</button>
            <button onClick={() => setView('all-transactions')} className={`px-4 h-9 rounded-full text-sm font-bold transition-colors ${view === 'all-transactions' ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}>Expert Finances</button>
          </div>
        </div>
      )}
      {view === 'finance' && <FinHubFinances currency={currency} onNavigateToWithdraw={() => goWithdraw('admin')} />}
      {view === 'all-transactions' && <FinAllTransactions currency={currency} onNavigateToWithdraw={() => goWithdraw('expert')} />}
      {view === 'withdraw' && <FinWithdraw currency={currency} mode={withdrawMode} onBack={() => setView(withdrawMode === 'expert' ? 'all-transactions' : 'finance')} />}
    </DashShell>
  );
}

Object.assign(window, { FinAllTransactions, FinWithdraw, FinanceDashPage });
