/* Mereka v2 — Finance (Hub Finances) — faithful port of FinancePage.tsx + AllTransactionsPage.tsx.
   Rendered inside the dashboard shell; navbar intentionally NOT copied from the Figma. */

/* ===================== Transactions table ===================== */
function FinTransactionsTable({ transactions, onRowClick, currency }) {
  if (transactions.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mb-4">
          <FIcon name="fileText" size={24} className="text-gray-400" />
        </div>
        <h3 className="text-lg font-medium text-gray-900 mb-1">No transactions yet</h3>
        <p className="text-gray-500 max-w-sm">Transactions will appear here once you start receiving payments or make withdrawals.</p>
      </div>
    );
  }
  const cols = 'grid grid-cols-1 lg:grid-cols-[1.2fr_1.5fr_2.5fr_1.8fr_1.2fr_1.5fr_1.2fr] gap-4';
  return (
    <div className="w-full">
      <div className={`${cols} px-8 py-4 bg-gray-50/50 items-center`}>
        {['Date', 'Type', 'Description', 'Vendor', 'Gross', 'Net (paid)', 'Status'].map(h => (
          <div key={h} className="text-[13px] font-semibold text-gray-900">{h}</div>
        ))}
      </div>
      <div className="divide-y divide-gray-100">
        {transactions.map(t => (
          <div key={t.id} onClick={() => onRowClick(t)}
            className={`${cols} px-8 py-6 items-start cursor-pointer hover:bg-gray-50/30 transition-colors group`}>
            <div className="text-[14px] text-gray-900 font-medium pt-0.5">{finDate(t.date)}</div>
            <div className="flex flex-col gap-1">
              <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] font-medium text-gray-600">{t.subType || 'Jobs'}</span>
            </div>
            <div className="flex flex-col gap-1">
              <span className="text-[14px] font-bold text-gray-900 leading-tight">{t.description}</span>
              {t.subDescription && <span className="text-[12px] text-gray-500">{t.subDescription}</span>}
            </div>
            <div className="flex items-center gap-2.5">
              <FAvatar src={t.vendorAvatar} fallback={t.vendor ? t.vendor.substring(0, 2).toUpperCase() : 'ME'} className="w-8 h-8 rounded-lg border border-gray-100" />
              <div className="flex flex-col">
                <span className="text-[14px] font-bold text-gray-900">{t.vendor || 'Mereka'}</span>
                {t.vendorSub && <span className="text-[12px] text-gray-500">{t.vendorSub}</span>}
              </div>
            </div>
            <div className="text-[14px] font-semibold text-gray-900 pt-0.5">{currency} {finNum(t.gross != null ? t.gross : t.amount)}</div>
            <div className="flex flex-col pt-0.5">
              <span className="text-[14px] font-semibold text-gray-900">{currency} {finNum(t.net != null ? t.net : t.amount * 0.98)}</span>
              <span className="text-[12px] text-gray-400 font-medium">Fees: -{currency} {finNum(t.fees != null ? t.fees : t.amount * 0.02)}</span>
            </div>
            <div className="pt-0.5">
              <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' ? 'COMPLETED' : t.status.toUpperCase())}
                {t.status === 'on hold' && <FIcon name="alertCircle" size={13} />}
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ===================== Transaction detail dialog (with payout split) ===================== */
function FinTransactionDetail({ transaction, onClose, currency = 'RM', onWithdraw, onConfirmSplit }) {
  const [isProcessing, setIsProcessing] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const displayAmount = Math.abs(transaction.gross || transaction.amount || 0);
  const transactionFees = transaction.fees || transaction.fee || 0;
  const netAmount = transaction.net || (displayAmount - transactionFees);

  const [expertSplits, setExpertSplits] = useState({ e1: 70, e2: 20 });
  const hubSplit = 100 - Object.values(expertSplits).reduce((a, b) => a + b, 0);
  const experts = [
    { id: 'e1', name: transaction.vendorSub || transaction.vendor || 'Sarah Chen', role: 'Primary Expert', avatar: transaction.vendorAvatar },
    { id: 'e2', name: 'Alex Rivera', role: 'Support Expert', avatar: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=100&h=100&fit=crop' },
  ];
  const handleUpdateSplit = (id, val) => {
    const num = parseInt(val) || 0;
    setExpertSplits(prev => {
      const other = Object.entries(prev).filter(([k]) => k !== id).reduce((s, [, v]) => s + v, 0);
      return { ...prev, [id]: Math.min(num, 100 - other) };
    });
  };
  const handleProcessWithdraw = () => {
    setIsProcessing(true);
    setTimeout(() => { setIsProcessing(false); setIsSuccess(true); if (onConfirmSplit) onConfirmSplit(netAmount); }, 2000);
  };
  const handleDownloadReceipt = () => {
    const c = `MEREKA FINANCE - TRANSACTION RECEIPT\n------------------------------------\nTransaction ID: ${transaction.id_long || transaction.id}\nDate: ${new Date(transaction.date).toLocaleDateString()}\nDescription: ${transaction.description}\nVendor: ${transaction.vendor || 'Mereka'}\nGross Amount: ${currency} ${displayAmount.toLocaleString()}\nFees: ${currency} ${transactionFees.toLocaleString()}\nNet Amount: ${currency} ${netAmount.toLocaleString()}\nStatus: ${transaction.status.toUpperCase()}\n------------------------------------\nGenerated on: ${new Date().toLocaleString()}`;
    const blob = new Blob([c], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = `receipt-${transaction.id}.txt`;
    document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url);
    finToast.success('Receipt downloaded successfully');
  };
  const handleGetHelp = () => finToast('Support request received', { description: "We've notified the team about this transaction. You'll receive an update via email shortly.", duration: 5000 });

  const isEarning = transaction.type === 'earning';
  const isWithdrawal = transaction.type === 'withdrawal';
  const isExpense = transaction.type === 'expense';
  const isRefund = transaction.mainType === 'REFUND';
  const statusColor = transaction.status === 'succeeded' ? 'text-green-600' : transaction.status === 'failed' ? 'text-red-600' : 'text-yellow-600';
  const statusBg = transaction.status === 'succeeded' ? 'bg-green-50' : transaction.status === 'failed' ? 'bg-red-50' : 'bg-yellow-50';
  const canWithdraw = isExpense && (transaction.status === 'completed' || transaction.status === 'succeeded') && !isRefund;
  const canReleasePayment = isEarning && !isRefund && (transaction.status === 'completed' || transaction.status === 'succeeded');

  if (isSuccess) {
    return (
      <div className="p-12 flex flex-col items-center text-center space-y-6">
        <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center text-green-600"><FIcon name="checkCircle2" size={40} /></div>
        <div className="space-y-2">
          <h2 className="text-2xl font-bold text-gray-900">Withdrawal Successful</h2>
          <p className="text-gray-500 text-sm leading-relaxed">The payouts have been processed according to the defined percentage split.</p>
        </div>
        <div className="w-full bg-gray-50 rounded-xl p-4 space-y-3 text-left">
          <div className="flex justify-between text-xs border-b border-gray-100 pb-2"><span className="text-gray-500">Transaction ID</span><span className="font-mono text-gray-900">{transaction.id}</span></div>
          {experts.map(e => (
            <div key={e.id} className="flex justify-between text-xs"><span className="text-gray-500">{e.name} ({expertSplits[e.id]}%)</span><span className="text-gray-900 font-bold">{currency} {finNum((netAmount * expertSplits[e.id]) / 100)}</span></div>
          ))}
          <div className="flex justify-between text-xs"><span className="text-gray-500">Hub Commission ({hubSplit}%)</span><span className="text-gray-900 font-bold">{currency} {finNum((netAmount * hubSplit) / 100)}</span></div>
        </div>
        <button className="w-full h-12 bg-black text-white rounded-full font-bold hover:bg-gray-800" onClick={onClose}>Done</button>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-[90vh] max-h-[800px]">
      <div className="p-6 pb-4">
        <button className="mb-6 -ml-2 text-gray-500 hover:text-gray-900 inline-flex items-center gap-1 rounded-full px-4 h-11 font-bold hover:bg-gray-100 transition-all" onClick={onClose}>
          <FIcon name="arrowLeft" size={20} /> Back to Transactions
        </button>
        <div className="flex items-center gap-3 mb-1">
          <h2 className="text-3xl font-bold text-gray-900">{(transaction.gross || transaction.amount || 0) < 0 ? '-' : ''}{currency} {finNum(displayAmount)}</h2>
          <span className={`${statusBg} ${statusColor} border-none uppercase text-[11px] px-2 h-5 inline-flex items-center rounded font-bold`}>{transaction.status === 'pending' ? 'ON HOLD' : transaction.status}</span>
        </div>
        <div className="text-xs text-gray-400 font-medium">{finDate(transaction.date, { day: '2-digit', month: 'short', year: 'numeric' })}, {new Date(transaction.date).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false })} • {transaction.id_long || transaction.id}</div>
      </div>
      <div className="h-px bg-gray-100" />
      <div className="flex-1 overflow-y-auto p-6 space-y-8 scrollbar-thin">
        <div className="space-y-4">
          <h3 className="font-bold text-gray-900 leading-tight pr-4">{transaction.description}</h3>
          <div className="flex items-start gap-8 flex-wrap">
            {(isEarning || isExpense) && (
              <div className="space-y-1">
                <div className={`text-[11px] font-bold uppercase flex items-center gap-1 ${isEarning ? 'text-green-600' : 'text-red-600'}`}>{isEarning ? 'EARNING' : 'SPENDING'} <FIcon name={isEarning ? 'arrowUpRight' : 'arrowDownRight'} size={10} /></div>
                <div className="flex items-center gap-2"><div className="text-xs font-semibold text-gray-900">{transaction.subType}</div>{isRefund && <span className="text-[11px] font-bold uppercase bg-orange-50 text-orange-700 h-4 inline-flex items-center px-1.5 rounded">Refund</span>}</div>
              </div>
            )}
            {isWithdrawal && (
              <div className="space-y-4 w-full">
                <div className="text-[11px] font-bold text-gray-500 uppercase tracking-wider">WITHDRAWAL DETAILS</div>
                <div className="bg-blue-50/50 border border-blue-100 rounded-xl p-4 space-y-3">
                  <div className="flex justify-between items-center text-xs"><span className="text-gray-500">Source</span><span className="text-gray-900 font-medium flex items-center gap-1.5"><FIcon name="wallet" size={14} className="text-blue-600" /> Hub Balance</span></div>
                  <div className="flex justify-between items-center text-xs"><span className="text-gray-500">Destination</span><span className="text-gray-900 font-medium flex items-center gap-1.5"><FIcon name="creditCard" size={14} className="text-blue-600" /> {transaction.destination || 'Stripe Payout to Bank'}</span></div>
                  <div className="flex justify-between items-center text-xs"><span className="text-gray-500">Processing Method</span><span className="text-gray-900 font-medium">Standard Payout (1-3 days)</span></div>
                </div>
              </div>
            )}
            {(isEarning || isExpense) && (
              <div className="flex items-center gap-3">
                <FAvatar fallback={isEarning ? 'DE' : 'AW'} className="w-8 h-8 rounded-lg border" />
                <div><div className="text-[12px] font-bold text-gray-900">{isEarning ? 'Deloitte' : (transaction.vendor || 'Mereka')}</div><div className="text-[11px] text-gray-500">{isEarning ? (transaction.clientExpert || 'Client') : 'Monthly Billing'}</div></div>
              </div>
            )}
          </div>
        </div>

        {(isEarning || isExpense) && (transaction.status === 'completed' || transaction.status === 'succeeded') && (
          <div className="space-y-4">
            <div className="flex items-center justify-between"><h4 className="text-[11px] font-bold text-gray-400 uppercase tracking-wider">Define Payout Split</h4><div className="text-[11px] font-bold text-gray-400">TOTAL: {currency} {finNum(netAmount)}</div></div>
            <div className="space-y-3">
              {experts.map(expert => (
                <div key={expert.id} className="bg-white border rounded-xl p-3 flex items-center justify-between transition-all hover:border-gray-300">
                  <div className="flex items-center gap-3">
                    <FAvatar src={expert.avatar} fallback={expert.name.charAt(0)} className="w-8 h-8 border rounded-full" />
                    <div><div className="text-xs font-bold text-gray-900">{expert.name}</div><div className="text-[11px] text-gray-500">{expert.role}</div></div>
                  </div>
                  <div className="flex items-center gap-3">
                    <div className="text-right"><div className="text-[11px] font-bold text-gray-400 uppercase">Payout</div><div className="text-[12px] font-bold text-black">{currency} {finNum((netAmount * expertSplits[expert.id]) / 100)}</div></div>
                    <div className="relative w-16">
                      <input type="number" className="h-8 w-full pr-5 pl-2 text-xs font-bold text-right rounded-lg bg-gray-50 border border-gray-100 focus:outline-none focus:border-gray-300" value={expertSplits[expert.id]} onChange={e => handleUpdateSplit(expert.id, e.target.value)} />
                      <span className="absolute right-2 top-1/2 -translate-y-1/2 text-[11px] font-bold text-gray-400">%</span>
                    </div>
                  </div>
                </div>
              ))}
              <div className="bg-gray-50 border border-dashed rounded-xl p-3 flex items-center justify-between">
                <div className="flex items-center gap-3"><div className="w-8 h-8 bg-white border rounded-lg flex items-center justify-center"><FIcon name="building2" size={16} className="text-gray-400" /></div><div><div className="text-xs font-bold text-gray-900">Hub Commission</div><div className="text-[11px] text-gray-500">Remaining Balance</div></div></div>
                <div className="text-right flex items-center gap-4"><div className="text-right"><div className="text-[11px] font-bold text-gray-400 uppercase">Allocation</div><div className="text-[12px] font-bold text-black">{currency} {finNum((netAmount * hubSplit) / 100)}</div></div><div className="w-16 h-8 flex items-center justify-end px-2 text-xs font-bold text-gray-400 bg-white border border-gray-100 rounded-lg">{hubSplit}%</div></div>
              </div>
            </div>
            {hubSplit < 0 && <div className="bg-red-50 text-red-600 text-[11px] font-bold p-2 rounded-lg text-center flex items-center justify-center gap-2"><FIcon name="alertCircle" size={12} /> Total expert splits cannot exceed 100%</div>}
          </div>
        )}

        <div className="h-px bg-gray-100 opacity-50" />
        <div className="space-y-4">
          <h4 className="text-[11px] font-bold text-gray-400 uppercase tracking-wider">Contract Details</h4>
          <div className="space-y-3 text-[12px]">
            <div className="flex justify-between items-center text-gray-500"><span>Contracted amount</span><span className="text-gray-900 font-medium font-mono">{currency} {finNum(displayAmount)}</span></div>
            {transactionFees > 0 && <div className="flex justify-between items-center text-gray-500"><span>Platform &amp; Service fees</span><span className="text-red-500 font-medium font-mono">-{currency} {finNum(transactionFees)}</span></div>}
            <div className="flex justify-between items-center pt-1 border-t border-gray-50 mt-1"><span className="font-bold text-gray-900">Net Withdrawable</span><span className="font-bold text-gray-900 font-mono text-base">{currency} {finNum(netAmount)}</span></div>
          </div>
        </div>
        <div className="h-px bg-gray-100 opacity-50" />
        <div className="space-y-4 pb-4">
          <h4 className="text-[11px] font-bold text-gray-400 uppercase tracking-wider">Transaction Status</h4>
          <div className="relative pl-6 space-y-6 before:absolute before:left-[11px] before:top-2 before:bottom-2 before:w-px before:bg-gray-100">
            {(transaction.timeline || [
              { label: 'Transaction initiated', status: 'completed', date: finDate(transaction.date) },
              { label: 'Processing payment', status: 'completed', date: finDate(transaction.date) },
              { label: 'Funds received', status: (transaction.status === 'completed' || transaction.status === 'succeeded') ? 'completed' : 'pending', date: (transaction.status === 'completed' || transaction.status === 'succeeded') ? finDate(transaction.date) : 'Expected tomorrow' },
            ]).map((step, idx) => (
              <div key={idx} className="relative">
                <div className={`absolute -left-[20px] top-0.5 w-[11px] h-[11px] rounded-full border-2 bg-white flex items-center justify-center z-10 ${step.status === 'completed' ? 'border-green-500' : step.status === 'failed' ? 'border-red-500' : 'border-yellow-500'}`}>
                  {step.status === 'completed' && <FIcon name="checkCircle2" size={10} className="text-green-500" />}
                  {step.status === 'failed' && <FIcon name="alertCircle" size={10} className="text-red-500" />}
                  {step.status === 'pending' && <FIcon name="clock" size={10} className="text-yellow-500" />}
                </div>
                <div className="space-y-0.5"><div className={`text-[12px] font-bold ${step.status === 'failed' ? 'text-red-600' : 'text-gray-900'}`}>{step.label}</div>{step.date && <div className="text-[11px] text-gray-400">{step.date}</div>}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div className="p-6 pt-4 border-t flex gap-2 bg-white">
        {isProcessing ? (
          <button className="flex-1 bg-black text-white rounded-full h-11 font-bold opacity-50 inline-flex items-center justify-center" disabled><FIcon name="refreshCw" size={16} className="mr-2 animate-spin" /> Processing Payout...</button>
        ) : transaction.status === 'failed' ? (
          <><button className="flex-1 bg-red-600 hover:bg-red-700 text-white rounded-full h-11 font-bold" onClick={handleGetHelp}>Contact Support</button><button className="rounded-full h-11 font-bold text-gray-600 px-4 border hover:bg-gray-50" onClick={handleDownloadReceipt}><FIcon name="download" size={16} /></button></>
        ) : canReleasePayment ? (
          <><button className="flex-1 bg-black hover:bg-gray-800 text-white rounded-full h-11 font-bold gap-2 inline-flex items-center justify-center" onClick={onWithdraw}><FIcon name="refreshCw" size={16} /> Release Payment</button><button className="flex-1 rounded-full h-11 font-bold text-gray-600 border hover:bg-gray-50" onClick={handleGetHelp}>Get help</button></>
        ) : canWithdraw ? (
          <><button className="flex-1 bg-black hover:bg-gray-800 text-white rounded-full h-11 font-bold gap-2 inline-flex items-center justify-center disabled:opacity-50" onClick={handleProcessWithdraw} disabled={hubSplit < 0}><FIcon name="wallet" size={16} /> Confirm Payout Split</button><button className="rounded-full h-11 font-bold text-gray-600 px-4 border hover:bg-gray-50" onClick={handleDownloadReceipt} title="Download Receipt"><FIcon name="download" size={16} /></button><button className="rounded-full h-11 font-bold text-gray-600 px-4 border hover:bg-gray-50" onClick={handleGetHelp} title="Get Help"><FIcon name="helpCircle" size={16} /></button></>
        ) : (
          <><button className="flex-1 bg-black hover:bg-gray-800 text-white rounded-full h-11 font-bold" onClick={isRefund ? handleGetHelp : (isEarning ? handleGetHelp : handleDownloadReceipt)}>{isRefund ? 'View refund details' : isEarning ? 'Contact client' : 'Download receipt'}</button><button className="flex-1 rounded-full h-11 font-bold text-gray-600 border hover:bg-gray-50" onClick={handleGetHelp}>Get help</button></>
        )}
      </div>
    </div>
  );
}

/* ===================== Commission settings dialog ===================== */
function FinCommissionSettings({ onClose }) {
  const [services, setServices] = useState(FIN_SERVICES);
  const [bulk, setBulk] = useState(15);
  const upd = (id, expertSplit) => {
    const v = Math.max(0, Math.min(100, expertSplit));
    setServices(prev => prev.map(s => s.id === id ? { ...s, expertSplit: v, hubSplit: 100 - v } : s));
  };
  return (
    <div className="p-6">
      <div className="mb-2"><h3 className="text-lg font-bold text-gray-900">Commission Settings</h3><p className="text-sm text-gray-500 mt-1">Configure the percentage split between Experts and the Hub for each service type.</p></div>
      <div className="py-4 space-y-6">
        <div className="bg-blue-50 text-blue-800 text-sm p-4 rounded-xl flex items-start gap-3 border border-blue-100"><FIcon name="percent" size={20} className="mt-0.5 text-blue-600 flex-shrink-0" /><div className="leading-relaxed">Commission splits are applied automatically when a transaction is completed. Changes will only apply to future transactions.</div></div>
        <div className="space-y-3">
          <h3 className="text-sm font-bold text-gray-900 px-1 uppercase tracking-wider">Service Category Splits</h3>
          <div className="border border-gray-100 rounded-xl overflow-hidden">
            <table className="w-full">
              <thead className="bg-gray-50/50"><tr className="border-b border-gray-100"><th className="text-left text-[12px] font-bold text-gray-500 uppercase py-3 px-4">Service Type</th><th className="text-left w-[150px] text-[12px] font-bold text-gray-500 uppercase py-3 px-4">Expert Split (%)</th><th className="text-left w-[150px] text-[12px] font-bold text-gray-500 uppercase py-3 px-4">Hub Split (%)</th></tr></thead>
              <tbody>
                {services.map(s => (
                  <tr key={s.id} className="border-b border-gray-100 last:border-0">
                    <td className="font-bold text-gray-900 py-4 px-4">{s.name}</td>
                    <td className="py-4 px-4"><div className="relative"><input type="number" min="0" max="100" value={s.expertSplit} onChange={e => upd(s.id, parseInt(e.target.value) || 0)} className="w-full pr-8 pl-3 h-10 border border-gray-200 rounded-lg font-bold focus:outline-none focus:border-black" /><span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs font-bold">%</span></div></td>
                    <td className="py-4 px-4"><div className="relative"><input type="number" value={s.hubSplit} disabled className="w-full bg-gray-50/50 border border-gray-200 pr-8 pl-3 h-10 rounded-lg text-gray-500 font-bold" /><span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs font-bold">%</span></div></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        <div className="space-y-3 pt-2">
          <h3 className="text-sm font-bold text-gray-900 px-1 uppercase tracking-wider">Withdrawal Settings</h3>
          <div className="border border-gray-100 rounded-xl p-5 bg-gray-50/30 flex items-center justify-between gap-6">
            <div className="space-y-1 flex-1"><p className="text-[14px] font-bold text-gray-900">Default Hub Commission for Bulk Withdrawal</p><p className="text-[12px] text-gray-500 leading-relaxed">This fixed percentage is applied as a platform fee when experts perform a consolidated withdrawal across multiple earnings.</p></div>
            <div className="w-[150px] shrink-0"><div className="relative"><input type="number" min="0" max="100" value={bulk} onChange={e => setBulk(Math.max(0, Math.min(100, parseInt(e.target.value) || 0)))} className="w-full pr-8 pl-3 h-11 border border-gray-200 rounded-lg font-bold bg-white focus:outline-none focus:border-black" /><span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs font-bold">%</span></div></div>
          </div>
        </div>
      </div>
      <div className="flex justify-end gap-2 pt-2">
        <button onClick={onClose} className="h-11 px-8 font-bold rounded-full border border-gray-200 hover:bg-gray-50 text-gray-600">Cancel</button>
        <button onClick={() => { finToast.success('Settings saved successfully', { description: 'Commission splits and withdrawal fees have been updated.' }); onClose(); }} className="h-11 px-8 bg-black hover:bg-gray-800 text-white font-bold rounded-full">Save Changes</button>
      </div>
    </div>
  );
}

/* ===================== Hub Finances page ===================== */
function FinHubFinances({ onNavigateToWithdraw, currency = 'RM' }) {
  const [selectedHub, setSelectedHub] = useState(FIN_HUBS[0].id);
  const [searchQuery, setSearchQuery] = useState('');
  const [banks, setBanks] = useState(FIN_BANK_ACCOUNTS);
  const [isAddBankOpen, setIsAddBankOpen] = useState(false);
  const [isEditBankOpen, setIsEditBankOpen] = useState(false);
  const [selectedBank, setSelectedBank] = useState(null);
  const [isCommissionOpen, setIsCommissionOpen] = useState(false);
  const [selectedTransaction, setSelectedTransaction] = useState(null);
  const [localAvailable, setLocalAvailable] = useState(null);
  const [editIsDefault, setEditIsDefault] = useState(false);
  const [txTab, setTxTab] = useState('all');

  const setDefault = (id) => { setBanks(prev => prev.map(a => ({ ...a, isDefault: a.id === id }))); finToast.success('Default bank account updated'); };
  const removeBank = (id) => { setBanks(prev => { const n = prev.filter(a => a.id !== id); if (n.length && !n.some(a => a.isDefault)) n[0].isDefault = true; return n; }); finToast.success('Bank account removed'); };

  const filtered = FIN_TRANSACTIONS.filter(t => t.hubId === selectedHub && t.description.toLowerCase().includes(searchQuery.toLowerCase()));
  const currentHubName = FIN_HUBS.find(h => h.id === selectedHub)?.name;
  const teamMembers = Array.from(new Set(FIN_TRANSACTIONS.map(t => t.vendor || t.vendorSub).filter(Boolean)));
  const availableBalance = localAvailable != null ? localAvailable : filtered.filter(t => t.status === 'completed' || t.status === 'succeeded').reduce((a, c) => a + (c.net || 0), 0);
  const pendingBalance = filtered.filter(t => t.status === 'on hold' || t.status === 'pending').reduce((a, c) => a + (c.gross || 0), 0);
  const defAcc = banks.find(a => a.isDefault);

  const tabbed = txTab === 'all' ? filtered : filtered.filter(t => t.type === (txTab === 'received' ? 'earning' : txTab === 'paidout' ? 'expense' : 'withdrawal'));
  const tabs = [{ v: 'all', l: 'All' }, { v: 'received', l: 'Earnings' }, { v: 'paidout', l: 'Spendings', info: true }, { v: 'withdrawals', l: 'Withdrawals' }];

  const openEdit = (acc) => { setSelectedBank(acc); setEditIsDefault(!!acc.isDefault); setIsEditBankOpen(true); };

  return (
    <div className="space-y-8">
      {/* Header */}
      <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">Finances</h1><p className="text-gray-500 text-sm mt-1">Manage your earnings and transactions for {currentHubName}</p></div>
        <div className="flex items-center gap-2"><span className="text-sm font-medium text-gray-500">Viewing:</span>
          <FSelect className="w-[200px]" triggerClassName="h-11" value={selectedHub} onValueChange={setSelectedHub} leftIcon={<FIcon name="building2" size={16} />} options={FIN_HUBS.map(h => ({ value: h.id, label: h.name }))} />
        </div>
      </div>

      {/* Balance Section */}
      <div className="bg-white border border-gray-200 rounded-xl">
        <div className="p-6 pb-4">
          <div className="flex items-center justify-between flex-wrap gap-3">
            <h2 className="text-base font-semibold">Business Balance</h2>
            <div className="flex gap-2 flex-wrap">
              <button onClick={() => setIsCommissionOpen(true)} 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="settings" size={16} /> Commission Settings</button>
              <button onClick={() => finToast('Opening Stripe Dashboard', { description: 'Redirecting to your Stripe account…' })} className="h-11 px-6 font-bold rounded-full gap-2 inline-flex items-center border border-gray-200 hover:bg-gray-50">Stripe Dashboard <FIcon name="externalLink" size={16} /></button>
              <button onClick={onNavigateToWithdraw} className="h-11 px-6 bg-black hover:bg-gray-800 text-white font-bold rounded-full">Withdraw</button>
            </div>
          </div>
        </div>
        <div className="px-6 pb-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-green-50 border border-green-100 rounded-xl p-4"><div className="text-green-700 text-xs font-semibold uppercase tracking-wide mb-1">Available</div><div className="text-green-800 text-2xl font-bold">{currency} {availableBalance.toFixed(2)}</div></div>
            <div className="bg-orange-50 border border-orange-100 rounded-xl p-4"><div className="text-orange-700 text-xs font-semibold uppercase tracking-wide mb-1">Pending</div><div className="text-orange-800 text-2xl font-bold">{currency} {pendingBalance.toFixed(2)}</div></div>
            <div className="bg-gray-50 border border-gray-100 rounded-xl p-4 flex items-start justify-between group">
              {defAcc ? (
                <div className="flex items-start gap-3"><div className="p-2 bg-white rounded-lg border border-gray-200"><FIcon name="creditCard" size={20} className="text-gray-600" /></div><div><div className="text-gray-500 text-xs font-medium mb-1">Hub Bank Account</div><div className="font-semibold text-gray-900 text-sm">{defAcc.bankName}</div><div className="text-gray-500 text-xs">****{defAcc.last4}</div></div></div>
              ) : (<div className="flex items-center gap-3 text-gray-400 py-2"><FIcon name="alertCircle" size={20} /><span className="text-sm">No default account set</span></div>)}
              <button className="h-8 w-8 grid place-items-center text-gray-400 opacity-0 group-hover:opacity-100 transition-all rounded-full hover:bg-gray-100" onClick={() => { if (defAcc) openEdit(defAcc); }}><FIcon name="pencil" size={14} /></button>
            </div>
          </div>
        </div>
      </div>

      {/* Bank Accounts */}
      <div className="space-y-4">
        <div className="flex items-center justify-between flex-wrap gap-3">
          <div className="flex items-center gap-2"><h2 className="text-lg font-bold text-gray-900">Hub Bank Accounts</h2><span title="These are the bank accounts for the Hub itself. Experts manage their own withdrawal accounts in their personal profiles." className="text-gray-400 cursor-help"><FIcon name="helpCircle" size={16} /></span></div>
          <button onClick={() => setIsAddBankOpen(true)} 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="plus" size={18} /> Add Bank Account</button>
        </div>
        {banks.map(account => (
          <div key={account.id} className="bg-gray-50 border border-gray-100 rounded-xl p-4 flex items-center justify-between group">
            <div className="flex items-center gap-4">
              <div className="p-3 bg-white rounded-lg border border-gray-200"><FIcon name="creditCard" size={24} className="text-gray-600" /></div>
              <div>
                <div className="flex items-center gap-2"><span className="font-bold text-gray-900">{account.bankName}</span>{account.isDefault && <span className="bg-green-100 text-green-700 h-5 inline-flex items-center px-1.5 text-[11px] rounded font-medium">Default</span>}<span className="ml-1 text-[11px] h-5 inline-flex items-center px-1.5 capitalize border border-gray-200 rounded text-gray-600">{account.type || 'business'}</span></div>
                <div className="text-sm text-gray-500">****{account.last4} • {account.holder}</div>
              </div>
            </div>
            <div className="flex items-center gap-2">
              {!account.isDefault && <button className="h-8 px-3 text-[11px] font-bold rounded-full border border-gray-200 hover:bg-gray-100 opacity-0 group-hover:opacity-100 transition-all" onClick={() => setDefault(account.id)}>Make Default</button>}
              <div className="flex items-center gap-1">
                <button className="w-9 h-9 grid place-items-center text-gray-400 hover:text-gray-900 hover:bg-gray-100 rounded-full" onClick={() => openEdit(account)}><FIcon name="pencil" size={16} /></button>
                <button className="w-9 h-9 grid place-items-center text-red-500 hover:text-red-600 hover:bg-red-50 rounded-full" onClick={() => removeBank(account.id)}><FIcon name="trash2" size={16} /></button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Transactions */}
      <div className="bg-white rounded-[24px] overflow-hidden" style={{ boxShadow: '0 4px 30px rgba(0,0,0,0.04)' }}>
        <div className="p-8 pb-0">
          <div className="flex flex-col gap-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-gray-100">
              <div className="flex items-center justify-start gap-10">
                {tabs.map(t => (
                  <button key={t.v} onClick={() => setTxTab(t.v)} className={`p-0 pb-4 h-auto rounded-none text-[15px] font-semibold bg-transparent inline-flex items-center gap-1.5 border-b-2 -mb-px ${txTab === t.v ? 'text-black border-black' : 'text-gray-500 border-transparent'}`}>{t.l}{t.info && <FIcon name="info" size={16} className="text-gray-400" />}</button>
                ))}
              </div>
            </div>
            <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">Transaction type</label><FSelect value="all" onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'all', label: 'All types' }, { value: 'purchase', label: 'Purchase' }, { value: 'refund', label: 'Refund' }]} /></div>
                <div className="space-y-2"><label className="text-[12px] font-medium text-gray-500">Vendor</label><FSelect value="all" onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'all', label: 'All' }, { value: 'lucas', label: 'Lucas Miller' }, { value: 'mereka', label: 'Mereka' }]} /></div>
                <div className="space-y-2"><label className="text-[12px] font-medium text-gray-500">Service</label><FSelect value="all" onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'all', label: 'All services' }, { value: 'fixed', label: 'Fixed Contract' }, { value: 'exp', label: 'Experience' }]} /></div>
              </div>
              <div className="flex items-center gap-3">
                <button onClick={() => finToast('Generating report', { description: 'Your financial report is being prepared with AI insights.' })} className="h-11 px-6 bg-[#F4EBFF] hover:bg-[#E9D7FE] text-[#7F56D9] font-bold rounded-full gap-2 inline-flex items-center">Generate Report <FIcon name="sparkles" size={16} /></button>
                <button onClick={() => finToast.success('CSV exported', { description: 'Your transactions have been exported.' })} className="h-11 px-6 bg-black hover:bg-gray-800 text-white font-bold rounded-full">CSV Export</button>
              </div>
            </div>
          </div>
          <div className="mt-8 -mx-8">
            <FinTransactionsTable transactions={tabbed} onRowClick={setSelectedTransaction} currency={currency} />
          </div>
        </div>
      </div>

      <div className="text-center text-sm text-gray-500 pb-8">View and manage your hub finances. <a href="#" onClick={e => e.preventDefault()} className="text-black font-medium hover:underline">Learn more.</a></div>

      {/* Dialogs */}
      <FModal open={!!selectedTransaction} onClose={() => setSelectedTransaction(null)} panelClassName="max-w-md overflow-hidden">
        {selectedTransaction && <FinTransactionDetail transaction={selectedTransaction} currency={currency} onClose={() => setSelectedTransaction(null)} onWithdraw={() => { setSelectedTransaction(null); onNavigateToWithdraw(); }} onConfirmSplit={(net) => { setLocalAvailable(p => (p != null ? p : availableBalance) - net); finToast.success('Payout Split Confirmed', { description: `${currency} ${net.toLocaleString()} has been moved to payouts.` }); }} />}
      </FModal>

      <FModal open={isCommissionOpen} onClose={() => setIsCommissionOpen(false)} panelClassName="max-w-2xl"><FinCommissionSettings onClose={() => setIsCommissionOpen(false)} /></FModal>

      <FModal open={isAddBankOpen} onClose={() => setIsAddBankOpen(false)} panelClassName="max-w-md">
        <div className="p-6">
          <div className="mb-2"><h3 className="text-lg font-bold">Add Bank Account</h3><p className="text-sm text-gray-500 mt-1">Enter the bank account details.</p></div>
          <div className="space-y-4 py-4">
            <div className="space-y-2"><label className="text-sm font-medium">Account Type</label><FSelect value="business" onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'business', label: 'Hub Business Account' }, { value: 'personal', label: 'Personal / Expert Account' }]} /></div>
            <div className="space-y-2"><label className="text-sm font-medium">Bank Name</label><input placeholder="e.g. Maybank" className="w-full h-11 px-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-gray-400" /></div>
            <div className="space-y-2"><label className="text-sm font-medium">Account Number</label><input placeholder="e.g. 1234567890" className="w-full h-11 px-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-gray-400" /></div>
            <div className="space-y-2"><label className="text-sm font-medium">Account Holder Name</label><FSelect value="hub" onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'hub', label: `Hub: ${currentHubName}` }, ...teamMembers.map(m => ({ value: m, label: m }))]} /></div>
            <button className="w-full h-11 bg-black hover:bg-gray-800 text-white font-bold rounded-full" onClick={() => { setIsAddBankOpen(false); finToast.success('Bank account added'); }}>Save Account</button>
          </div>
        </div>
      </FModal>

      <FModal open={isEditBankOpen} onClose={() => setIsEditBankOpen(false)} panelClassName="max-w-md">
        <div className="p-6">
          <div className="mb-2"><h3 className="text-lg font-bold">Edit Bank Account</h3><p className="text-sm text-gray-500 mt-1">Update the bank account details for {selectedBank?.bankName}.</p></div>
          <div className="space-y-4 py-4">
            <div className="space-y-2"><label className="text-sm font-medium">Account Type</label><FSelect value={selectedBank?.type || 'business'} onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'business', label: 'Hub Business Account' }, { value: 'personal', label: 'Personal / Expert Account' }]} /></div>
            <div className="space-y-2"><label className="text-sm font-medium">Bank Name</label><input defaultValue={selectedBank?.bankName} placeholder="e.g. Maybank" className="w-full h-11 px-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-gray-400" /></div>
            <div className="space-y-2"><label className="text-sm font-medium">Account Number</label><input defaultValue={`****${selectedBank?.last4}`} className="w-full h-11 px-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-gray-400" /></div>
            <div className="space-y-2"><label className="text-sm font-medium">Account Holder Name</label><FSelect value="hub" onValueChange={() => {}} triggerClassName="h-11" options={[{ value: 'hub', label: `Hub: ${currentHubName}` }, ...teamMembers.map(m => ({ value: m, label: m }))]} /></div>
            <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-100"><div className="space-y-0.5"><label className="text-sm font-semibold">Set as Default Account</label><div className="text-[11px] text-gray-500">Use this account for all future withdrawals by default</div></div><FSwitch checked={editIsDefault} onCheckedChange={(c) => { setEditIsDefault(c); if (c && selectedBank) setDefault(selectedBank.id); }} /></div>
            <button className="w-full h-11 bg-black hover:bg-gray-800 text-white font-bold rounded-full" onClick={() => { setIsEditBankOpen(false); finToast.success('Bank account updated'); }}>Save Changes</button>
          </div>
        </div>
      </FModal>
    </div>
  );
}

Object.assign(window, {
  FinTransactionsTable, FinTransactionDetail, FinCommissionSettings, FinHubFinances,
});
