// --- CONFIGURATION ---
const CONFIG = {
    companyDetails: {
        name: 'Josh Yenne',
        address: '203 Bettencourt St.\nSonoma, CA 95476',
        email: 'JoshYenne@me.com',
        phone: '707-332-6141',
        logo: ''
    },
    paymentInstructions: {
        title: 'Payment Instructions',
        methods: [
            { name: 'PayPal', details: 'JoshYenne@me.com', note: '(Please use Friends & Family to avoid fees, or add the percentage on top)' },
            { name: 'Venmo', details: '@Josh-Yenne', note: '' }
        ],
        otherMethods: 'Other methods accepted: Check, Cash, Cash App, Apple Pay.',
        preferred: 'Digital payment preferred.'
    },
    initialClients: [
        { id: 1, name: 'Wisdom Word', email: '', billingRate: 45, contactInfo: '', phone: '' },
        { id: 2, name: 'Sonoma Bookkeepers', email: '', billingRate: 45, contactInfo: '', phone: '' },
        { id: 3, name: 'Homespun Music', email: '', billingRate: 45, contactInfo: '', phone: '' }
    ]
};
// --- END CONFIGURATION ---

const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString + 'T00:00:00');
    return date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' });
};

const formatCurrency = (amount) => '$' + (parseFloat(amount) || 0).toFixed(2);

const App = () => {
    const [clients, setClients] = React.useState(() => {
        const saved = localStorage.getItem('clients');
        return saved ? JSON.parse(saved) : CONFIG.initialClients;
    });

    const clientMap = React.useMemo(() => {
        const map = new Map();
        for (const c of clients) {
            map.set(c.id, c);
        }
        return map;
    }, [clients]);

    const [company] = React.useState(CONFIG.companyDetails);
    const companyAddressLines = React.useMemo(() => company.address.split('\n'), [company.address]);
    const [client, setClient] = React.useState({ name: '', billingRate: 0, contactInfo: '', email: '' });
    const [invoice, setInvoice] = React.useState({ number: '1', startDate: new Date().toISOString().slice(0, 10), endDate: new Date().toISOString().slice(0, 10) });
    const [items, setItems] = React.useState([{ description: 'Computer & Web Work', quantity: 1, amount: 0 }]);
    const [isModalOpen, setIsModalOpen] = React.useState(false);
    const [editingClient, setEditingClient] = React.useState(null);
    const [isOneTimeClient, setIsOneTimeClient] = React.useState(false);
    const [isServiceEndDateVisible, setIsServiceEndDateVisible] = React.useState(true);

    React.useEffect(() => {
        localStorage.setItem('clients', JSON.stringify(clients));
    }, [clients]);

    React.useEffect(() => {
        setClient({ name: '', billingRate: 0, contactInfo: '', email: '' });
        setItems([{ description: 'Computer & Web Work', quantity: 1, amount: 0 }]);
    }, [isOneTimeClient]);

    const handleInvoiceChange = React.useCallback((e) => {
        const { name, value } = e.target;
        if (name === 'number') {
            if (value === '' || (/^[1-9][0-9]?$/.test(value) && parseInt(value, 10) < 100)) {
                setInvoice({ ...invoice, number: value });
            }
        } else {
            const newInvoice = { ...invoice, [name]: value };
            if (name === 'startDate' && !isServiceEndDateVisible) {
                newInvoice.endDate = value;
            }
            setInvoice(newInvoice);
        }
    }, [invoice, isServiceEndDateVisible]);

    const handleHideEndDate = React.useCallback(() => {
        setIsServiceEndDateVisible(false);
        setInvoice(prev => ({ ...prev, endDate: prev.startDate }));
    }, []);

    const handleClientSelect = React.useCallback((e) => {
        const selectedClientId = e.target.value;
        if (selectedClientId) {
            const selectedClient = clientMap.get(parseInt(selectedClientId));
            setClient(selectedClient);
            setItems([{ description: 'Computer & Web Work', quantity: 1, amount: parseFloat(selectedClient.billingRate) || 0 }]);
        } else {
            setClient({ name: '', billingRate: 0, contactInfo: '', email: '' });
            setItems([]);
        }
    }, [clientMap]);

    const handleOneTimeClientChange = React.useCallback((e) => {
        const { name, value } = e.target;
        setClient(prev => ({ ...prev, [name]: value }));
    }, []);

    const handleItemChange = React.useCallback((index, e) => {
        const newItems = [...items];
        const { name, value } = e.target;
        newItems[index][name] = (name === "quantity" || name === "amount") ? (parseFloat(value) || 0) : value;
        setItems(newItems);
    }, [items]);

    const handleAddWork = React.useCallback(() => {
        setItems([...items, { description: 'Computer & Web Work', quantity: 1, amount: parseFloat(client.billingRate) || 0 }]);
    }, [items, client.billingRate]);

    const handleRemoveItem = React.useCallback((index) => {
        const newItems = [...items];
        newItems.splice(index, 1);
        setItems(newItems);
    }, [items]);

    const handleResetClients = React.useCallback(() => {
        if (confirm('Are you sure you want to reset all client data to defaults?')) {
            setClients(CONFIG.initialClients);
            localStorage.removeItem('clients');
        }
    }, []);

    const handleClientFormChange = React.useCallback((e) => {
        const { name, value } = e.target;
        setEditingClient(prev => ({ ...prev, [name]: value }));
    }, []);

    const handleSaveClient = React.useCallback((e) => {
        e.preventDefault();
        if (editingClient.id) {
            setClients(prevClients => prevClients.map(c => c.id === editingClient.id ? editingClient : c));
        } else {
            const newClient = { ...editingClient, id: Date.now() };
            setClients(prevClients => [...prevClients, newClient]);
        }
        setEditingClient(null);
    }, [editingClient]);

    const handleDeleteClient = React.useCallback((id) => {
        if (confirm('Are you sure you want to delete this client?')) {
            setClients(prevClients => prevClients.filter(c => c.id !== id));
        }
    }, []);

    const total = React.useMemo(() => items.reduce((acc, item) => acc + ((parseFloat(item.quantity) || 0) * (parseFloat(item.amount) || 0)), 0), [items]);

    // Native jsPDF - no html2canvas
    const handleDownloadPdf = React.useCallback(() => {
        const pdf = new jspdf.jsPDF('p', 'mm', 'a4');
        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();
        const margin = 20;
        const contentWidth = pageWidth - (margin * 2);
        let y = margin;

        // Fonts
        // Helvetica is standard, close enough to Work Sans for PDF without embedding
        const addText = (text, x, currentY, opts = {}) => {
            const { fontSize = 10, fontStyle = 'normal', color = [30, 41, 59], align = 'left', maxWidth = null } = opts;
            pdf.setFontSize(fontSize);
            pdf.setFont('helvetica', fontStyle);
            pdf.setTextColor(...color);
            if (maxWidth) {
                const lines = pdf.splitTextToSize(String(text), maxWidth);
                pdf.text(lines, x, currentY, { align });
                return lines.length * (fontSize * 0.35);
            }
            pdf.text(String(text), x, currentY, { align });
            return fontSize * 0.35;
        };

        const drawLine = (x1, lineY, x2, color = [220, 220, 220]) => {
            pdf.setDrawColor(...color);
            pdf.setLineWidth(0.3);
            pdf.line(x1, lineY, x2, lineY);
        };

        // HEADER - Company logo and info left
        if (company.logo) {
            try {
                pdf.addImage(company.logo, 'PNG', margin, y, 30, 12);
                y += 15;
            } catch (e) {
                console.error('Error adding logo to PDF:', e);
            }
        }
        addText(company.name, margin, y, { fontSize: 14, color: [30, 41, 59] });
        y += 6;
        companyAddressLines.forEach(line => {
            addText(line, margin, y, { fontSize: 9, color: [30, 41, 59] });
            y += 4;
        });
        addText(company.email, margin, y, { fontSize: 9, color: [30, 41, 59] });
        y += 4;
        addText(company.phone, margin, y, { fontSize: 9, color: [30, 41, 59] });

        // HEADER - Invoice details right
        let rightY = margin;
        addText('INVOICE', pageWidth - margin, rightY, { fontSize: 24, color: [30, 41, 59], align: 'right' });
        rightY += 12;
        addText('Invoice #: ' + invoice.number, pageWidth - margin, rightY, { fontSize: 10, align: 'right', color: [30, 41, 59] });
        rightY += 6;
        const dateLabel = (isServiceEndDateVisible && invoice.startDate !== invoice.endDate)
            ? 'Service: ' + formatDate(invoice.startDate) + ' - ' + formatDate(invoice.endDate)
            : 'Service Date: ' + formatDate(invoice.startDate);
        addText(dateLabel, pageWidth - margin, rightY, { fontSize: 10, align: 'right', color: [30, 41, 59] });

        y = Math.max(y, rightY) + 15;

        // BILL TO
        drawLine(margin, y, pageWidth - margin);
        y += 8;
        addText('Bill To:', margin, y, { fontSize: 11, color: [30, 41, 59] });
        y += 6;

        if (client.name) {
            addText(client.name, margin, y, { fontSize: 11, color: [30, 41, 59] });
            y += 5;
            if (client.phone) {
                addText(client.phone, margin, y, { fontSize: 9, color: [30, 41, 59] });
                y += 4;
            }
            if (client.email) {
                addText(client.email, margin, y, { fontSize: 9, color: [30, 41, 59] });
                y += 4;
            }
            if (client.contactInfo) {
                client.contactInfo.split('\n').forEach(line => {
                    addText(line, margin, y, { fontSize: 9, color: [30, 41, 59] });
                    y += 4;
                });
            }
        } else {
            addText('(No client selected)', margin, y, { fontSize: 10, color: [156, 163, 175] });
        }
        y += 12;

        // LINE ITEMS TABLE
        const colDesc = margin;
        const colQty = pageWidth - margin - 70;
        const colRate = pageWidth - margin - 35;
        const colTotal = pageWidth - margin;

        // Table header
        // Simple minimal header
        drawLine(margin, y - 2, pageWidth - margin, [30, 41, 59]);
        y += 5;
        addText('Description', colDesc, y, { fontSize: 9, color: [30, 41, 59] });
        addText('Qty', colQty, y, { fontSize: 9, color: [30, 41, 59], align: 'center' });
        addText('Rate', colRate, y, { fontSize: 9, color: [30, 41, 59], align: 'right' });
        addText('Amount', colTotal, y, { fontSize: 9, color: [30, 41, 59], align: 'right' });
        y += 4;
        drawLine(margin, y, pageWidth - margin, [220, 220, 220]);
        y += 8;

        // Table rows
        items.forEach((item) => {
            if (y > pageHeight - 60) {
                pdf.addPage();
                y = margin;
            }
            const lineTotal = (parseFloat(item.quantity) || 0) * (parseFloat(item.amount) || 0);

            // Allow description to wrap
            const descLines = pdf.splitTextToSize(String(item.description || ''), colQty - colDesc - 10);
            const descHeight = descLines.length * 5;

            pdf.setFontSize(10);
            pdf.setTextColor(30, 41, 59);
            pdf.text(descLines, colDesc, y);

            addText(String(item.quantity || 0), colQty, y, { fontSize: 10, align: 'center', color: [30, 41, 59] });
            addText(formatCurrency(item.amount), colRate, y, { fontSize: 10, align: 'right', color: [30, 41, 59] });
            addText(formatCurrency(lineTotal), colTotal, y, { fontSize: 10, align: 'right', color: [30, 41, 59] });

            y += Math.max(8, descHeight + 4);
            drawLine(margin, y - 2, pageWidth - margin, [240, 240, 240]);
        });
        y += 4;

        // TOTAL
        // Minimal total section
        addText('Total', pageWidth - margin - 40, y + 4, { fontSize: 12, color: [30, 41, 59], align: 'right' });
        addText(formatCurrency(total), pageWidth - margin, y + 4, { fontSize: 16, color: [30, 41, 59], align: 'right' });
        y += 25;

        // PAYMENT INSTRUCTIONS
        if (y > pageHeight - 50) {
            pdf.addPage();
            y = margin;
        }

        addText(CONFIG.paymentInstructions.title, margin, y, { fontSize: 10, color: [30, 41, 59] });
        y += 6;

        // Payment columns - manually positioned
        const leftColX = margin;
        const rightColX = margin + 80; // Moved over to the right significantly

        // PayPal (first item)
        const method1 = CONFIG.paymentInstructions.methods[0];
        if (method1) {
            addText(method1.name, leftColX, y, { fontSize: 9, color: [30, 41, 59] });
            y += 4;
            addText(method1.details, leftColX, y, { fontSize: 9, color: [30, 41, 59] });
            if (method1.note) {
                // Note takes up full width if needed, or wraps in column
                const noteLines = pdf.splitTextToSize(method1.note, 75);
                y += 4;
                pdf.text(noteLines, leftColX, y);
                y += (noteLines.length * 3.5);
            }
        }

        // Venmo (second item, manually positioned right)
        // Reset Y to top of section for second column
        // We need to track max Y to move past afterwards
        let currentY = y;
        let startY = y - (method1.note ? (4 + (pdf.splitTextToSize(method1.note, 75).length * 3.5)) : 0) - 4; // Backtrack nicely

        // Actually simplest to just re-render or track. Let's just reset Y for the second col if we know it fits
        // But since we did sequential, let's just render the right col at the same start Y
        const method2 = CONFIG.paymentInstructions.methods[1];
        if (method2) {
            const rightY = startY;
            addText(method2.name, rightColX, rightY, { fontSize: 9, color: [30, 41, 59] });
            addText(method2.details, rightColX, rightY + 4, { fontSize: 9, color: [30, 41, 59] });
        }

        y = Math.max(y, startY + 25);
        addText(CONFIG.paymentInstructions.otherMethods, margin, y, { fontSize: 9, color: [30, 41, 59] });
        y += 5;
        addText(CONFIG.paymentInstructions.preferred, margin, y, { fontSize: 9, color: [30, 41, 59] });
        y += 12;
        addText('Thank you for your business!', pageWidth / 2, y, { fontSize: 10, align: 'center', color: [30, 41, 59] });

        pdf.save(`${client.name || 'Client'} Invoice ${invoice.startDate}.pdf`);
    }, [companyAddressLines, company, invoice, client, items, total, isServiceEndDateVisible]);

    return (
        <div className="min-h-screen bg-slate-50 text-slate-900 font-sans selection:bg-slate-200">
            <div className="max-w-4xl mx-auto px-4 py-8 sm:px-6 lg:px-8">
                {/* Top Action Bar */}
                <div className="flex justify-end gap-3 mb-8 no-print">
                    <button onClick={handleResetClients} className="text-slate-500 hover:text-slate-900 text-sm px-3 py-2 transition-colors">
                        Reset Data
                    </button>
                    <button onClick={() => setIsModalOpen(true)} className="bg-white border border-slate-300 text-slate-800 hover:bg-slate-50 py-2 px-4 rounded-md text-sm font-medium transition-colors">
                        Manage Clients
                    </button>
                    <button onClick={handleAddWork} className="bg-slate-900 hover:bg-slate-800 text-white py-2 px-4 rounded-md text-sm font-medium transition-colors">
                        + Add Item
                    </button>
                </div>

                <div className="bg-white rounded-xl shadow-xl border border-slate-200 overflow-hidden">
                    {/* Invoice Header */}
                    <div className="p-8 md:p-12 border-b border-slate-100">
                        <div className="flex flex-col md:flex-row justify-between items-start gap-8">
                            {/* Company Info */}
                            <div>
                                <h2 className="text-2xl font-bold text-slate-900 mb-1 tracking-tight">{company.name}</h2>
                                <div className="text-sm text-slate-500 space-y-0.5">
                                    {companyAddressLines.map((line, i) => (
                                        <div key={i}>{line}</div>
                                    ))}
                                    <div>{company.email}</div>
                                    <div>{company.phone}</div>
                                </div>
                            </div>

                            {/* Invoice Meta */}
                            <div className="w-full md:w-auto min-w-[200px]">
                                <div className="grid grid-cols-[1fr_auto] gap-y-2 gap-x-4 items-center">
                                    <label className="text-sm text-slate-500 text-right">Invoice #</label>
                                    <input type="number" name="number" value={invoice.number} onChange={handleInvoiceChange} className="w-24 text-right p-1.5 border-transparent hover:bg-slate-50 focus:bg-slate-50 focus:ring-0 rounded text-sm text-slate-900 font-medium transition-colors" placeholder="#" />

                                    <label className="text-sm text-slate-500 text-right">{isServiceEndDateVisible ? 'Start' : 'Date'}</label>
                                    <input type="date" name="startDate" value={invoice.startDate} onChange={handleInvoiceChange} className="w-36 p-1.5 border-transparent hover:bg-slate-50 focus:bg-slate-50 focus:ring-0 rounded text-sm text-slate-900 font-medium transition-colors" />

                                    {isServiceEndDateVisible && (
                                        <>
                                            <label className="text-sm text-slate-500 text-right">End</label>
                                            <div className="relative">
                                                <input type="date" name="endDate" value={invoice.endDate} onChange={handleInvoiceChange} className="w-36 p-1.5 border-transparent hover:bg-slate-50 focus:bg-slate-50 focus:ring-0 rounded text-sm text-slate-900 font-medium transition-colors" />
                                                <button onClick={handleHideEndDate} className="absolute -right-5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-red-500" title="Remove">×</button>
                                            </div>
                                        </>
                                    )}

                                    {!isServiceEndDateVisible && (
                                        <div className="col-span-2 text-right mt-1">
                                            <button onClick={() => setIsServiceEndDateVisible(true)} className="text-xs text-indigo-600 hover:text-indigo-800 transition-colors font-medium">+ Add end date</button>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Client Selection */}
                    <div className="px-8 md:px-12 py-6 border-b border-slate-100 bg-white">
                        <div className="flex items-center justify-between mb-4">
                            <h3 className="text-xs uppercase tracking-wider font-semibold text-slate-500">Bill To</h3>
                            <label className="flex items-center cursor-pointer group">
                                <input type="checkbox" checked={isOneTimeClient} onChange={(e) => setIsOneTimeClient(e.target.checked)} className="rounded border-slate-300 text-slate-900 focus:ring-slate-900 h-4 w-4" />
                                <span className="ml-2 text-sm text-slate-500 group-hover:text-slate-900 transition-colors">Manual Entry</span>
                            </label>
                        </div>

                        {isOneTimeClient ? (
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <input type="text" name="name" placeholder="Client Name" value={client.name} onChange={handleOneTimeClientChange} className="block w-full border-0 border-b border-slate-200 bg-transparent py-2 px-0 text-slate-900 placeholder:text-slate-400 focus:border-slate-900 focus:ring-0 text-sm font-medium transition-colors" />
                                <input type="email" name="email" placeholder="Email Address" value={client.email || ''} onChange={handleOneTimeClientChange} className="block w-full border-0 border-b border-slate-200 bg-transparent py-2 px-0 text-slate-900 placeholder:text-slate-400 focus:border-slate-900 focus:ring-0 text-sm transition-colors" />
                                <textarea name="contactInfo" placeholder="Client Address" value={client.contactInfo} onChange={handleOneTimeClientChange} className="col-span-1 md:col-span-2 block w-full border-0 border-b border-slate-200 bg-transparent py-2 px-0 text-slate-900 placeholder:text-slate-400 focus:border-slate-900 focus:ring-0 text-sm resize-none transition-colors" rows="2" />
                            </div>
                        ) : (
                            <div className="relative group">
                                <select onChange={handleClientSelect} className="block w-full appearance-none rounded-lg border-transparent bg-slate-50 py-3 px-4 pr-10 text-slate-900 focus:border-slate-300 focus:outline-none focus:ring-0 text-sm font-medium transition-colors cursor-pointer hover:bg-slate-100">
                                    <option value="">Select a client...</option>
                                    {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                                </select>
                                <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-4 text-slate-500 group-hover:text-slate-800 transition-colors">
                                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" /></svg>
                                </div>

                                {client.name && (
                                    <div className="mt-4 pl-1">
                                        <div className="text-sm text-slate-600 whitespace-pre-line leading-relaxed">
                                            {client.contactInfo}
                                            {client.phone && <div className="text-slate-500">{client.phone}</div>}
                                            {client.email && <div className="text-slate-500">{client.email}</div>}
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>

                    {/* Line Items */}
                    <div className="p-8 md:p-12">
                        <table className="min-w-full">
                            <thead>
                                <tr className="border-b border-slate-200">
                                    <th scope="col" className="py-3 text-left text-xs uppercase tracking-wider font-semibold text-slate-500">Description</th>
                                    <th scope="col" className="px-3 py-3 text-center text-xs uppercase tracking-wider font-semibold text-slate-500">Qty</th>
                                    <th scope="col" className="px-3 py-3 text-right text-xs uppercase tracking-wider font-semibold text-slate-500">Rate</th>
                                    <th scope="col" className="py-3 w-8"><span className="sr-only">Delete</span></th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {items.map((item, index) => (
                                    <tr key={index} className="group">
                                        <td className="py-4">
                                            <input type="text" name="description" value={item.description} onChange={(e) => handleItemChange(index, e)} className="w-full border-0 p-2 -ml-2 rounded bg-transparent hover:bg-slate-50 focus:bg-slate-50 text-slate-900 placeholder:text-slate-400 focus:ring-0 text-sm transition-colors" placeholder="Item description" />
                                        </td>
                                        <td className="px-3 py-4 text-center">
                                            <input type="number" step="0.5" name="quantity" value={item.quantity} onChange={(e) => handleItemChange(index, e)} className="w-16 mx-auto border-0 rounded p-2 bg-transparent hover:bg-slate-50 focus:bg-slate-50 text-center text-slate-900 focus:ring-0 text-sm transition-colors" />
                                        </td>
                                        <td className="px-3 py-4 text-right">
                                            <div className="flex items-center justify-end gap-1">
                                                <span className="text-slate-400 text-sm">$</span>
                                                <input type="number" step="0.01" name="amount" value={item.amount} onChange={(e) => handleItemChange(index, e)} className="w-20 text-right border-0 rounded p-2 bg-transparent hover:bg-slate-50 focus:bg-slate-50 text-slate-900 focus:ring-0 text-sm transition-colors" />
                                            </div>
                                        </td>
                                        <td className="py-4 pl-2 text-right">
                                            <button onClick={() => handleRemoveItem(index)} title="Remove item" className="text-slate-300 hover:text-red-500 transition-colors p-1">
                                                <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                                                    <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                                                </svg>
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colSpan="4" className="pt-8 text-right">
                                        <div className="flex justify-end items-center gap-6">
                                            <span className="text-sm font-medium text-slate-500 uppercase tracking-wider">Total</span>
                                            <span className="text-4xl font-bold text-slate-900 tracking-tight">{formatCurrency(total)}</span>
                                        </div>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    {/* Footer / Instructions */}
                    <div className="bg-white px-8 py-8 md:px-12 border-t border-slate-100">
                        <h4 className="text-xs uppercase tracking-wider font-semibold text-slate-500 mb-4">Payment Instructions</h4>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-12">
                            {CONFIG.paymentInstructions.methods.map((method, i) => (
                                <div key={i}>
                                    <div className="text-slate-900 text-sm font-medium">{method.name}</div>
                                    <div className="text-slate-600 text-sm mt-0.5">{method.details}</div>
                                    {method.note && <div className="text-xs text-slate-400 mt-1">{method.note}</div>}
                                </div>
                            ))}
                        </div>
                        <div className="mt-8 pt-6 border-t border-slate-100 text-center">
                            <p className="text-sm text-slate-500">{CONFIG.paymentInstructions.otherMethods}</p>
                            <p className="text-sm text-slate-500 mt-1">{CONFIG.paymentInstructions.preferred}</p>
                        </div>
                    </div>
                </div>

                {/* Main Action */}
                <div className="mt-12 text-center pb-12">
                    <button onClick={handleDownloadPdf} className="bg-slate-900 text-white hover:bg-black py-4 px-10 rounded-xl shadow-xl hover:shadow-2xl hover:-translate-y-0.5 transition-all duration-200 flex items-center gap-3 mx-auto text-lg font-medium">
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                        Download Invoice PDF
                    </button>
                </div>

                {/* Modals */}
                {isModalOpen && (
                    <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm flex items-center justify-center p-4 z-50">
                        <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col">
                            <div className="p-6 border-b border-slate-100 flex justify-between items-center bg-white">
                                <h2 className="text-lg font-semibold text-slate-900">Manage Clients</h2>
                                <button onClick={() => setIsModalOpen(false)} className="text-slate-400 hover:text-slate-900 transition-colors">
                                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" /></svg>
                                </button>
                            </div>

                            <div className="p-6 overflow-y-auto">
                                {!editingClient ? (
                                    <>
                                        <div className="mb-6">
                                            <button onClick={() => setEditingClient({ name: '', email: '', billingRate: 45, contactInfo: '', phone: '' })} className="w-full py-4 border-2 border-dashed border-slate-200 rounded-xl text-slate-500 hover:border-slate-900 hover:text-slate-900 transition-colors flex items-center justify-center gap-2 group">
                                                <span className="text-xl leading-none group-hover:scale-110 transition-transform">+</span> Add New Client
                                            </button>
                                        </div>
                                        <div className="space-y-3">
                                            {clients.map(c => (
                                                <div key={c.id} className="flex items-center justify-between p-4 bg-white border border-slate-100 rounded-lg hover:border-slate-300 transition-colors shadow-sm">
                                                    <div>
                                                        <div className="text-slate-900 font-medium">{c.name}</div>
                                                        <div className="text-sm text-slate-500 mt-0.5">${c.billingRate}/hr</div>
                                                    </div>
                                                    <div className="flex items-center gap-2">
                                                        <button onClick={() => setEditingClient(c)} className="p-2 text-slate-400 hover:text-slate-900 hover:bg-slate-50 rounded-md transition-colors">
                                                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" /></svg>
                                                        </button>
                                                        <button onClick={() => handleDeleteClient(c.id)} className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-md transition-colors">
                                                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                                                        </button>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    </>
                                ) : (
                                    <form onSubmit={handleSaveClient} className="space-y-4">
                                        <div>
                                            <label className="block text-sm font-medium text-slate-700 mb-1">Client Name</label>
                                            <input type="text" name="name" value={editingClient.name} onChange={handleClientFormChange} required className="block w-full rounded-md border-slate-300 shadow-sm focus:border-slate-900 focus:ring-slate-900 sm:text-sm" />
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-slate-700 mb-1">Email</label>
                                            <input type="email" name="email" value={editingClient.email || ''} onChange={handleClientFormChange} className="block w-full rounded-md border-slate-300 shadow-sm focus:border-slate-900 focus:ring-slate-900 sm:text-sm" />
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-slate-700 mb-1">Hourly Rate</label>
                                            <div className="relative">
                                                <span className="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-500">$</span>
                                                <input type="number" name="billingRate" value={editingClient.billingRate} onChange={handleClientFormChange} required className="block w-full pl-7 rounded-md border-slate-300 shadow-sm focus:border-slate-900 focus:ring-slate-900 sm:text-sm" />
                                            </div>
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-slate-700 mb-1">Phone (Optional)</label>
                                            <input type="tel" name="phone" value={editingClient.phone || ''} onChange={handleClientFormChange} className="block w-full rounded-md border-slate-300 shadow-sm focus:border-slate-900 focus:ring-slate-900 sm:text-sm" />
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-slate-700 mb-1">Address (Optional)</label>
                                            <textarea name="contactInfo" value={editingClient.contactInfo} onChange={handleClientFormChange} rows="3" className="block w-full rounded-md border-slate-300 shadow-sm focus:border-slate-900 focus:ring-slate-900 sm:text-sm" />
                                        </div>
                                        <div className="flex gap-3 pt-4 border-t border-slate-100 mt-6">
                                            <button type="button" onClick={() => setEditingClient(null)} className="flex-1 py-2 px-4 border border-slate-300 rounded-md shadow-sm text-sm font-medium text-slate-700 bg-white hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-500">Cancel</button>
                                            <button type="submit" className="flex-1 py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-slate-900 hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900">Save Client</button>
                                        </div>
                                    </form>
                                )}
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

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