/* ========== Finance: Income & Expenses ========== */
function FinanceView({ onNav }) {
  const state = useStore();
  const [tab, setTab] = useState('all');
  const [showNew, setShowNew] = useState(null); // 'income' | 'expense' | null
  const [editing, setEditing] = useState(null); // {kind, item}

  // Build unified ledger
  const entries = useMemo(() => {
    const a = state.income.map(i => ({ ...i, kind: 'income' }));
    const b = state.expenses.map(e => ({ ...e, kind: 'expense' }));
    return [...a, ...b].sort((x,y) => y.date - x.date);
  }, [state.income, state.expenses]);

  const shown = entries.filter(e => tab === 'all' ? true : e.kind === tab);

  // Monthly totals
  const now = new Date();
  const mStart = new Date(now.getFullYear(), now.getMonth(), 1).getTime();
  const incUsd = state.income.filter(i => i.date >= mStart && i.currency === 'USD').reduce((s,i)=>s+i.amount, 0);
  const incLak = state.income.filter(i => i.date >= mStart && i.currency === 'LAK').reduce((s,i)=>s+i.amount, 0);
  const expUsd = state.expenses.filter(e => e.date >= mStart && e.currency === 'USD').reduce((s,e)=>s+e.amount, 0);
  const expLak = state.expenses.filter(e => e.date >= mStart && e.currency === 'LAK').reduce((s,e)=>s+e.amount, 0);

  return (
    <div>
      <div className="kpi-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
        <div className="kpi accent-green">
          <div className="kpi-label">Income this month</div>
          <div className="kpi-value">{fmtMoney(incUsd, 'USD')}</div>
          {incLak > 0 && <div className="kpi-sub">+ {fmtMoney(incLak, 'LAK')}</div>}
        </div>
        <div className="kpi accent-red">
          <div className="kpi-label">Expenses this month</div>
          <div className="kpi-value">{fmtMoney(expUsd, 'USD')}</div>
          {expLak > 0 && <div className="kpi-sub">+ {fmtMoney(expLak, 'LAK')}</div>}
        </div>
        <div className="kpi accent">
          <div className="kpi-label">Net this month</div>
          <div className="kpi-value" style={{ color: (incUsd-expUsd) >= 0 ? 'var(--green-600)' : 'var(--red-600)' }}>
            {fmtMoney(incUsd-expUsd, 'USD')}
          </div>
          {(incLak || expLak) > 0 && <div className="kpi-sub">+ {fmtMoney(incLak-expLak, 'LAK')}</div>}
        </div>
      </div>

      <div className="toolbar">
        <div className="filters">
          <button className={`btn ${tab==='all' ? 'primary' : ''}`} onClick={()=>setTab('all')}>All</button>
          <button className={`btn ${tab==='income' ? 'primary' : ''}`} onClick={()=>setTab('income')}>Income</button>
          <button className={`btn ${tab==='expense' ? 'primary' : ''}`} onClick={()=>setTab('expense')}>Expenses</button>
        </div>
        <div className="spacer"/>
        <button className="btn" onClick={() => setShowNew('expense')}>
          <Icon name="plus" size={14}/> Expense
        </button>
        <button className="btn primary" onClick={() => setShowNew('income')}>
          <Icon name="plus" size={14}/> Income
        </button>
      </div>

      <div className="card">
        {shown.length === 0 ? (
          <div className="empty"><h4>No entries</h4><p>Add your first {tab === 'expense' ? 'expense' : 'income'} entry.</p></div>
        ) : (
          <table className="tbl">
            <thead>
              <tr>
                <th>Date</th>
                <th>Type</th>
                <th>Category / Source</th>
                <th>Order</th>
                <th>Vendor / Method</th>
                <th>Note</th>
                <th className="num">Amount</th>
                <th style={{ width: 40 }}></th>
              </tr>
            </thead>
            <tbody>
              {shown.map(e => {
                const order = e.orderId ? state.orders.find(o => o.id === e.orderId) : null;
                return (
                  <tr key={e.kind + e.id} className="clickable" onClick={() => setEditing({ kind: e.kind, item: e })}>
                    <td>{fmtDateShort(e.date)}</td>
                    <td>
                      <span className={`badge ${e.kind === 'income' ? 'green' : 'red'}`}>
                        <span className="dot"/>{e.kind === 'income' ? 'Income' : 'Expense'}
                      </span>
                    </td>
                    <td><b>{e.kind === 'income' ? e.source : e.category}</b></td>
                    <td>
                      {order ? (
                        <a onClick={(ev) => { ev.stopPropagation(); onNav('orders', { orderId: order.id }); }} style={{ color: 'var(--navy-700)', cursor: 'pointer' }}>
                          <span className="order-num">{order.orderNo}</span>
                        </a>
                      ) : <span className="dim">—</span>}
                    </td>
                    <td>{e.vendor || e.method || <span className="dim">—</span>}</td>
                    <td style={{ fontSize: 12, color: 'var(--ink-500)', maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.note || '—'}</td>
                    <td className="num"><b style={{ color: e.kind === 'income' ? 'var(--green-600)' : 'var(--red-600)' }}>{e.kind === 'income' ? '+' : '−'} {fmtMoney(e.amount, e.currency)}</b></td>
                    <td>
                      <button className="btn ghost icon" onClick={(ev) => {
                        ev.stopPropagation();
                        if (confirm('Delete this entry?')) {
                          if (e.kind === 'income') window.PVStore.deleteIncome(e.id);
                          else window.PVStore.deleteExpense(e.id);
                        }
                      }}><Icon name="trash" size={13}/></button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      {showNew && (
        <FinanceModal
          kind={showNew}
          onClose={() => setShowNew(null)}
          onSaved={() => setShowNew(null)}
        />
      )}
      {editing && (
        <FinanceModal
          kind={editing.kind}
          item={editing.item}
          onClose={() => setEditing(null)}
          onSaved={() => setEditing(null)}
        />
      )}
    </div>
  );
}

function FinanceModal({ kind, item, onClose, onSaved }) {
  const state = useStore();
  const isIncome = kind === 'income';
  const [form, setForm] = useState(() => ({
    dateStr: item ? new Date(item.date).toISOString().slice(0,10) : new Date().toISOString().slice(0,10),
    source: item?.source || (isIncome ? 'Service fee' : ''),
    category: item?.category || (isIncome ? '' : 'Embassy fee'),
    orderId: item?.orderId || '',
    currency: item?.currency || 'USD',
    amount: item?.amount || '',
    method: item?.method || 'BCEL Transfer',
    vendor: item?.vendor || '',
    note: item?.note || '',
  }));

  const incomeSources = ['Service fee', 'Invoice payment', 'Translation fee', 'Consulting fee', 'Refund received', 'Other'];
  const expenseCategories = ['Embassy fee', 'Translation fee', 'Courier', 'Office supplies', 'Rent', 'Salary', 'Travel', 'Notary', 'Bank fee', 'Other'];

  const handleSave = () => {
    if (!form.amount || isNaN(parseFloat(form.amount))) { alert('Enter amount'); return; }
    const payload = {
      date: new Date(form.dateStr).getTime(),
      currency: form.currency,
      amount: parseFloat(form.amount),
      orderId: form.orderId || null,
      note: form.note,
      ...(isIncome
        ? { source: form.source, method: form.method }
        : { category: form.category, vendor: form.vendor }
      ),
    };
    if (item) {
      isIncome ? window.PVStore.updateIncome(item.id, payload) : window.PVStore.updateExpense(item.id, payload);
    } else {
      isIncome ? window.PVStore.addIncome(payload) : window.PVStore.addExpense(payload);
    }
    onSaved && onSaved();
  };

  return (
    <Modal
      open
      onClose={onClose}
      title={(item ? 'Edit ' : 'Add ') + (isIncome ? 'income' : 'expense')}
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={handleSave}>{item ? 'Save' : 'Add entry'}</button>
      </>}
    >
      <div className="row-gap">
        <div className="form-row two">
          <div className="field">
            <label>Date</label>
            <input type="date" value={form.dateStr} onChange={e=>setForm({...form, dateStr: e.target.value})}/>
          </div>
          <div className="field">
            <label>{isIncome ? 'Source' : 'Category'}</label>
            <select
              value={isIncome ? form.source : form.category}
              onChange={e => setForm(f => isIncome ? {...f, source: e.target.value} : {...f, category: e.target.value})}
            >
              {(isIncome ? incomeSources : expenseCategories).map(s => <option key={s} value={s}>{s}</option>)}
            </select>
          </div>
        </div>
        <div className="form-row two">
          <div className="field">
            <label>Amount</label>
            <input type="number" step="0.01" value={form.amount} onChange={e=>setForm({...form, amount: e.target.value})}/>
          </div>
          <div className="field">
            <label>Currency</label>
            <select value={form.currency} onChange={e=>setForm({...form, currency: e.target.value})}>
              <option value="USD">USD ($)</option>
              <option value="LAK">LAK (₭)</option>
              <option value="THB">THB (฿)</option>
            </select>
          </div>
        </div>
        <div className="form-row two">
          <div className="field">
            <label>Link to order (optional)</label>
            <select value={form.orderId} onChange={e=>setForm({...form, orderId: e.target.value})}>
              <option value="">— None —</option>
              {state.orders.map(o => <option key={o.id} value={o.id}>{o.orderNo} · {customerName(o.customerId)} · {o.title}</option>)}
            </select>
          </div>
          <div className="field">
            <label>{isIncome ? 'Payment method' : 'Vendor'}</label>
            <input
              value={isIncome ? form.method : form.vendor}
              onChange={e => setForm(f => isIncome ? {...f, method: e.target.value} : {...f, vendor: e.target.value})}
              placeholder={isIncome ? 'BCEL Transfer / Cash / …' : 'Vendor name'}
            />
          </div>
        </div>
        <div className="field">
          <label>Note</label>
          <textarea value={form.note} onChange={e=>setForm({...form, note: e.target.value})} rows="2"/>
        </div>
      </div>
    </Modal>
  );
}

window.FinanceView = FinanceView;
