import React, { useEffect, useMemo, useState } from 'react';
import { __ } from '@wordpress/i18n';

const appData = window.manfietExpenseTrackerData || {};

const requestJson = (url, options = {}) => {
    const headers = {
        'Content-Type': 'application/json',
        ...(options.headers || {}),
    };

    if (appData.restNonce) {
        headers['X-WP-Nonce'] = appData.restNonce;
    }

    return fetch(url, {
        credentials: 'same-origin',
        ...options,
        headers,
    }).then(async (response) => {
        const data = await response.json().catch(() => ({}));
        if (!response.ok) {
            throw new Error(data.message || 'Request failed');
        }

        return data;
    });
};

let __campaignIdCounter = Date.now();
const genCampaignId = () => String(__campaignIdCounter++);
const emptyCampaign = () => ({
    id: genCampaignId(),
    name: '',
    daily_budget: '',
    duration: '',
    description: '',
});

const newFormState = () => ({
    id: null,
    invoice_type: 'standard',
    service_type_label: '',
    currency: 'BDT',
    vendor_id: '',
    client_id: '',
    client_name: '',
    invoice_no: '',
    date: new Date().toISOString().slice(0, 10),
    due_date: '',
    late_fee_pct: String(appData.invoiceLateFeePct ?? '5'),
    address: '',
    phone: '',
    email: '',
    email2: '',
    service_desc: '',
    notes: '',
    exchange_rate: '150',
    discount_type: 'percentage',
    discount_val: '0',
    discount_pct: '0',
    vat_pct: '15',
    adjustment_usd: '',
    adjustment_bdt: '',
    adjustment_note: '',
    status: 'pending',
    previous_invoice_id: '',
    previous_invoice_no: '',
    previous_due_amount: '0',
    payment_received_amount: '0',
    payments: [],
    financial_account_ids: [],
    campaigns: [emptyCampaign()],
    share_token: '',
    payment_link: '',
});

const currencySymbols = {
    BDT: '৳',
    USD: '$',
    GBP: '£',
    EUR: '€',
    CAD: 'CA$',
    AUD: 'A$',
    INR: '₹',
    AED: 'AED ',
    SAR: 'SAR ',
    MYR: 'RM ',
    SGD: 'S$',
};

const getCurrencySymbol = (code = 'BDT') => currencySymbols[code] || `${code} `;
const formatMoneyCurrency = (value, code = 'BDT') => `${getCurrencySymbol(code)}${Number(value || 0).toFixed(2)}`;
const formatMoney = (value) => `$${Number(value || 0).toFixed(2)}`;
const formatMoneyBdt = (value) => `৳${Number(value || 0).toFixed(2)}`;

const parseInvoiceDate = (value) => {
    if (!value) {
        return null;
    }

    const parsed = new Date(`${value}T00:00:00`);
    return Number.isNaN(parsed.getTime()) ? null : parsed;
};

const startOfToday = () => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    return now;
};

const getInvoiceDueAmount = (invoice) => Number(invoice.balance_due ?? Math.max(0, Number(invoice.amount_due ?? invoice.totals?.grand_total ?? 0) - Number(invoice.payment_received_amount || 0)));

const getInvoicePaidAmount = (invoice) => Number(invoice.payment_received_amount || 0);

const getInvoiceStatus = (invoice) => String(invoice.status || 'pending').toLowerCase();

const getInvoiceReferenceDate = (invoice) => parseInvoiceDate(invoice.date || invoice.created_at || '');

const startOfDay = (date) => {
    const value = new Date(date);
    value.setHours(0, 0, 0, 0);
    return value;
};

const formatDashboardDate = (date) => {
    if (!date) {
        return '';
    }

    return date.toLocaleDateString(undefined, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
    });
};

const endOfDay = (date) => {
    const value = new Date(date);
    value.setHours(23, 59, 59, 999);
    return value;
};

const shiftMonths = (date, months) => {
    const value = new Date(date);
    value.setMonth(value.getMonth() + months);
    return value;
};

const dashboardRangeOptions = [
    { value: 'this-week', label: __('This week', 'manfi-expense-tracker') },
    { value: 'this-month', label: __('This month', 'manfi-expense-tracker') },
    { value: 'last-month', label: __('Last month', 'manfi-expense-tracker') },
    { value: 'last-6-months', label: __('Last 6 months', 'manfi-expense-tracker') },
    { value: 'last-year', label: __('Last year', 'manfi-expense-tracker') },
    { value: 'custom', label: __('Custom range', 'manfi-expense-tracker') },
];

const getDashboardRange = (rangeKey, customStart, customEnd) => {
    const today = startOfDay(new Date());
    let start = null;
    let end = endOfDay(today);

    switch (rangeKey) {
        case 'this-week': {
            const day = today.getDay();
            start = startOfDay(new Date(today));
            start.setDate(today.getDate() - day);
            break;
        }
        case 'this-month': {
            start = startOfDay(new Date(today.getFullYear(), today.getMonth(), 1));
            break;
        }
        case 'last-month': {
            start = startOfDay(new Date(today.getFullYear(), today.getMonth() - 1, 1));
            end = endOfDay(new Date(today.getFullYear(), today.getMonth(), 0));
            break;
        }
        case 'last-6-months': {
            start = startOfDay(new Date(today.getFullYear(), today.getMonth() - 5, 1));
            break;
        }
        case 'last-year': {
            start = startOfDay(new Date(today.getFullYear() - 1, today.getMonth(), 1));
            break;
        }
        case 'custom': {
            start = customStart ? startOfDay(new Date(`${customStart}T00:00:00`)) : null;
            end = customEnd ? endOfDay(new Date(`${customEnd}T00:00:00`)) : null;
            break;
        }
        default: {
            start = null;
        }
    }

    return { start, end };
};

const calculateCampaignAmount = (campaign, invoiceType = 'standard') => {
    const rate = Number(campaign.daily_budget || 0);
    const isFixed = invoiceType === 'fixed';
    const rawDuration = campaign.duration;

    let duration;
    if (isFixed || rawDuration === '' || rawDuration === null || rawDuration === undefined) {
        duration = 1;
    } else {
        duration = Number(rawDuration);
        if (isNaN(duration)) {
            duration = 1;
        }
    }
    return Number((rate * duration).toFixed(2));
};

const calculateTotals = (form) => {
    const isDailyRate = form.invoice_type === 'daily_rate';
    const exchangeRate = Number(form.exchange_rate || 0);
    const subtotalUsd = form.campaigns.reduce((sum, campaign) => sum + calculateCampaignAmount(campaign, form.invoice_type), 0);
    const discountType = form.discount_type || 'percentage';
    const discountVal = Number(form.discount_val ?? form.discount_pct ?? 0);
    const vatPct = Number(form.vat_pct || 0);
    const previousDueAmount = Number(form.previous_due_amount || 0);
    const paymentReceivedAmount = Number(form.payment_received_amount || 0);
    const adjustmentUsd = Number(form.adjustment_usd || 0);
    const adjustmentBdt = Number(form.adjustment_bdt || 0);

    const subtotalBdt = isDailyRate && exchangeRate > 0 ? subtotalUsd * exchangeRate : subtotalUsd;

    let discountBdt = 0;
    let discountPct = 0;
    if (discountType === 'flat') {
        discountBdt = Math.min(subtotalBdt, Math.max(0, discountVal));
        discountPct = subtotalBdt > 0 ? Number(((discountBdt / subtotalBdt) * 100).toFixed(2)) : 0;
    } else {
        discountPct = Math.max(0, discountVal);
        discountBdt = subtotalBdt * (discountPct / 100);
    }

    const afterDiscount = Math.max(0, subtotalBdt - discountBdt);
    const vatBdt = afterDiscount * (vatPct / 100);
    const grandTotal = afterDiscount + vatBdt + adjustmentBdt;
    const amountDue = grandTotal + previousDueAmount;
    const balanceDue = Math.max(0, amountDue - paymentReceivedAmount);
    const overpaidAmount = Math.max(0, paymentReceivedAmount - amountDue);

    return {
        subtotalUsd,
        subtotalBdt,
        discountType,
        discountVal,
        discountPct,
        discountBdt,
        afterDiscount,
        vatBdt,
        adjustmentUsd,
        adjustmentBdt,
        grandTotal,
        previousDueAmount,
        paymentReceivedAmount,
        amountDue,
        balanceDue,
        overpaidAmount,
    };
};

const derivePaymentStatus = (amountDue, paymentReceived, currentStatus = 'pending') => {
    const normalizedStatus = String(currentStatus || 'pending');
    if (normalizedStatus === 'draft') {
        return normalizedStatus;
    }

    const due = Number(amountDue || 0);
    const received = Number(paymentReceived || 0);

    if (normalizedStatus === 'overdue' && received <= 0) {
        return normalizedStatus;
    }

    if (received <= 0) {
        return 'pending';
    }

    if (received >= due) {
        return 'paid';
    }

    return 'partial';
};

const accountLabel = (account) => {
    if (!account) {
        return '';
    }

    return [account.provider_name, account.account_type, account.account_number].filter(Boolean).join(' - ') || account.title || '';
};

const InvoiceChart = ({ monthly }) => {
    const data = Array.isArray(monthly) ? monthly : [];
    const maxValue = Math.max(...data.map((item) => Number(item.value || 0)), 0);

    if (!data.length || maxValue <= 0) {
        return <p className="manfiet-text-muted">{__('No invoice data available yet.', 'manfi-expense-tracker')}</p>;
    }

    return (
        <div className="manfiet-chart-bars-wrap manfiet-invoice-chart">
            {data.map((item, index) => {
                const value = Number(item.value || 0);
                const widthPercent = Math.max(4, Math.round((value / maxValue) * 100));
                return (
                    <div key={item.label} className="manfiet-bar-item">
                        <div className="manfiet-bar-header">
                            <span>{item.label}</span>
                            <span>{formatMoneyBdt(value)}</span>
                        </div>
                        <div className="manfiet-progress-track manfiet-progress-track-sm">
                            <div
                                className="manfiet-progress-bar"
                                style={{
                                    width: `${widthPercent}%`,
                                    backgroundColor: index % 2 === 0 ? '#2563eb' : '#0ea5e9',
                                }}
                            />
                        </div>
                    </div>
                );
            })}
        </div>
    );
};

const buildAdminPageUrl = (page, invoiceId = '') => {
    const url = new URL(window.location.href);
    url.searchParams.set('page', page);

    if (invoiceId) {
        url.searchParams.set('invoice_id', String(invoiceId));
    } else {
        url.searchParams.delete('invoice_id');
    }

    return url.toString();
};

const InvoiceManager = ({ mode = 'dashboard' }) => {
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';
    const isCreateMode = mode === 'create';
    const [form, setForm] = useState(newFormState());
    const [invoices, setInvoices] = useState([]);
    const [vendors, setVendors] = useState([]);
    const [clients, setClients] = useState([]);
    const [financialAccounts, setFinancialAccounts] = useState([]);
    const [report, setReport] = useState({ summary: { count: 0, total: 0, average: 0 }, monthly: [], status_counts: {} });
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');
    const [message, setMessage] = useState('');
    const [shareUrl, setShareUrl] = useState('');
    const getCurrentLocalDateTime = () => {
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        return now.toISOString().slice(0, 16);
    };

    const [paymentInvoice, setPaymentInvoice] = useState(null);
    const [paymentAmount, setPaymentAmount] = useState('');
    const [paymentDate, setPaymentDate] = useState(getCurrentLocalDateTime());
    const [paymentMethod, setPaymentMethod] = useState('bKash');
    const [customPaymentMethod, setCustomPaymentMethod] = useState('');
    const [transactionId, setTransactionId] = useState('');
    const [paymentNote, setPaymentNote] = useState('');
    const [paymentSaving, setPaymentSaving] = useState(false);
    const [paymentError, setPaymentError] = useState('');
    const [dashboardRange, setDashboardRange] = useState('this-month');
    const [customRangeStart, setCustomRangeStart] = useState('');
    const [customRangeEnd, setCustomRangeEnd] = useState('');

    const closePaymentDialog = () => {
        setPaymentInvoice(null);
        setPaymentAmount('');
        setPaymentDate(getCurrentLocalDateTime());
        setPaymentMethod('bKash');
        setCustomPaymentMethod('');
        setTransactionId('');
        setPaymentNote('');
        setPaymentError('');
    };

    const openPaymentDialog = (invoice) => {
        setPaymentInvoice(invoice);
        setPaymentAmount('');
        setPaymentDate(getCurrentLocalDateTime());
        setPaymentMethod('bKash');
        setCustomPaymentMethod('');
        setTransactionId('');
        setPaymentNote('');
        setPaymentError('');
        setMessage('');
    };

    const submitPayment = () => {
        if (!paymentInvoice) {
            return;
        }

        const receivedAmount = Number(paymentAmount || 0);
        if (Number.isNaN(receivedAmount) || receivedAmount <= 0) {
            setPaymentError(__('Enter a valid payment amount greater than zero.', 'manfi-expense-tracker'));
            return;
        }

        const selectedMethod = paymentMethod === 'Other' ? customPaymentMethod : paymentMethod;

        setPaymentSaving(true);
        requestJson(`${restBase}invoices/${paymentInvoice.id}/payment`, {
            method: 'POST',
            body: JSON.stringify({
                payment_amount: receivedAmount,
                payment_date: paymentDate,
                payment_method: selectedMethod,
                transaction_id: transactionId,
                note: paymentNote,
            }),
        })
            .then((savedInvoice) => {
                setMessage(__('Payment recorded successfully.', 'manfi-expense-tracker'));
                setPaymentInvoice(savedInvoice);
                setPaymentAmount('');
                setTransactionId('');
                setPaymentNote('');
                loadData();
            })
            .catch((requestError) => {
                setPaymentError(requestError.message || __('Failed to update payment.', 'manfi-expense-tracker'));
            })
            .finally(() => setPaymentSaving(false));
    };

    const deletePayment = (invoiceId, paymentId) => {
        if (!window.confirm(__('Are you sure you want to delete this payment record?', 'manfi-expense-tracker'))) {
            return;
        }
        setPaymentSaving(true);
        requestJson(`${restBase}invoices/${invoiceId}/payment/${paymentId}`, {
            method: 'DELETE',
        })
            .then((savedInvoice) => {
                setMessage(__('Payment record deleted successfully.', 'manfi-expense-tracker'));
                if (paymentInvoice && String(paymentInvoice.id) === String(invoiceId)) {
                    setPaymentInvoice(savedInvoice);
                }
                loadData();
            })
            .catch((requestError) => {
                setPaymentError(requestError.message || __('Failed to delete payment.', 'manfi-expense-tracker'));
            })
            .finally(() => setPaymentSaving(false));
    };

    const totals = useMemo(() => calculateTotals(form), [form]);
    const derivedStatus = useMemo(() => derivePaymentStatus(totals.amountDue, totals.paymentReceivedAmount, form.status), [form.status, totals.amountDue, totals.paymentReceivedAmount]);
    const previousInvoiceOptions = useMemo(() => {
        const clientKey = form.client_id ? String(form.client_id) : '';
        const clientNameKey = String(form.client_name || '').trim().toLowerCase();

        // Collect IDs of invoices that have ALREADY been carried forward into another invoice
        const carriedInvoiceIds = new Set(
            invoices
                .filter((inv) => !form.id || String(inv.id) !== String(form.id))
                .map((inv) => String(inv.previous_invoice_id || ''))
                .filter((id) => id !== '' && id !== '0')
        );

        return invoices.filter((invoice) => {
            if (form.id && String(invoice.id) === String(form.id)) {
                return false;
            }

            // Exclude invoices that were ALREADY carried forward into another invoice,
            // UNLESS it is the currently selected previous invoice for the form.
            const isCurrentlySelected = form.previous_invoice_id && String(invoice.id) === String(form.previous_invoice_id);
            if (!isCurrentlySelected && carriedInvoiceIds.has(String(invoice.id))) {
                return false;
            }

            const invoiceBalance = Number(invoice.balance_due ?? invoice.amount_due ?? invoice.totals?.grand_total ?? 0);
            if (invoiceBalance <= 0) {
                return false;
            }

            if (clientKey) {
                return String(invoice.client_id || '') === clientKey;
            }

            if (clientNameKey) {
                return String(invoice.client_name || '').trim().toLowerCase() === clientNameKey;
            }

            return true;
        });
    }, [form.client_id, form.client_name, form.id, form.previous_invoice_id, invoices]);

    const loadData = () => {
        setLoading(true);
        return Promise.all([
            requestJson(`${restBase}invoices`),
            requestJson(`${restBase}invoice-report`),
            requestJson(`${restBase}financial-accounts`),
            requestJson(`${restBase}vendors`),
            requestJson(`${restBase}clients`),
        ])
            .then(([invoiceData, reportData, accountData, vendorData, clientData]) => {
                setInvoices(Array.isArray(invoiceData) ? invoiceData : []);
                setReport(reportData || { summary: { count: 0, total: 0, average: 0 }, monthly: [], status_counts: {} });
                setFinancialAccounts(Array.isArray(accountData) ? accountData : []);
                setVendors(Array.isArray(vendorData) ? vendorData : []);
                setClients(Array.isArray(clientData) ? clientData : []);
                setError('');
            })
            .catch((requestError) => {
                setError(requestError.message || __('Failed to load invoices.', 'manfi-expense-tracker'));
            })
            .finally(() => setLoading(false));
    };

    const invoiceIdParam = useMemo(() => {
        const searchParams = new URLSearchParams(window.location.search);
        return searchParams.get('invoice_id') || '';
    }, []);

    // Auto-populate client_name when client_id changes
    useEffect(() => {
        if (!form.client_id || !clients.length) {
            return;
        }

        const selectedClient = clients.find((client) => String(client.id) === String(form.client_id));
        if (selectedClient && selectedClient.client_name) {
            setForm((current) => ({ ...current, client_name: selectedClient.client_name }));
        }
    }, [form.client_id, clients]);

    // Best-effort backfill for older invoices that were saved before vendor/client IDs existed.
    useEffect(() => {
        if (!form.id) {
            return;
        }

        if (!form.vendor_id && vendors.length === 1) {
            setForm((current) => ({ ...current, vendor_id: String(vendors[0].id) }));
        }

        if (!form.client_id && form.client_name && clients.length) {
            const matchedClient = clients.find((client) => String(client.client_name || '').trim().toLowerCase() === String(form.client_name || '').trim().toLowerCase());
            if (matchedClient) {
                setForm((current) => ({ ...current, client_id: String(matchedClient.id) }));
            } else if (clients.length === 1) {
                setForm((current) => ({ ...current, client_id: String(clients[0].id) }));
            }
        }
    }, [form.id, form.vendor_id, form.client_id, form.client_name, vendors, clients]);

    useEffect(() => {
        loadData();
    }, [restBase]);

    const updateField = (field, value) => {
        setForm((current) => ({ ...current, [field]: value }));
    };

    const generateDefaultTerms = (dueDate = form.due_date, invoiceNo = form.invoice_no) => {
        const template = appData.invoiceDefaultTerms || "• Payment is due on or before the specified due date ({due_date}).\n• An overdue/late payment fee of {late_fee}% will apply to any unpaid balance after the due date.\n• Please mention invoice #{invoice_no} as reference when making payments.";
        const lateFeePct = appData.invoiceLateFeePct ?? 5.0;
        const formattedDue = dueDate ? dueDate : 'the due date';
        return template
            .replace(/\{due_date\}/g, formattedDue)
            .replace(/\{late_fee\}/g, String(lateFeePct))
            .replace(/\{invoice_no\}/g, invoiceNo || 'INV-XXXX');
    };

    const updateBankField = (field, value) => {
        setForm((current) => ({
            ...current,
            bank: {
                ...current.bank,
                [field]: value,
            },
        }));
    };

    const applyLateFeeForInvoice = (targetInvoice = null) => {
        const selected = targetInvoice || invoices.find((inv) => String(inv.id) === String(form.previous_invoice_id));
        const prevDue = Number(form.previous_due_amount || selected?.balance_due || selected?.amount_due || 0);
        if (prevDue <= 0) return;

        const lateFeePct = Number(appData.invoiceLateFeePct ?? 5.0);
        const lateFeeType = appData.invoiceLateFeeType || 'percentage';
        const calculatedFee = lateFeeType === 'flat' ? lateFeePct : Number((prevDue * (lateFeePct / 100)).toFixed(2));
        
        const rate = Number(form.exchange_rate || 150);
        const adjBdt = calculatedFee.toFixed(2);
        const adjUsd = (form.invoice_type === 'daily_rate' && rate > 0) ? (calculatedFee / rate).toFixed(2) : '';
        const invNo = selected?.invoice_no || form.previous_invoice_no || '';
        const currencyLabel = selected?.currency || form.currency || 'BDT';
        const adjNote = `Adjusted due fee ${lateFeePct}% of ${prevDue.toFixed(2)} ${currencyLabel.toLowerCase()} from previous invoice ${invNo}`.trim();

        setForm((current) => ({
            ...current,
            adjustment_bdt: adjBdt,
            adjustment_usd: adjUsd,
            adjustment_note: adjNote,
        }));
    };

    const applyPreviousInvoice = (invoiceId) => {
        if (!invoiceId) {
            setForm((current) => ({
                ...current,
                previous_invoice_id: '',
                previous_invoice_no: '',
                previous_due_amount: '0',
            }));
            return;
        }

        const selectedInvoice = invoices.find((invoice) => String(invoice.id) === String(invoiceId));
        if (!selectedInvoice) {
            setForm((current) => ({
                ...current,
                previous_invoice_id: String(invoiceId),
            }));
            return;
        }

        const previousDueAmount = Number(selectedInvoice.balance_due ?? selectedInvoice.amount_due ?? selectedInvoice.totals?.grand_total ?? 0);
        
        // Determine if selected invoice is overdue
        const invoiceDueDate = selectedInvoice.due_date ? new Date(`${selectedInvoice.due_date}T23:59:59`) : null;
        const compareDate = form.date ? new Date(`${form.date}T00:00:00`) : new Date();
        const isOverdue = selectedInvoice.status === 'overdue' || (invoiceDueDate && invoiceDueDate < compareDate);
        const shouldAutoApplyLateFee = Boolean(appData.invoiceLateFeeEnabled ?? 1) && isOverdue && previousDueAmount > 0;

        let autoAdjBdt = form.adjustment_bdt;
        let autoAdjUsd = form.adjustment_usd;
        let autoAdjNote = form.adjustment_note;

        if (shouldAutoApplyLateFee) {
            const lateFeePct = Number(appData.invoiceLateFeePct ?? 5.0);
            const lateFeeType = appData.invoiceLateFeeType || 'percentage';
            const calculatedFee = lateFeeType === 'flat' ? lateFeePct : Number((previousDueAmount * (lateFeePct / 100)).toFixed(2));
            const rate = Number(form.exchange_rate || 150);
            autoAdjBdt = calculatedFee.toFixed(2);
            if (form.invoice_type === 'daily_rate' && rate > 0) {
                autoAdjUsd = (calculatedFee / rate).toFixed(2);
            }
            const currencyLabel = selectedInvoice.currency || form.currency || 'BDT';
            autoAdjNote = `Adjusted due fee ${lateFeePct}% of ${previousDueAmount.toFixed(2)} ${currencyLabel.toLowerCase()} from previous invoice ${selectedInvoice.invoice_no || ''}`.trim();
        }

        setForm((current) => ({
            ...current,
            previous_invoice_id: String(selectedInvoice.id),
            previous_invoice_no: selectedInvoice.invoice_no || '',
            previous_due_amount: previousDueAmount.toFixed(2),
            ...(shouldAutoApplyLateFee ? {
                adjustment_bdt: autoAdjBdt,
                adjustment_usd: autoAdjUsd,
                adjustment_note: autoAdjNote,
            } : {})
        }));
    };

    const updateCampaignField = (index, field, value) => {
        setForm((current) => {
            const campaigns = current.campaigns.map((campaign, campaignIndex) => (
                campaignIndex === index ? { ...campaign, [field]: value } : campaign
            ));
            return { ...current, campaigns };
        });
    };

    const addCampaign = () => {
        setForm((current) => ({
            ...current,
            campaigns: [...current.campaigns, emptyCampaign()],
        }));
    };

    const removeCampaign = (index) => {
        setForm((current) => ({
            ...current,
            campaigns: current.campaigns.length > 1 ? current.campaigns.filter((_, itemIndex) => itemIndex !== index) : [emptyCampaign()],
        }));
    };

    const resetForm = () => {
        setForm(newFormState());
        setShareUrl('');
        setMessage('');
        setError('');
    };

    const newInvoice = () => {
        resetForm();
        setMessage(__('Ready to create a new invoice.', 'manfi-expense-tracker'));
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    const editInvoice = (invoice, shouldScroll = true) => {
        setForm({
            id: String(invoice.id),
            invoice_type: invoice.invoice_type || 'standard',
            service_type_label: invoice.service_type_label || '',
            currency: invoice.currency || 'BDT',
            vendor_id: invoice.vendor_id ? String(invoice.vendor_id) : '',
            client_id: invoice.client_id ? String(invoice.client_id) : '',
            client_name: invoice.client_name || '',
            invoice_no: invoice.invoice_no || '',
            date: invoice.date || new Date().toISOString().slice(0, 10),
            due_date: invoice.due_date || '',
            late_fee_pct: String(invoice.late_fee_pct ?? appData.invoiceLateFeePct ?? '5'),
            address: invoice.address || '',
            phone: invoice.phone || '',
            email: invoice.email || '',
            email2: invoice.email2 || '',
            service_desc: invoice.service_desc || '',
            notes: invoice.notes || '',
            exchange_rate: String(invoice.exchange_rate ?? '150'),
            discount_type: invoice.discount_type || (Number(invoice.discount_val ?? invoice.discount_amount ?? 0) > 0 && Number(invoice.discount_pct || 0) === 0 ? 'flat' : 'percentage'),
            discount_val: String(invoice.discount_val ?? (invoice.discount_type === 'flat' ? invoice.discount_amount : invoice.discount_pct) ?? '0'),
            discount_pct: String(invoice.discount_pct ?? '0'),
            vat_pct: String(invoice.vat_pct ?? '15'),
            adjustment_usd: invoice.adjustment_usd ? String(invoice.adjustment_usd) : '',
            adjustment_bdt: invoice.adjustment_bdt ? String(invoice.adjustment_bdt) : '',
            adjustment_note: invoice.adjustment_note || '',
            status: invoice.status || 'pending',
            previous_invoice_id: invoice.previous_invoice_id ? String(invoice.previous_invoice_id) : '',
            previous_invoice_no: invoice.previous_invoice_no || '',
            previous_due_amount: String(invoice.previous_due_amount ?? '0'),
            payment_received_amount: String(invoice.payment_received_amount ?? '0'),
            payments: Array.isArray(invoice.payments) ? invoice.payments : [],
            financial_account_ids: Array.isArray(invoice.financial_account_ids) ? invoice.financial_account_ids.map((accountId) => String(accountId)) : [],
            campaigns: Array.isArray(invoice.campaigns) && invoice.campaigns.length > 0
                ? invoice.campaigns.map((campaign) => ({
                    id: campaign.id || genCampaignId(),
                    name: campaign.name || '',
                    daily_budget: String(campaign.daily_budget ?? ''),
                    duration: String(campaign.duration ?? ''),
                    description: campaign.description || '',
                }))
                : [emptyCampaign()],
            share_token: invoice.share_token || '',
            payment_link: invoice.payment_link || '',
        });
        setShareUrl(invoice.share_url || '');
        setMessage(__('Editing invoice', 'manfi-expense-tracker'));
        setError('');
        if (shouldScroll) {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    };

    useEffect(() => {
        if (!isCreateMode || !invoiceIdParam || loading || invoices.length === 0) {
            return;
        }

        const selectedInvoice = invoices.find((invoice) => String(invoice.id) === String(invoiceIdParam));
        if (selectedInvoice && String(form.id) !== String(selectedInvoice.id)) {
            editInvoice(selectedInvoice, false);
        }
    }, [form.id, invoiceIdParam, invoices, isCreateMode, loading]);

    const copyShareLink = async (url) => {
        if (!url) {
            return;
        }
        try {
            await navigator.clipboard.writeText(url);
            setMessage(__('Invoice link copied to clipboard.', 'manfi-expense-tracker'));
        } catch (clipboardError) {
            setMessage(url);
        }
    };

    const deleteInvoice = (invoice) => {
        if (!window.confirm(__('Delete this invoice?', 'manfi-expense-tracker'))) {
            return;
        }

        requestJson(`${restBase}invoices/${invoice.id}`, { method: 'DELETE' })
            .then(() => {
                setMessage(__('Invoice deleted.', 'manfi-expense-tracker'));
                if (form.id === invoice.id) {
                    resetForm();
                }
                loadData();
            })
            .catch((requestError) => {
                setError(requestError.message || __('Failed to delete invoice.', 'manfi-expense-tracker'));
            });
    };

    const submitInvoice = (event) => {
        event.preventDefault();
        setSaving(true);
        setError('');
        setMessage('');

        const payload = {
            invoice_type: form.invoice_type || 'standard',
            service_type_label: form.service_type_label || '',
            vendor_id: form.vendor_id,
            client_id: form.client_id,
            client_name: form.client_name,
            currency: form.currency || 'BDT',
            invoice_no: form.invoice_no,
            date: form.date,
            due_date: form.due_date,
            late_fee_pct: form.late_fee_pct ?? '5',
            address: form.address,
            phone: form.phone,
            email: form.email,
            email2: form.email2,
            service_desc: form.service_desc,
            notes: form.notes,
            exchange_rate: form.exchange_rate,
            discount_type: form.discount_type || 'percentage',
            discount_val: form.discount_val ?? form.discount_pct ?? '0',
            discount_pct: form.discount_type === 'flat' ? totals.discountPct : (form.discount_val ?? form.discount_pct ?? '0'),
            vat_pct: form.vat_pct,
            adjustment_usd: form.adjustment_usd,
            adjustment_bdt: form.adjustment_bdt,
            adjustment_note: form.adjustment_note,
            status: derivePaymentStatus(totals.amountDue, totals.paymentReceivedAmount, form.status),
            previous_invoice_id: form.previous_invoice_id,
            previous_invoice_no: form.previous_invoice_no,
            previous_due_amount: form.previous_due_amount,
            payment_received_amount: form.payment_received_amount,
            payments: form.payments || [],
            financial_account_ids: form.financial_account_ids,
            payment_link: form.payment_link,
            campaigns: form.campaigns.map((campaign) => ({
                name: campaign.name,
                daily_budget: campaign.daily_budget,
                duration: form.invoice_type === 'fixed' ? '1' : (campaign.duration || '1'),
                description: campaign.description,
                amount: calculateCampaignAmount(campaign, form.invoice_type),
            })),
        };

        const method = form.id ? 'PUT' : 'POST';
        const url = form.id ? `${restBase}invoices/${form.id}` : `${restBase}invoices`;

        requestJson(url, {
            method,
            body: JSON.stringify(payload),
        })
            .then((savedInvoice) => {
                const isNew = !form.id;
                setMessage(isNew ? __('Invoice created successfully. Continue editing or print.', 'manfi-expense-tracker') : __('Invoice updated successfully.', 'manfi-expense-tracker'));
                setShareUrl(savedInvoice.share_url || '');
                // Keep saved invoice in edit mode for further updates or printing
                editInvoice(savedInvoice);
                loadData();
            })
            .catch((requestError) => {
                setError(requestError.message || __('Failed to save invoice.', 'manfi-expense-tracker'));
            })
            .finally(() => setSaving(false));
    };

    const filteredInvoices = useMemo(() => {
        const { start, end } = getDashboardRange(dashboardRange, customRangeStart, customRangeEnd);

        return invoices.filter((invoice) => {
            const invoiceDate = getInvoiceReferenceDate(invoice);
            if (!invoiceDate) {
                return dashboardRange === 'last-year' || dashboardRange === 'last-6-months' || dashboardRange === 'this-month' || dashboardRange === 'this-week' || dashboardRange === 'last-month' ? false : true;
            }

            if (start && invoiceDate < start) {
                return false;
            }

            if (end && invoiceDate > end) {
                return false;
            }

            return true;
        });
    }, [customRangeEnd, customRangeStart, dashboardRange, invoices]);

    const dashboardStats = useMemo(() => {
        const today = startOfDay(new Date());
        const summary = {
            totalInvoiced: 0,
            totalPaid: 0,
            totalUnpaid: 0,
            paidCount: 0,
            partialCount: 0,
            overdueCount: 0,
            unpaidCount: 0,
            dueSoonCount: 0,
            overdueAmount: 0,
            partialAmount: 0,
            pendingAmount: 0,
        };

        const attentionInvoices = [];
        const monthlyMap = new Map();

        filteredInvoices.forEach((invoice) => {
            const amountDue = Number(invoice.amount_due ?? invoice.totals?.grand_total ?? 0);
            const paidAmount = getInvoicePaidAmount(invoice);
            const balanceDue = getInvoiceDueAmount(invoice);
            const dueDate = parseInvoiceDate(invoice.due_date);
            const status = getInvoiceStatus(invoice);
            const isPaid = status === 'paid' || balanceDue <= 0;
            const isPartial = !isPaid && (status === 'partial' || paidAmount > 0);
            const isOverdue = !isPaid && balanceDue > 0 && (status === 'overdue' || (dueDate && dueDate < today));
            const isUnpaid = !isPaid && !isPartial && !isOverdue && balanceDue > 0;
            const daysLate = dueDate ? Math.max(0, Math.ceil((today.getTime() - dueDate.getTime()) / 86400000)) : 0;
            const dueSoon = !isPaid && !isOverdue && balanceDue > 0 && dueDate ? Math.ceil((dueDate.getTime() - today.getTime()) / 86400000) <= 7 : false;

            summary.totalInvoiced += amountDue;
            summary.totalPaid += paidAmount;
            summary.totalUnpaid += balanceDue;

            if (isPaid) {
                summary.paidCount += 1;
            } else if (isPartial) {
                summary.partialCount += 1;
                summary.partialAmount += balanceDue;
            } else if (isOverdue) {
                summary.overdueCount += 1;
                summary.overdueAmount += balanceDue;
            } else if (isUnpaid) {
                summary.unpaidCount += 1;
                summary.pendingAmount += balanceDue;
            }

            if (dueSoon) {
                summary.dueSoonCount += 1;
            }

            const referenceDate = getInvoiceReferenceDate(invoice);
            if (referenceDate) {
                const monthKey = referenceDate.toISOString().slice(0, 7);
                monthlyMap.set(monthKey, (monthlyMap.get(monthKey) || 0) + amountDue);
            }

            if (balanceDue > 0 && (isOverdue || isPartial || isUnpaid || dueSoon)) {
                attentionInvoices.push({
                    ...invoice,
                    amountDue,
                    paidAmount,
                    balanceDue,
                    dueDate,
                    daysLate,
                    isPaid,
                    isPartial,
                    isOverdue,
                    isUnpaid,
                    dueSoon,
                });
            }
        });

        attentionInvoices.sort((left, right) => {
            const leftPriority = left.isOverdue ? 0 : left.isPartial ? 1 : left.dueSoon ? 2 : 3;
            const rightPriority = right.isOverdue ? 0 : right.isPartial ? 1 : right.dueSoon ? 2 : 3;

            if (leftPriority !== rightPriority) {
                return leftPriority - rightPriority;
            }

            return (right.daysLate || 0) - (left.daysLate || 0);
        });

        const monthly = Array.from(monthlyMap.entries())
            .sort(([leftMonth], [rightMonth]) => String(leftMonth).localeCompare(String(rightMonth)))
            .map(([label, value]) => ({ label, value: Number(value.toFixed(2)) }));

        return {
            summary,
            monthly,
            attentionInvoices: attentionInvoices.slice(0, 6),
            count: filteredInvoices.length,
            range: getDashboardRange(dashboardRange, customRangeStart, customRangeEnd),
        };
    }, [customRangeEnd, customRangeStart, dashboardRange, filteredInvoices]);

    const dashboardUrl = buildAdminPageUrl('manfiet-invoice-manager');
    const createInvoiceUrl = buildAdminPageUrl('manfiet-invoice-create');
    const dashboardRangeLabel = useMemo(() => {
        if (dashboardRange === 'custom') {
            const start = customRangeStart ? formatDashboardDate(startOfDay(new Date(`${customRangeStart}T00:00:00`))) : '';
            const end = customRangeEnd ? formatDashboardDate(startOfDay(new Date(`${customRangeEnd}T00:00:00`))) : '';
            if (start && end) {
                return `${start} - ${end}`;
            }
            if (start) {
                return `${start} - ${__('Open ended', 'manfi-expense-tracker')}`;
            }
            if (end) {
                return `${__('Up to', 'manfi-expense-tracker')} ${end}`;
            }
            return __('Custom range', 'manfi-expense-tracker');
        }

        return dashboardRangeOptions.find((option) => option.value === dashboardRange)?.label || __('This month', 'manfi-expense-tracker');
    }, [customRangeEnd, customRangeStart, dashboardRange]);
    const title = isCreateMode ? __('Create Invoice', 'manfi-expense-tracker') : __('Invoice Dashboard', 'manfi-expense-tracker');
    const subtitle = isCreateMode
        ? __('Create or edit a single invoice and track any carried due from a previous invoice.', 'manfi-expense-tracker')
        : __('Review invoice totals, payment status, and recent balances in one place.', 'manfi-expense-tracker');

    return (
        <div className="manfiet-page-shell manfiet-page-shell-wide manfiet-invoice-manager-shell">
            <div className="manfiet-page-hero">
                <div className='left-section'>
                    <h1 className="manfiet-page-title">{title}</h1>
                    <p className="manfiet-page-subtitle">{subtitle}</p>
                    {isCreateMode ? (
                        <button type="button" className="manfiet-button manfiet-button-secondary" onClick={() => window.location.href = dashboardUrl}>
                            {__('Back to Dashboard', 'manfi-expense-tracker')}
                        </button>
                    ) : (
                        <button type="button" className="manfiet-button manfiet-button-primary" onClick={() => window.location.href = createInvoiceUrl}>
                            {__('Create Invoice', 'manfi-expense-tracker')}
                        </button>
                    )}
                </div>
                <div className="manfiet-hero-toolbar">
                    {!isCreateMode && (
                        <div className="manfiet-dashboard-range-panel">
                            <div className="manfiet-dashboard-range-top">
                                <div>
                                    <div className="manfiet-dashboard-range-label">{__('Date range', 'manfi-expense-tracker')}</div>
                                    <div className="manfiet-dashboard-range-value">{dashboardRangeLabel}</div>
                                </div>
                                <div className="manfiet-dashboard-range-count">{filteredInvoices.length} {__('invoices', 'manfi-expense-tracker')}</div>
                            </div>
                            <div className="manfiet-dashboard-range-controls">
                                <div className="manfiet-field manfiet-dashboard-range-field">
                                    <label className="manfiet-sr-only" htmlFor="manfiet-dashboard-range">{__('Range', 'manfi-expense-tracker')}</label>
                                    <select
                                        id="manfiet-dashboard-range"
                                        className="manfiet-input manfiet-dashboard-range-select"
                                        value={dashboardRange}
                                        onChange={(event) => setDashboardRange(event.target.value)}
                                    >
                                        {dashboardRangeOptions.map((option) => (
                                            <option key={option.value} value={option.value}>{option.label}</option>
                                        ))}
                                    </select>
                                </div>
                                {dashboardRange === 'custom' && (
                                    <>
                                        <div className="manfiet-field">
                                            <label className="manfiet-label" htmlFor="manfiet-dashboard-range-start">{__('From', 'manfi-expense-tracker')}</label>
                                            <input
                                                id="manfiet-dashboard-range-start"
                                                type="date"
                                                className="manfiet-input"
                                                value={customRangeStart}
                                                onChange={(event) => setCustomRangeStart(event.target.value)}
                                            />
                                        </div>
                                        <div className="manfiet-field">
                                            <label className="manfiet-label" htmlFor="manfiet-dashboard-range-end">{__('To', 'manfi-expense-tracker')}</label>
                                            <input
                                                id="manfiet-dashboard-range-end"
                                                type="date"
                                                className="manfiet-input"
                                                value={customRangeEnd}
                                                onChange={(event) => setCustomRangeEnd(event.target.value)}
                                            />
                                        </div>
                                    </>
                                )}
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {!isCreateMode && (
                <>
                    <div className="manfiet-stats-grid manfiet-mb-16">
                        <div className="manfiet-card manfiet-stat-card">
                            <div className="manfiet-stat-label">{__('Invoices', 'manfi-expense-tracker')}</div>
                            <div className="manfiet-stat-value">{dashboardStats.count || 0}</div>
                        </div>
                        <div className="manfiet-card manfiet-stat-card">
                            <div className="manfiet-stat-label">{__('Total Invoiced', 'manfi-expense-tracker')}</div>
                            <div className="manfiet-stat-value">{formatMoneyBdt(dashboardStats.summary.totalInvoiced)}</div>
                        </div>
                        <div className="manfiet-card manfiet-stat-card">
                            <div className="manfiet-stat-label">{__('Total Paid', 'manfi-expense-tracker')}</div>
                            <div className="manfiet-stat-value">{formatMoneyBdt(dashboardStats.summary.totalPaid)}</div>
                        </div>
                        <div className="manfiet-card manfiet-stat-card">
                            <div className="manfiet-stat-label">{__('Total Unpaid', 'manfi-expense-tracker')}</div>
                            <div className="manfiet-stat-value">{formatMoneyBdt(dashboardStats.summary.totalUnpaid)}</div>
                        </div>
                        <div className="manfiet-card manfiet-stat-card">
                            <div className="manfiet-stat-label">{__('Overdue', 'manfi-expense-tracker')}</div>
                            <div className="manfiet-stat-value">{dashboardStats.summary.overdueCount}</div>
                            <div className="manfiet-text-muted">{formatMoneyBdt(dashboardStats.summary.overdueAmount)} {__('at risk', 'manfi-expense-tracker')}</div>
                        </div>
                        <div className="manfiet-card manfiet-stat-card">
                            <div className="manfiet-stat-label">{__('Partial', 'manfi-expense-tracker')}</div>
                            <div className="manfiet-stat-value">{dashboardStats.summary.partialCount}</div>
                            <div className="manfiet-text-muted">{formatMoneyBdt(dashboardStats.summary.partialAmount)} {__('remaining', 'manfi-expense-tracker')}</div>
                        </div>
                        <div className="manfiet-card manfiet-stat-card">
                            <div className="manfiet-stat-label">{__('Pending / Unpaid', 'manfi-expense-tracker')}</div>
                            <div className="manfiet-stat-value">{dashboardStats.summary.unpaidCount}</div>
                            <div className="manfiet-text-muted">{formatMoneyBdt(dashboardStats.summary.pendingAmount)} {__('awaiting payment', 'manfi-expense-tracker')}</div>
                        </div>
                        <div className="manfiet-card manfiet-stat-card">
                            <div className="manfiet-stat-label">{__('Paid', 'manfi-expense-tracker')}</div>
                            <div className="manfiet-stat-value">{dashboardStats.summary.paidCount}</div>
                        </div>
                    </div>

                    <div className="manfiet-card manfiet-mb-16">
                        <div className="manfiet-card-head-row manfiet-mb-14">
                            <h3 className="manfiet-card-title manfiet-card-title-no-margin">{__('Payment Attention', 'manfi-expense-tracker')}</h3>
                        </div>
                        {dashboardStats.attentionInvoices.length === 0 ? (
                            <p className="manfiet-text-muted">{__('No overdue or partially unpaid invoices right now.', 'manfi-expense-tracker')}</p>
                        ) : (
                            <div className="manfiet-table-scroll">
                                <table className="manfiet-table">
                                    <thead>
                                        <tr>
                                            <th>{__('Invoice', 'manfi-expense-tracker')}</th>
                                            <th>{__('Client', 'manfi-expense-tracker')}</th>
                                            <th>{__('Due Date', 'manfi-expense-tracker')}</th>
                                            <th>{__('Status', 'manfi-expense-tracker')}</th>
                                            <th>{__('Paid', 'manfi-expense-tracker')}</th>
                                            <th>{__('Remaining', 'manfi-expense-tracker')}</th>
                                            <th>{__('Priority', 'manfi-expense-tracker')}</th>
                                            <th>{__('Actions', 'manfi-expense-tracker')}</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {dashboardStats.attentionInvoices.map((invoice) => (
                                            <tr key={`attention-${invoice.id}`}>
                                                <td>{invoice.invoice_no}</td>
                                                <td>{invoice.client_name}</td>
                                                <td>{invoice.dueDate ? invoice.dueDate.toLocaleDateString() : __('Not set', 'manfi-expense-tracker')}</td>
                                                <td><span className={`manfiet-pill manfiet-pill-${invoice.status || 'pending'}`}>{invoice.status || 'pending'}</span></td>
                                                <td>{formatMoneyBdt(invoice.paidAmount)}</td>
                                                <td>{formatMoneyBdt(invoice.balanceDue)}</td>
                                                <td>
                                                    {invoice.isOverdue ? `${invoice.daysLate} ${__('days overdue', 'manfi-expense-tracker')}` : invoice.isPartial ? __('Partially paid', 'manfi-expense-tracker') : invoice.dueSoon ? __('Due soon', 'manfi-expense-tracker') : __('Unpaid', 'manfi-expense-tracker')}
                                                </td>
                                                <td>
                                                    <button type="button" className="manfiet-button manfiet-button-primary manfiet-button-sm" onClick={() => openPaymentDialog(invoice)}>{__('Payment', 'manfi-expense-tracker')}</button>
                                                    <a href={`${restBase}invoices/${invoice.id}/pdf?token=${invoice.share_token}`} download className="manfiet-button manfiet-button-secondary manfiet-button-sm manfiet-ml-8">{__('PDF', 'manfi-expense-tracker')}</a>
                                                    <button type="button" className="manfiet-button manfiet-button-info manfiet-button-sm manfiet-ml-8" onClick={() => { window.location.href = buildAdminPageUrl('manfiet-invoice-create', invoice.id); }}>{__('Open', 'manfi-expense-tracker')}</button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </div>
                </>
            )}

            {isCreateMode && (
                <div className="manfiet-card manfiet-mb-16">
                    <h3 className="manfiet-card-title">{form.id ? __('Edit Invoice', 'manfi-expense-tracker') : __('Create Invoice', 'manfi-expense-tracker')}</h3>
                    {error && <p className="manfiet-alert manfiet-alert-error">{error}</p>}
                    {message && <p className="manfiet-alert manfiet-alert-success">{message}</p>}

                    <form onSubmit={submitInvoice} className="manfiet-form-stack">
                        <div className="manfiet-card manfiet-card-inset manfiet-mb-14">
                            <h4 className="manfiet-card-subtitle">{__('Vendor & Client', 'manfi-expense-tracker')}</h4>
                            <p className="manfiet-text-muted manfiet-mb-12">{__('Select a vendor (your company) and client (customer). If not available, create them on their respective pages first.', 'manfi-expense-tracker')}</p>
                            <div className="manfiet-form-grid">
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-vendor-select">{__('Vendor (Your Company)', 'manfi-expense-tracker')}</label>
                                    <select
                                        id="manfiet-vendor-select"
                                        className="manfiet-input"
                                        value={form.vendor_id}
                                        onChange={(e) => updateField('vendor_id', e.target.value)}
                                    >
                                        <option value="">{__('-- Select vendor --', 'manfi-expense-tracker')}</option>
                                        {vendors.map((vendor) => (
                                            <option key={vendor.id} value={String(vendor.id)}>
                                                {vendor.company_name}
                                            </option>
                                        ))}
                                    </select>
                                    {vendors.length === 0 && <p className="manfiet-text-muted manfiet-mt-4">{__('No vendors available. Create one on the Vendors page.', 'manfi-expense-tracker')}</p>}
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-client-select">{__('Client (Customer)', 'manfi-expense-tracker')}</label>
                                    <select
                                        id="manfiet-client-select"
                                        className="manfiet-input"
                                        value={form.client_id}
                                        onChange={(e) => updateField('client_id', e.target.value)}
                                    >
                                        <option value="">{__('-- Select client --', 'manfi-expense-tracker')}</option>
                                        {clients.map((client) => (
                                            <option key={client.id} value={String(client.id)}>
                                                {client.client_name}
                                            </option>
                                        ))}
                                    </select>
                                    {clients.length === 0 && <p className="manfiet-text-muted manfiet-mt-4">{__('No clients available. Create one on the Clients page.', 'manfi-expense-tracker')}</p>}
                                </div>
                            </div>
                        </div>
                        <div className="manfiet-form-grid">
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-invoice-type">{__('Invoice Type / Mode', 'manfi-expense-tracker')}</label>
                                <select
                                    id="manfiet-invoice-type"
                                    className="manfiet-input"
                                    value={form.invoice_type || 'standard'}
                                    onChange={(e) => updateField('invoice_type', e.target.value)}
                                >
                                    <option value="standard">{__('Standard Products & Services (Direct Currency)', 'manfi-expense-tracker')}</option>
                                    <option value="daily_rate">{__('Daily Rate & Campaign (USD with Exchange Rate)', 'manfi-expense-tracker')}</option>
                                    <option value="hourly">{__('Hourly & Retainer Services', 'manfi-expense-tracker')}</option>
                                    <option value="fixed">{__('Fixed Milestone / Flat Fee', 'manfi-expense-tracker')}</option>
                                </select>
                            </div>
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-currency">{__('Currency', 'manfi-expense-tracker')}</label>
                                <select
                                    id="manfiet-currency"
                                    className="manfiet-input"
                                    value={form.currency || 'BDT'}
                                    onChange={(e) => updateField('currency', e.target.value)}
                                >
                                    <option value="BDT">BDT (৳) - Bangladeshi Taka</option>
                                    <option value="USD">USD ($) - US Dollar</option>
                                    <option value="GBP">GBP (£) - British Pound</option>
                                    <option value="EUR">EUR (€) - Euro</option>
                                    <option value="CAD">CAD (CA$) - Canadian Dollar</option>
                                    <option value="AUD">AUD (A$) - Australian Dollar</option>
                                    <option value="INR">INR (₹) - Indian Rupee</option>
                                    <option value="AED">AED (AED) - UAE Dirham</option>
                                    <option value="SAR">SAR (SAR) - Saudi Riyal</option>
                                    <option value="MYR">MYR (RM) - Malaysian Ringgit</option>
                                    <option value="SGD">SGD (S$) - Singapore Dollar</option>
                                </select>
                            </div>
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-service-type-label">{__('Category / Service Label', 'manfi-expense-tracker')}</label>
                                <input
                                    id="manfiet-service-type-label"
                                    className="manfiet-input"
                                    value={form.service_type_label || ''}
                                    onChange={(e) => updateField('service_type_label', e.target.value)}
                                    placeholder={__('e.g. E-Commerce Order, Web Development, Consulting', 'manfi-expense-tracker')}
                                />
                            </div>
                            {!form.client_id && (
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-client-name">{__('Client Name', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-client-name" className="manfiet-input" value={form.client_name} onChange={(e) => updateField('client_name', e.target.value)} placeholder={__('Enter client name manually if not selecting from list', 'manfi-expense-tracker')} />
                                </div>
                            )}
                            {form.client_id && (
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-client-name-readonly">{__('Client Name', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-client-name-readonly" className="manfiet-input" value={form.client_name} readOnly style={{ backgroundColor: '#f0f0f0', cursor: 'not-allowed' }} />
                                    <p className="manfiet-text-muted manfiet-mt-4">{__('Auto-populated from selected client. Clear client selection to edit.', 'manfi-expense-tracker')}</p>
                                </div>
                            )}
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-invoice-no">{__('Invoice #', 'manfi-expense-tracker')}</label>
                                <input id="manfiet-invoice-no" className="manfiet-input" value={form.invoice_no} onChange={(e) => updateField('invoice_no', e.target.value)} />
                                {!form.id && <p className="manfiet-text-muted manfiet-mt-4">{__('Leave blank to generate automatically.', 'manfi-expense-tracker')}</p>}
                            </div>
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-invoice-date">{__('Date', 'manfi-expense-tracker')}</label>
                                <input id="manfiet-invoice-date" type="date" className="manfiet-input" value={form.date} onChange={(e) => updateField('date', e.target.value)} />
                            </div>
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-due-date">{__('Due Date', 'manfi-expense-tracker')}</label>
                                <input id="manfiet-due-date" type="date" className="manfiet-input" value={form.due_date} onChange={(e) => updateField('due_date', e.target.value)} />
                            </div>
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-late-fee-pct">{__('Overdue Due Fee (%)', 'manfi-expense-tracker')}</label>
                                <input id="manfiet-late-fee-pct" type="number" min="0" step="0.1" className="manfiet-input" value={form.late_fee_pct} onChange={(e) => updateField('late_fee_pct', e.target.value)} placeholder="5.0" />
                                <p className="manfiet-text-muted manfiet-mt-4">{__('Late fee % applied if unpaid after due date.', 'manfi-expense-tracker')}</p>
                            </div>
                            {form.invoice_type === 'daily_rate' && (
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-exchange-rate">{__('Exchange Rate (BDT/USD)', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-exchange-rate" type="number" min="0" step="0.01" className="manfiet-input" value={form.exchange_rate} onChange={(e) => updateField('exchange_rate', e.target.value)} />
                                </div>
                            )}
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-discount-type">{__('Discount Type', 'manfi-expense-tracker')}</label>
                                <select
                                    id="manfiet-discount-type"
                                    className="manfiet-input"
                                    value={form.discount_type || 'percentage'}
                                    onChange={(e) => updateField('discount_type', e.target.value)}
                                >
                                    <option value="percentage">{__('Percentage (%)', 'manfi-expense-tracker')}</option>
                                    <option value="flat">{__('Flat Amount', 'manfi-expense-tracker')}</option>
                                </select>
                            </div>
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-discount-val">
                                    {form.discount_type === 'flat'
                                        ? `${__('Discount Amount', 'manfi-expense-tracker')} (${currencySymbols[form.currency] || form.currency})`
                                        : __('Discount %', 'manfi-expense-tracker')}
                                </label>
                                <input
                                    id="manfiet-discount-val"
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    className="manfiet-input"
                                    value={form.discount_val ?? form.discount_pct ?? '0'}
                                    onChange={(e) => {
                                        updateField('discount_val', e.target.value);
                                        if (form.discount_type !== 'flat') {
                                            updateField('discount_pct', e.target.value);
                                        }
                                    }}
                                    placeholder="0"
                                />
                            </div>
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-vat-pct">{__('VAT %', 'manfi-expense-tracker')}</label>
                                <input id="manfiet-vat-pct" type="number" min="0" step="0.01" className="manfiet-input" value={form.vat_pct} onChange={(e) => updateField('vat_pct', e.target.value)} />
                            </div>
                            <div className="manfiet-field">
                                <label className="manfiet-label" htmlFor="manfiet-status">{__('Status', 'manfi-expense-tracker')}</label>
                                <select id="manfiet-status" className="manfiet-input" value={form.status} onChange={(e) => updateField('status', e.target.value)}>
                                    <option value="pending">{__('Pending', 'manfi-expense-tracker')}</option>
                                    <option value="partial">{__('Partial', 'manfi-expense-tracker')}</option>
                                    <option value="paid">{__('Paid', 'manfi-expense-tracker')}</option>
                                    <option value="overdue">{__('Overdue', 'manfi-expense-tracker')}</option>
                                    <option value="draft">{__('Draft', 'manfi-expense-tracker')}</option>
                                </select>
                            </div>
                        </div>

                        <div className="manfiet-card manfiet-card-inset manfiet-mb-14">
                            <h4 className="manfiet-card-subtitle">{__('Invoice Adjustment (Optional)', 'manfi-expense-tracker')}</h4>
                            <p className="manfiet-text-muted manfiet-mb-12">{__('Add a manual adjustment (credit/debit) from a previous invoice or general changes. Positive values increase the invoice total, negative values decrease it.', 'manfi-expense-tracker')}</p>
                            <div className="manfiet-form-grid">
                                {form.invoice_type === 'daily_rate' && (
                                    <div className="manfiet-field">
                                        <label className="manfiet-label" htmlFor="manfiet-adjustment-usd">{__('Adjustment Amount (USD)', 'manfi-expense-tracker')}</label>
                                        <input
                                            id="manfiet-adjustment-usd"
                                            type="number"
                                            step="0.01"
                                            className="manfiet-input"
                                            value={form.adjustment_usd}
                                            onChange={(e) => {
                                                const val = e.target.value;
                                                updateField('adjustment_usd', val);
                                                // Auto-calculate BDT based on exchange rate
                                                const rate = Number(form.exchange_rate || 0);
                                                const bdt = (val !== '' && rate > 0) ? String((Number(val) * rate).toFixed(2)) : '';
                                                updateField('adjustment_bdt', bdt);
                                            }}
                                            placeholder={__('e.g. -10.00', 'manfi-expense-tracker')}
                                        />
                                    </div>
                                )}
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-adjustment-bdt">{__('Adjustment Amount', 'manfi-expense-tracker')}</label>
                                    <input
                                        id="manfiet-adjustment-bdt"
                                        type="number"
                                        step="0.01"
                                        className="manfiet-input"
                                        value={form.adjustment_bdt}
                                        onChange={(e) => {
                                            const val = e.target.value;
                                            updateField('adjustment_bdt', val);
                                            // If daily rate mode, sync USD
                                            if (form.invoice_type === 'daily_rate') {
                                                const rate = Number(form.exchange_rate || 0);
                                                const usd = (val !== '' && rate > 0) ? String((Number(val) / rate).toFixed(2)) : '';
                                                updateField('adjustment_usd', usd);
                                            }
                                        }}
                                        placeholder={__('e.g. -1500.00', 'manfi-expense-tracker')}
                                    />
                                </div>
                            </div>
                            <div className="manfiet-field manfiet-mt-12">
                                <label className="manfiet-label" htmlFor="manfiet-adjustment-note">{__('Adjustment Note / Message', 'manfi-expense-tracker')}</label>
                                <input
                                    id="manfiet-adjustment-note"
                                    className="manfiet-input"
                                    value={form.adjustment_note}
                                    onChange={(e) => updateField('adjustment_note', e.target.value)}
                                    placeholder={__('e.g. Credit adjustment from previous period', 'manfi-expense-tracker')}
                                />
                            </div>
                        </div>

                        <div className="manfiet-card manfiet-card-inset manfiet-mb-14">
                            <h4 className="manfiet-card-subtitle">{__('Payment Tracking', 'manfi-expense-tracker')}</h4>
                            <p className="manfiet-text-muted manfiet-mb-12">{__('Link a previous invoice when you are carrying an unpaid balance into this invoice. Enter how much was received so the balance stays visible.', 'manfi-expense-tracker')}</p>
                            <div className="manfiet-form-grid">
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-previous-invoice">{__('Previous Invoice', 'manfi-expense-tracker')}</label>
                                    <select
                                        id="manfiet-previous-invoice"
                                        className="manfiet-input"
                                        value={form.previous_invoice_id}
                                        onChange={(e) => applyPreviousInvoice(e.target.value)}
                                    >
                                        <option value="">{__('-- None --', 'manfi-expense-tracker')}</option>
                                        {previousInvoiceOptions.map((invoice) => (
                                            <option key={invoice.id} value={String(invoice.id)}>
                                                {invoice.invoice_no} - {invoice.client_name} - {formatMoneyCurrency(Number(invoice.balance_due ?? invoice.amount_due ?? invoice.totals?.grand_total ?? 0), invoice.currency || form.currency)} {__('due', 'manfi-expense-tracker')}
                                            </option>
                                        ))}
                                    </select>
                                    {previousInvoiceOptions.length === 0 && <p className="manfiet-text-muted manfiet-mt-4">{__('No open invoices found for this client.', 'manfi-expense-tracker')}</p>}
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-previous-invoice-no">{__('Previous Invoice #', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-previous-invoice-no" className="manfiet-input" value={form.previous_invoice_no} onChange={(e) => updateField('previous_invoice_no', e.target.value)} placeholder={__('Selected invoice number', 'manfi-expense-tracker')} />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-previous-due">{__('Previous Due', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-previous-due" type="number" min="0" step="0.01" className="manfiet-input" value={form.previous_due_amount} onChange={(e) => updateField('previous_due_amount', e.target.value)} />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-payment-received">{__('Current Payment Received (Total)', 'manfi-expense-tracker')}</label>
                                    <div style={{ display: 'flex', gap: '8px' }}>
                                        <input id="manfiet-payment-received" type="number" min="0" step="0.01" className="manfiet-input" value={form.payment_received_amount} onChange={(e) => updateField('payment_received_amount', e.target.value)} />
                                        {form.id && (
                                            <button type="button" className="manfiet-button manfiet-button-primary" style={{ whitespace: 'nowrap' }} onClick={() => openPaymentDialog(form)}>
                                                {__('+ Add Payment', 'manfi-expense-tracker')}
                                            </button>
                                        )}
                                    </div>
                                    <p className="manfiet-text-muted manfiet-mt-4">{__('Total amount received for this invoice.', 'manfi-expense-tracker')}</p>
                                </div>
                            </div>

                            {(() => {
                                const selectedLinked = invoices.find((inv) => String(inv.id) === String(form.previous_invoice_id));
                                if (!selectedLinked) return null;
                                const linkedDue = selectedLinked.due_date ? new Date(`${selectedLinked.due_date}T23:59:59`) : null;
                                const compareDate = form.date ? new Date(`${form.date}T00:00:00`) : new Date();
                                const isOverdue = selectedLinked.status === 'overdue' || (linkedDue && linkedDue < compareDate);
                                const prevDueNum = Number(form.previous_due_amount || selectedLinked.balance_due || 0);
                                if (!isOverdue || prevDueNum <= 0) return null;

                                const lateFeePct = Number(appData.invoiceLateFeePct ?? 5.0);
                                const lateFeeType = appData.invoiceLateFeeType || 'percentage';
                                const calcFee = lateFeeType === 'flat' ? lateFeePct : Number((prevDueNum * (lateFeePct / 100)).toFixed(2));

                                return (
                                    <div style={{ background: '#fffbeb', border: '1.5px solid #fde68a', borderRadius: '8px', padding: '12px 16px', marginTop: '14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '10px' }}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                            <span style={{ fontSize: '20px' }}>⚡</span>
                                            <div>
                                                <div style={{ fontSize: '13.5px', color: '#92400e', fontWeight: '700' }}>
                                                    {__('Overdue Invoice Detected:', 'manfi-expense-tracker')} {selectedLinked.invoice_no}
                                                    {selectedLinked.due_date ? ` (${__('Due Date was:', 'manfi-expense-tracker')} ${selectedLinked.due_date})` : ''}
                                                </div>
                                                <div style={{ fontSize: '12.5px', color: '#b45309', marginTop: '2px' }}>
                                                    {__('Overdue balance:', 'manfi-expense-tracker')} <strong>{formatMoneyCurrency(prevDueNum, selectedLinked.currency || form.currency)}</strong> • {__('Late fine at', 'manfi-expense-tracker')} {lateFeePct}%: <strong>+{formatMoneyCurrency(calcFee, form.currency)}</strong>
                                                </div>
                                            </div>
                                        </div>
                                        <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                                            <button
                                                type="button"
                                                className="manfiet-button manfiet-button-primary manfiet-button-sm"
                                                style={{ background: '#d97706', borderColor: '#b45309', fontWeight: '600', padding: '6px 14px' }}
                                                onClick={() => applyLateFeeForInvoice(selectedLinked)}
                                            >
                                                {__('⚡ Apply Late Fee Adjustment', 'manfi-expense-tracker')}
                                            </button>
                                        </div>
                                    </div>
                                );
                            })()}

                            {form.payments && form.payments.length > 0 && (
                                <div className="manfiet-mt-14" style={{ background: '#ffffff', padding: '12px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                                        <h5 style={{ margin: 0, fontSize: '14px', fontWeight: '600', color: '#1e293b' }}>{__('Recorded Payments History', 'manfi-expense-tracker')}</h5>
                                        {form.id && (
                                            <button type="button" className="manfiet-button manfiet-button-primary manfiet-button-sm" onClick={() => openPaymentDialog(form)}>
                                                {__('+ Add Payment', 'manfi-expense-tracker')}
                                            </button>
                                        )}
                                    </div>
                                    <div className="manfiet-table-responsive">
                                        <table className="manfiet-table manfiet-table-sm" style={{ width: '100%', fontSize: '13px' }}>
                                            <thead>
                                                <tr>
                                                    <th>{__('Date & Time', 'manfi-expense-tracker')}</th>
                                                    <th>{__('Method', 'manfi-expense-tracker')}</th>
                                                    <th>{__('Trx ID', 'manfi-expense-tracker')}</th>
                                                    <th>{__('Amount', 'manfi-expense-tracker')}</th>
                                                    {form.id && <th style={{ textAlign: 'right' }}>{__('Action', 'manfi-expense-tracker')}</th>}
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {form.payments.map((item) => (
                                                    <tr key={item.id}>
                                                        <td>{item.date || '-'}</td>
                                                        <td><span className="manfiet-badge" style={{ background: '#e0f2fe', color: '#0369a1', padding: '2px 8px', borderRadius: '4px', fontSize: '12px', fontWeight: '500' }}>{item.method || 'Default'}</span></td>
                                                        <td><code>{item.transaction_id || '-'}</code></td>
                                                        <td><strong>{formatMoneyCurrency(item.amount, form.currency)}</strong></td>
                                                        {form.id && (
                                                            <td style={{ textAlign: 'right' }}>
                                                                <button
                                                                    type="button"
                                                                    className="manfiet-button manfiet-button-danger manfiet-button-sm"
                                                                    onClick={() => deletePayment(form.id, item.id)}
                                                                >
                                                                    {__('Delete', 'manfi-expense-tracker')}
                                                                </button>
                                                            </td>
                                                        )}
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            )}

                            <div className="manfiet-summary-list manfiet-mt-12">
                                <div><span>{__('Amount Due', 'manfi-expense-tracker')}</span><strong>{formatMoneyCurrency(totals.amountDue, form.currency)}</strong></div>
                                <div><span>{__('Current Received', 'manfi-expense-tracker')}</span><strong>{formatMoneyCurrency(totals.paymentReceivedAmount, form.currency)}</strong></div>
                                <div><span>{__('Balance Due', 'manfi-expense-tracker')}</span><strong>{formatMoneyCurrency(totals.balanceDue, form.currency)}</strong></div>
                            </div>
                        </div>

                        <div className="manfiet-card manfiet-card-inset manfiet-mb-14">
                            <h4 className="manfiet-card-subtitle">{__('Invoice Contact Overrides', 'manfi-expense-tracker')}</h4>
                            <p className="manfiet-text-muted manfiet-mb-12">{__('Use these only if you want to override the saved vendor or client contact details on this invoice.', 'manfi-expense-tracker')}</p>
                            <div className="manfiet-form-grid">
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-phone">{__('Client Phone Number', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-phone" className="manfiet-input" value={form.phone} onChange={(e) => updateField('phone', e.target.value)} />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-email">{__('Client Email Address', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-email" className="manfiet-input" value={form.email} onChange={(e) => updateField('email', e.target.value)} />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-email2">{__('Client Secondary Email', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-email2" className="manfiet-input" value={form.email2} onChange={(e) => updateField('email2', e.target.value)} />
                                </div>
                            </div>

                            <div className="manfiet-field manfiet-mt-12">
                                <label className="manfiet-label" htmlFor="manfiet-address">{__('Client Address', 'manfi-expense-tracker')}</label>
                                <textarea id="manfiet-address" className="manfiet-input" rows="3" value={form.address} onChange={(e) => updateField('address', e.target.value)} />
                            </div>
                        </div>

                        <div className="manfiet-field">
                            <label className="manfiet-label" htmlFor="manfiet-service-desc">{__('Service Description', 'manfi-expense-tracker')}</label>
                            <input id="manfiet-service-desc" className="manfiet-input" value={form.service_desc} onChange={(e) => updateField('service_desc', e.target.value)} placeholder={__('e.g. Services & Billing', 'manfi-expense-tracker')} />
                        </div>

                        <div className="manfiet-field manfiet-mt-12">
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                                <label className="manfiet-label" htmlFor="manfiet-notes" style={{ margin: 0 }}>
                                    {__('Notes & Conditions', 'manfi-expense-tracker')}
                                </label>
                                <button
                                    type="button"
                                    className="manfiet-button manfiet-button-secondary manfiet-button-sm"
                                    style={{ fontSize: '11.5px', padding: '3px 10px', background: '#f1f5f9', color: '#1e293b', border: '1px solid #cbd5e1' }}
                                    onClick={() => {
                                        const defaultTerms = generateDefaultTerms(form.due_date, form.invoice_no);
                                        updateField('notes', form.notes ? `${form.notes.trim()}\n\n${defaultTerms}` : defaultTerms);
                                    }}
                                >
                                    {__('📋 Insert Standard Terms & Late Fee Policy', 'manfi-expense-tracker')}
                                </button>
                            </div>
                            <textarea id="manfiet-notes" className="manfiet-input" rows="3" value={form.notes} onChange={(e) => updateField('notes', e.target.value)} placeholder={__('Enter custom terms, notes, or conditions...', 'manfi-expense-tracker')} />
                        </div>

                        <div className="manfiet-card manfiet-card-inset">
                            <h4 className="manfiet-card-subtitle">{__('Payment Accounts', 'manfi-expense-tracker')}</h4>
                            <p className="manfiet-text-muted manfiet-mb-12">{__('Select the payment accounts to display on this invoice:', 'manfi-expense-tracker')}</p>
                            
                            {financialAccounts.length === 0 ? (
                                <p className="manfiet-text-muted">{__('No financial accounts available. Create them on the Financial Accounts page.', 'manfi-expense-tracker')}</p>
                            ) : (
                                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '10px', marginTop: '10px' }}>
                                    {financialAccounts.map((account) => {
                                        const accountIdStr = String(account.id);
                                        const isChecked = form.financial_account_ids.includes(accountIdStr);
                                        return (
                                            <label
                                                key={account.id}
                                                style={{
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    gap: '10px',
                                                    padding: '10px 14px',
                                                    background: isChecked ? '#eff6ff' : '#ffffff',
                                                    border: `1.5px solid ${isChecked ? '#2563eb' : '#e2e8f0'}`,
                                                    borderRadius: '8px',
                                                    cursor: 'pointer',
                                                    transition: 'all 0.15s ease',
                                                    boxShadow: isChecked ? '0 1px 3px rgba(37,99,235,0.1)' : 'none',
                                                }}
                                            >
                                                <input
                                                    type="checkbox"
                                                    checked={isChecked}
                                                    onChange={(e) => {
                                                        const checked = e.target.checked;
                                                        setForm((prev) => {
                                                            const currentIds = prev.financial_account_ids || [];
                                                            if (checked) {
                                                                return {
                                                                    ...prev,
                                                                    financial_account_ids: currentIds.includes(accountIdStr) ? currentIds : [...currentIds, accountIdStr],
                                                                };
                                                            }
                                                            return {
                                                                ...prev,
                                                                financial_account_ids: currentIds.filter((id) => id !== accountIdStr),
                                                            };
                                                        });
                                                    }}
                                                    style={{ width: '18px', height: '18px', cursor: 'pointer', accentColor: '#2563eb' }}
                                                />
                                                <div style={{ display: 'flex', flexDirection: 'column' }}>
                                                    <span style={{ fontWeight: '600', fontSize: '13px', color: '#1e293b' }}>
                                                        {account.label || accountLabel(account)}
                                                    </span>
                                                    <span style={{ fontSize: '11px', color: '#64748b' }}>
                                                        {account.account_type || __('Account', 'manfi-expense-tracker')}
                                                    </span>
                                                </div>
                                            </label>
                                        );
                                    })}
                                </div>
                            )}

                            <div className="manfiet-field manfiet-mt-16">
                                <label className="manfiet-label" htmlFor="manfiet-payment-link">{__('Custom Payment / Checkout Link', 'manfi-expense-tracker')}</label>
                                <input
                                    id="manfiet-payment-link"
                                    type="url"
                                    className="manfiet-input"
                                    value={form.payment_link || ''}
                                    onChange={(e) => updateField('payment_link', e.target.value)}
                                    placeholder={__('e.g. https://buy.stripe.com/..., https://paypal.me/...', 'manfi-expense-tracker')}
                                />
                                <p className="manfiet-text-muted manfiet-mt-4">
                                    {__('Provide a direct hosted checkout or payment URL. A "Pay Invoice Online" button will be displayed on the public share page.', 'manfi-expense-tracker')}
                                </p>
                            </div>
                        </div>

                        <div className="manfiet-card manfiet-card-inset">
                            <div className="manfiet-card-head-row manfiet-mb-14">
                                <h4 className="manfiet-card-subtitle">
                                    {form.invoice_type === 'daily_rate'
                                        ? __('Campaigns & Daily Rates', 'manfi-expense-tracker')
                                        : form.invoice_type === 'hourly'
                                        ? __('Tasks & Hourly Rates', 'manfi-expense-tracker')
                                        : form.invoice_type === 'fixed'
                                        ? __('Milestones & Fixed Fees', 'manfi-expense-tracker')
                                        : __('Invoice Line Items / Services', 'manfi-expense-tracker')}
                                </h4>
                                <button type="button" className="manfiet-button manfiet-button-secondary manfiet-button-sm" onClick={addCampaign}>
                                    {__('+ Add Line Item', 'manfi-expense-tracker')}
                                </button>
                            </div>
                            <div className="manfiet-form-stack">
                                {form.campaigns.map((campaign, index) => {
                                    const amount = calculateCampaignAmount(campaign, form.invoice_type);
                                    const isDailyRate = form.invoice_type === 'daily_rate';
                                    const isHourly = form.invoice_type === 'hourly';
                                    const isFixed = form.invoice_type === 'fixed';
                                    return (
                                        <div key={campaign.id} className="manfiet-invoice-campaign-row">
                                            <div className="manfiet-form-grid">
                                                <div className="manfiet-field">
                                                    <label className="manfiet-label">{isFixed ? __('Milestone / Title', 'manfi-expense-tracker') : __('Item / Service Name', 'manfi-expense-tracker')}</label>
                                                    <input className="manfiet-input" value={campaign.name} onChange={(e) => updateCampaignField(index, 'name', e.target.value)} placeholder={__('Enter title or item name', 'manfi-expense-tracker')} />
                                                </div>
                                                <div className="manfiet-field">
                                                    <label className="manfiet-label">{isDailyRate ? __('Daily Budget ($)', 'manfi-expense-tracker') : isHourly ? __('Hourly Rate', 'manfi-expense-tracker') : isFixed ? __('Amount', 'manfi-expense-tracker') : __('Unit Price / Rate', 'manfi-expense-tracker')}</label>
                                                    <input type="number" min="0" step="0.01" className="manfiet-input" value={campaign.daily_budget} onChange={(e) => updateCampaignField(index, 'daily_budget', e.target.value)} placeholder="0.00" />
                                                </div>
                                                {!isFixed && (
                                                    <div className="manfiet-field">
                                                        <label className="manfiet-label">{isDailyRate ? __('Duration (Days)', 'manfi-expense-tracker') : isHourly ? __('Hours Worked', 'manfi-expense-tracker') : __('Quantity', 'manfi-expense-tracker')}</label>
                                                        <input type="number" min="0" step="0.1" className="manfiet-input" value={campaign.duration} onChange={(e) => updateCampaignField(index, 'duration', e.target.value)} placeholder="1" />
                                                    </div>
                                                )}
                                                <div className="manfiet-field">
                                                    <label className="manfiet-label">{isDailyRate ? __('Amount (USD)', 'manfi-expense-tracker') : __('Line Total', 'manfi-expense-tracker')}</label>
                                                    <input className="manfiet-input" value={isDailyRate ? `$${amount.toFixed(2)}` : formatMoneyCurrency(amount, form.currency)} readOnly style={{ fontWeight: '600', backgroundColor: '#f8fafc' }} />
                                                </div>
                                            </div>
                                            <div className="manfiet-invoice-campaign-actions">
                                                <input className="manfiet-input" placeholder={__('Short note or description for this item', 'manfi-expense-tracker')} value={campaign.description} onChange={(e) => updateCampaignField(index, 'description', e.target.value)} />
                                                <button type="button" className="manfiet-button manfiet-button-danger manfiet-button-sm" onClick={() => removeCampaign(index)} disabled={form.campaigns.length === 1}>{__('Remove', 'manfi-expense-tracker')}</button>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>

                        <div className="manfiet-invoice-summary-grid">
                            <div className="manfiet-card manfiet-card-inset">
                                <h4 className="manfiet-card-subtitle">{__('Totals Preview', 'manfi-expense-tracker')}</h4>
                                <div className="manfiet-summary-list">
                                    {form.invoice_type === 'daily_rate' ? (
                                        <>
                                            <div><span>{__('Subtotal (USD)', 'manfi-expense-tracker')}</span><strong>{formatMoney(totals.subtotalUsd)}</strong></div>
                                            {totals.adjustmentUsd !== 0 && (
                                                <div><span>{__('Adjustment (USD)', 'manfi-expense-tracker')}</span><strong style={{ color: totals.adjustmentUsd < 0 ? '#b91c1c' : '#15803d' }}>{totals.adjustmentUsd < 0 ? '− ' : '+ '}{formatMoney(Math.abs(totals.adjustmentUsd))}</strong></div>
                                            )}
                                            <div><span>{__('Subtotal (BDT)', 'manfi-expense-tracker')}</span><strong>{formatMoneyBdt(totals.subtotalBdt)}</strong></div>
                                        </>
                                    ) : (
                                        <div><span>{__('Subtotal', 'manfi-expense-tracker')}</span><strong>{formatMoneyCurrency(totals.subtotalBdt, form.currency)}</strong></div>
                                    )}
                                    <div>
                                        <span>
                                            {__('Discount', 'manfi-expense-tracker')}
                                            {form.discount_type === 'flat' ? ` (${__('Flat', 'manfi-expense-tracker')})` : ` (${totals.discountPct}%)`}
                                        </span>
                                        <strong style={{ color: totals.discountBdt > 0 ? '#15803d' : 'inherit' }}>
                                            {totals.discountBdt > 0 ? '− ' : ''}{formatMoneyCurrency(totals.discountBdt, form.currency)}
                                        </strong>
                                    </div>
                                    <div><span>{__('VAT', 'manfi-expense-tracker')}</span><strong>{formatMoneyCurrency(totals.vatBdt, form.currency)}</strong></div>
                                    {totals.adjustmentBdt !== 0 && (
                                        <div><span>{__('Adjustment', 'manfi-expense-tracker')}</span><strong style={{ color: totals.adjustmentBdt < 0 ? '#b91c1c' : '#15803d' }}>{totals.adjustmentBdt < 0 ? '− ' : '+ '}{formatMoneyCurrency(Math.abs(totals.adjustmentBdt), form.currency)}</strong></div>
                                    )}
                                    <div className="is-total"><span>{__('Grand Total', 'manfi-expense-tracker')}</span><strong>{formatMoneyCurrency(totals.grandTotal, form.currency)}</strong></div>
                                    {totals.previousDueAmount > 0 && (
                                        <div><span>{__('Previous Due', 'manfi-expense-tracker')}</span><strong>+ {formatMoneyCurrency(totals.previousDueAmount, form.currency)}</strong></div>
                                    )}
                                    <div><span>{__('Total Amount Due', 'manfi-expense-tracker')}</span><strong>{formatMoneyCurrency(totals.amountDue, form.currency)}</strong></div>
                                    <div><span>{__('Paid Amount', 'manfi-expense-tracker')}</span><strong style={{ color: '#15803d' }}>− {formatMoneyCurrency(totals.paymentReceivedAmount, form.currency)}</strong></div>
                                    {totals.overpaidAmount > 0 && (
                                        <div><span style={{ color: '#1e40af', fontWeight: '600' }}>{__('Overpaid / Refundable', 'manfi-expense-tracker')}</span><strong style={{ color: '#2563eb' }}>{formatMoneyCurrency(totals.overpaidAmount, form.currency)}</strong></div>
                                    )}
                                    <div className="is-total" style={{ borderTop: '2px solid #cbd5e1', paddingTop: '6px' }}><span>{__('Balance Due', 'manfi-expense-tracker')}</span><strong style={{ color: totals.balanceDue > 0 ? '#b91c1c' : '#15803d' }}>{formatMoneyCurrency(totals.balanceDue, form.currency)}</strong></div>
                                </div>
                                {form.payments && form.payments.length > 0 && (
                                    <div style={{ marginTop: '12px', paddingTop: '10px', borderTop: '1px dashed #cbd5e1', fontSize: '13px' }}>
                                        <strong style={{ display: 'block', marginBottom: '6px', color: '#334155' }}>{__('Payments Recorded:', 'manfi-expense-tracker')}</strong>
                                        {form.payments.map((p) => (
                                            <div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', color: '#475569', marginBottom: '4px', background: '#f8fafc', padding: '4px 8px', borderRadius: '4px', border: '1px solid #f1f5f9' }}>
                                                <span>{p.date || 'Payment'} &nbsp;<span className="manfiet-badge" style={{ background: '#e0f2fe', color: '#0369a1', padding: '1px 6px', borderRadius: '3px', fontSize: '11px', fontWeight: '500' }}>{p.method || 'bKash'}</span>{p.transaction_id ? <code> ({p.transaction_id})</code> : ''}</span>
                                                <strong style={{ color: '#15803d' }}>{formatMoneyBdt(p.amount)}</strong>
                                            </div>
                                        ))}
                                    </div>
                                )}
                                {shareUrl && (
                                    <p className="manfiet-invoice-link-box">
                                        <strong>{__('Share Link:', 'manfi-expense-tracker')}</strong> <a href={shareUrl} target="_blank" rel="noreferrer">{shareUrl}</a>
                                        <button type="button" className="manfiet-button manfiet-button-secondary manfiet-button-sm manfiet-ml-8" onClick={() => copyShareLink(shareUrl)}>{__('Copy Link', 'manfi-expense-tracker')}</button>
                                    </p>
                                )}
                            </div>

                            <div className="manfiet-card manfiet-card-inset">
                                <h4 className="manfiet-card-subtitle">{__('Save Invoice', 'manfi-expense-tracker')}</h4>
                                <div className="manfiet-form-row manfiet-form-row-end">
                                    {form.id && (
                                        <a href={`${restBase}invoices/${form.id}/pdf?token=${form.share_token}`} download className="manfiet-button manfiet-button-secondary">{__('Download PDF', 'manfi-expense-tracker')}</a>
                                    )}
                                    <button type="submit" className="manfiet-button manfiet-button-primary" disabled={saving}>{saving ? __('Saving...', 'manfi-expense-tracker') : (form.id ? __('Update Invoice', 'manfi-expense-tracker') : __('Create Invoice', 'manfi-expense-tracker'))}</button>
                                    <button type="button" className="manfiet-button manfiet-button-secondary" onClick={newInvoice}>{__('New Invoice', 'manfi-expense-tracker')}</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            )}

            {!isCreateMode && (<>
                <div className="manfiet-card manfiet-mb-16">
                    <div className="manfiet-card-head-row manfiet-mb-14">
                        <h3 className="manfiet-card-title manfiet-card-title-no-margin">{__('Invoice Report', 'manfi-expense-tracker')}</h3>
                    </div>
                    <div className="manfiet-invoice-report-grid">
                        <div>
                            <InvoiceChart monthly={dashboardStats.monthly || []} />
                        </div>
                        <div className="manfiet-report-side">
                            <div className="manfiet-summary-list">
                                <div><span>{__('Pending / Unpaid', 'manfi-expense-tracker')}</span><strong>{dashboardStats.summary.unpaidCount || 0}</strong></div>
                                <div><span>{__('Partial', 'manfi-expense-tracker')}</span><strong>{dashboardStats.summary.partialCount || 0}</strong></div>
                                <div><span>{__('Paid', 'manfi-expense-tracker')}</span><strong>{dashboardStats.summary.paidCount || 0}</strong></div>
                                <div><span>{__('Overdue', 'manfi-expense-tracker')}</span><strong>{dashboardStats.summary.overdueCount || 0}</strong></div>
                                <div><span>{__('Due Soon', 'manfi-expense-tracker')}</span><strong>{dashboardStats.summary.dueSoonCount || 0}</strong></div>
                            </div>
                            <p className="manfiet-text-muted">{__('Use the chart to track invoice volume and the table below to manage invoices that need follow-up.', 'manfi-expense-tracker')}</p>
                        </div>
                    </div>
                </div>

                <div className="manfiet-card">
                    <div className="manfiet-card-head-row manfiet-mb-14">
                        <h3 className="manfiet-card-title manfiet-card-title-no-margin">{__('Saved Invoices', 'manfi-expense-tracker')}</h3>
                    </div>
                    {loading ? (
                        <p>{__('Loading invoices...', 'manfi-expense-tracker')}</p>
                    ) : filteredInvoices.length === 0 ? (
                        <p className="manfiet-text-muted">{__('No invoices found in the selected range.', 'manfi-expense-tracker')}</p>
                    ) : (
                        <div className="manfiet-table-scroll">
                            <table className="manfiet-table">
                                <thead>
                                    <tr>
                                        <th>{__('Invoice', 'manfi-expense-tracker')}</th>
                                        <th>{__('Client', 'manfi-expense-tracker')}</th>
                                        <th>{__('Total', 'manfi-expense-tracker')}</th>
                                        <th>{__('Paid', 'manfi-expense-tracker')}</th>
                                        <th>{__('Due', 'manfi-expense-tracker')}</th>
                                        <th>{__('Status', 'manfi-expense-tracker')}</th>
                                        <th>{__('Link', 'manfi-expense-tracker')}</th>
                                        <th>{__('Actions', 'manfi-expense-tracker')}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {filteredInvoices.map((invoice) => (
                                        <tr key={invoice.id}>
                                            <td>{invoice.invoice_no}</td>
                                            <td>{invoice.client_name}</td>
                                            <td>{formatMoneyBdt(invoice.amount_due != null ? invoice.amount_due : (invoice.totals?.grand_total || 0))}</td>
                                            <td>{formatMoneyBdt(invoice.payment_received_amount || 0)}</td>
                                            <td>{formatMoneyBdt(invoice.balance_due ?? 0)}</td>
                                            <td><span className={`manfiet-pill manfiet-pill-${invoice.status || 'pending'}`}>{invoice.status || 'pending'}</span></td>
                                            <td><a href={invoice.share_url} target="_blank" rel="noreferrer">{__('Open', 'manfi-expense-tracker')}</a></td>
                                            <td>
                                                <button type="button" className="manfiet-button manfiet-button-primary manfiet-button-sm" onClick={() => openPaymentDialog(invoice)}>{__('Payment', 'manfi-expense-tracker')}</button>
                                                <button type="button" className="manfiet-button manfiet-button-info manfiet-button-sm" onClick={() => { window.location.href = buildAdminPageUrl('manfiet-invoice-create', invoice.id); }}>{__('Edit', 'manfi-expense-tracker')}</button>
                                                <button type="button" className="manfiet-button manfiet-button-secondary manfiet-button-sm manfiet-ml-8" onClick={() => copyShareLink(invoice.share_url)}>{__('Copy', 'manfi-expense-tracker')}</button>
                                                <button type="button" className="manfiet-button manfiet-button-danger manfiet-button-sm manfiet-ml-8" onClick={() => deleteInvoice(invoice)}>{__('Delete', 'manfi-expense-tracker')}</button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>
            </>)}

            {paymentInvoice && (
                <div className="manfiet-modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="manfiet-payment-modal-title">
                    <div className="manfiet-modal manfiet-modal-lg">
                        <h3 className="manfiet-modal-title" id="manfiet-payment-modal-title">{__('Record Payment', 'manfi-expense-tracker')}</h3>
                        <p className="manfiet-modal-text">
                            <strong>{paymentInvoice.invoice_no}</strong> - {paymentInvoice.client_name}
                            <br />
                            {__('Amount due:', 'manfi-expense-tracker')} <strong>{formatMoneyBdt(paymentInvoice.amount_due ?? paymentInvoice.totals?.grand_total ?? 0)}</strong> &nbsp;|&nbsp; {__('Already paid:', 'manfi-expense-tracker')} <strong>{formatMoneyBdt(paymentInvoice.payment_received_amount || 0)}</strong> &nbsp;|&nbsp; {__('Balance:', 'manfi-expense-tracker')} <strong style={{ color: paymentInvoice.balance_due > 0 ? '#d97706' : '#16a34a' }}>{formatMoneyBdt(paymentInvoice.balance_due ?? 0)}</strong>
                        </p>
                        {paymentError && <p className="manfiet-alert manfiet-alert-error">{paymentError}</p>}

                        <div className="manfiet-card manfiet-card-inset manfiet-mb-14" style={{ padding: '14px', background: '#f8fafc', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                            <h4 className="manfiet-card-subtitle" style={{ margin: '0 0 10px', fontSize: '15px' }}>{__('Add New Payment', 'manfi-expense-tracker')}</h4>
                            <div className="manfiet-form-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '10px' }}>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-payment-amount">{__('Payment Amount (৳)', 'manfi-expense-tracker')}</label>
                                    <input
                                        id="manfiet-payment-amount"
                                        type="number"
                                        min="0"
                                        step="0.01"
                                        className="manfiet-input"
                                        value={paymentAmount}
                                        onChange={(e) => setPaymentAmount(e.target.value)}
                                        placeholder="0.00"
                                    />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-payment-date">{__('Payment Date & Time', 'manfi-expense-tracker')}</label>
                                    <input
                                        id="manfiet-payment-date"
                                        type="datetime-local"
                                        className="manfiet-input"
                                        value={paymentDate}
                                        onChange={(e) => setPaymentDate(e.target.value)}
                                    />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-payment-method">{__('Payment Method', 'manfi-expense-tracker')}</label>
                                    <select
                                        id="manfiet-payment-method"
                                        className="manfiet-input"
                                        value={paymentMethod}
                                        onChange={(e) => setPaymentMethod(e.target.value)}
                                    >
                                        <option value="bKash">bKash</option>
                                        <option value="Nagad">Nagad</option>
                                        <option value="Rocket">Rocket</option>
                                        <option value="Bank Transfer">Bank Transfer</option>
                                        <option value="Cash">Cash</option>
                                        <option value="Card">Card</option>
                                        <option value="Other">Other (Custom)</option>
                                    </select>
                                </div>
                                {paymentMethod === 'Other' && (
                                    <div className="manfiet-field">
                                        <label className="manfiet-label" htmlFor="manfiet-custom-method">{__('Custom Method', 'manfi-expense-tracker')}</label>
                                        <input
                                            id="manfiet-custom-method"
                                            type="text"
                                            className="manfiet-input"
                                            value={customPaymentMethod}
                                            onChange={(e) => setCustomPaymentMethod(e.target.value)}
                                            placeholder="e.g. Wallet, Check"
                                        />
                                    </div>
                                )}
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-transaction-id">{__('Transaction ID / Reference', 'manfi-expense-tracker')}</label>
                                    <input
                                        id="manfiet-transaction-id"
                                        type="text"
                                        className="manfiet-input"
                                        value={transactionId}
                                        onChange={(e) => setTransactionId(e.target.value)}
                                        placeholder="e.g. TRX123456"
                                    />
                                </div>
                            </div>
                            <div className="manfiet-field manfiet-mt-8">
                                <label className="manfiet-label" htmlFor="manfiet-payment-note">{__('Payment Note (Optional)', 'manfi-expense-tracker')}</label>
                                <input
                                    id="manfiet-payment-note"
                                    type="text"
                                    className="manfiet-input"
                                    value={paymentNote}
                                    onChange={(e) => setPaymentNote(e.target.value)}
                                    placeholder="Optional note"
                                />
                            </div>
                            <div className="manfiet-mt-12" style={{ textAlign: 'right' }}>
                                <button type="button" className="manfiet-button manfiet-button-primary" onClick={submitPayment} disabled={paymentSaving}>
                                    {paymentSaving ? __('Saving...', 'manfi-expense-tracker') : __('+ Save Payment', 'manfi-expense-tracker')}
                                </button>
                            </div>
                        </div>

                        {paymentInvoice.payments && paymentInvoice.payments.length > 0 && (
                            <div className="manfiet-card manfiet-card-inset manfiet-mb-14" style={{ padding: '14px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                                <h4 className="manfiet-card-subtitle" style={{ margin: '0 0 10px', fontSize: '15px' }}>{__('Recorded Payments History', 'manfi-expense-tracker')}</h4>
                                <div className="manfiet-table-responsive" style={{ maxHeight: '220px', overflowY: 'auto' }}>
                                    <table className="manfiet-table manfiet-table-sm" style={{ width: '100%', fontSize: '13px' }}>
                                        <thead>
                                            <tr>
                                                <th>{__('Date & Time', 'manfi-expense-tracker')}</th>
                                                <th>{__('Method', 'manfi-expense-tracker')}</th>
                                                <th>{__('Trx ID', 'manfi-expense-tracker')}</th>
                                                <th>{__('Amount', 'manfi-expense-tracker')}</th>
                                                <th style={{ textAlign: 'right' }}>{__('Action', 'manfi-expense-tracker')}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {paymentInvoice.payments.map((item) => (
                                                <tr key={item.id}>
                                                    <td>{item.date || '-'}</td>
                                                    <td><span className="manfiet-badge" style={{ background: '#e0f2fe', color: '#0369a1', padding: '2px 8px', borderRadius: '4px', fontSize: '12px', fontWeight: '500' }}>{item.method || 'Default'}</span></td>
                                                    <td><code>{item.transaction_id || '-'}</code></td>
                                                    <td><strong>{formatMoneyBdt(item.amount)}</strong></td>
                                                    <td style={{ textAlign: 'right' }}>
                                                        <button
                                                            type="button"
                                                            className="manfiet-button manfiet-button-danger manfiet-button-sm"
                                                            onClick={() => deletePayment(paymentInvoice.id, item.id)}
                                                            disabled={paymentSaving}
                                                        >
                                                            {__('Delete', 'manfi-expense-tracker')}
                                                        </button>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        )}

                        <div className="manfiet-modal-actions manfiet-mt-16">
                            <button type="button" className="manfiet-button manfiet-button-secondary" onClick={closePaymentDialog} disabled={paymentSaving}>{__('Close', 'manfi-expense-tracker')}</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default InvoiceManager;
