/* ========== Invoices ========== */
function InvoicesView({ initialInvoiceId, onNav }) {
  const state = useStore();
  const [q, setQ] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [selectedId, setSelectedId] = useState(initialInvoiceId || null);
  const [showNew, setShowNew] = useState(false);

  useEffect(() => { if (initialInvoiceId) setSelectedId(initialInvoiceId); }, [initialInvoiceId]);

  const filtered = state.invoices.filter(inv => {
    if (statusFilter !== 'all' && inv.status !== statusFilter) return false;
    if (q) {
      const t = (inv.no + ' ' + customerName(inv.customerId)).toLowerCase();
      if (!t.includes(q.toLowerCase())) return false;
    }
    return true;
  });

  if (selectedId) {
    return <InvoiceDetail invoiceId={selectedId} onBack={() => setSelectedId(null)} onNav={onNav}/>;
  }

  return (
    <div>
      <div className="toolbar">
        <div className="search" style={{ flex: 1, maxWidth: 380 }}>
          <Icon name="search" size={14}/>
          <input
            type="text"
            placeholder="Search invoices…"
            value={q}
            onChange={e=>setQ(e.target.value)}
            style={{ width: '100%' }}
          />
        </div>
        <div className="filters">
          <select value={statusFilter} onChange={e=>setStatusFilter(e.target.value)}>
            <option value="all">All statuses</option>
            <option value="draft">Draft</option>
            <option value="sent">Sent</option>
            <option value="paid">Paid</option>
            <option value="void">Void</option>
          </select>
        </div>
        <div className="spacer"/>
        <button className="btn primary" onClick={() => setShowNew(true)}>
          <Icon name="plus" size={14}/> New invoice
        </button>
      </div>

      <div className="card">
        {filtered.length === 0 ? (
          <div className="empty"><h4>No invoices</h4></div>
        ) : (
          <table className="tbl">
            <thead>
              <tr>
                <th>No.</th>
                <th>Date</th>
                <th>Client</th>
                <th>Items</th>
                <th>Status</th>
                <th className="num">Total</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(inv => (
                <tr key={inv.id} className="clickable" onClick={() => setSelectedId(inv.id)}>
                  <td><span className="order-num">{inv.no}</span></td>
                  <td>{fmtDateShort(inv.date)}</td>
                  <td>{customerName(inv.customerId)}</td>
                  <td>{inv.items.length} item{inv.items.length === 1 ? '' : 's'}</td>
                  <td><span className={`badge ${inv.status === 'paid' ? 'green' : inv.status === 'sent' ? 'amber' : inv.status === 'void' ? 'red' : 'slate'}`}>{inv.status}</span></td>
                  <td className="num"><b>{fmtMoney(inv.total, inv.currency)}</b></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {showNew && <NewInvoiceModal onClose={() => setShowNew(false)} onCreated={(id) => { setShowNew(false); setSelectedId(id); }}/>}
    </div>
  );
}

/* ========== Invoice detail (with preview matching Prime format) ========== */
function InvoiceDetail({ invoiceId, onBack, onNav }) {
  const state = useStore();
  const inv = state.invoices.find(i => i.id === invoiceId);
  const [editing, setEditing] = useState(false);

  if (!inv) return <div className="empty"><h4>Invoice not found</h4><button className="btn" onClick={onBack}>← Back</button></div>;

  const cust = customerById(inv.customerId);

  const markStatus = (status) => {
    window.PVStore.updateInvoice(inv.id, { status });
  };

  return (
    <div>
      <button className="btn ghost" onClick={onBack} style={{ marginBottom: 14 }}>
        <Icon name="arrowLeft" size={14}/> Back to invoices
      </button>

      <div className="detail-head">
        <div className="h-left">
          <h1>Invoice {inv.no}</h1>
          <div className="h-meta">
            <span>{fmtDate(inv.date)}</span>
            <span>·</span>
            <span>{customerName(inv.customerId)}</span>
            <span>·</span>
            <span className={`badge ${inv.status === 'paid' ? 'green' : inv.status === 'sent' ? 'amber' : inv.status === 'void' ? 'red' : 'slate'}`}>{inv.status}</span>
          </div>
        </div>
        <div className="hstack">
          {inv.status === 'draft' && <button className="btn" onClick={() => markStatus('sent')}>Mark as sent</button>}
          {inv.status === 'sent' && <button className="btn primary" onClick={() => markStatus('paid')}><Icon name="check" size={13}/> Mark as paid</button>}
          {inv.status !== 'paid' && <button className="btn" onClick={() => setEditing(true)}><Icon name="edit" size={13}/> Edit</button>}
          <button className="btn" onClick={() => window.print()}><Icon name="print" size={13}/> Print</button>
        </div>
      </div>

      {inv.orderId && (
        <div style={{ marginBottom: 14, fontSize: 13 }}>
          <Icon name="link" size={13} style={{ verticalAlign: 'middle' }}/>{' '}
          Linked to order{' '}
          <a onClick={() => onNav('orders', { orderId: inv.orderId })} style={{ color: 'var(--navy-700)', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 2 }}>
            {state.orders.find(o => o.id === inv.orderId)?.orderNo}
          </a>
        </div>
      )}

      <InvoicePreview invoice={inv} business={state.business} customer={cust}/>

      {editing && <NewInvoiceModal invoice={inv} onClose={() => setEditing(false)} onCreated={() => setEditing(false)}/>}
    </div>
  );
}

/* ========== Prime-format invoice preview ========== */
function InvoicePreview({ invoice, business, customer }) {
  const d = new Date(invoice.date);
  const dateStr = `${String(d.getDate()).padStart(2,'0')}/${String(d.getMonth()+1).padStart(2,'0')}/${d.getFullYear()}`;
  const emptyRows = Math.max(0, 4 - invoice.items.length);
  return (
    <div className="invoice-preview" style={{ maxWidth: 800, margin: '0 auto' }}>
      <div className="iv-head">
        <div className="iv-biz">
          <b>{business.name}</b><br/>
          {business.address}<br/>
          {business.city}<br/>
          {business.phone}
        </div>
        <PrimeLogo size={64}/>
      </div>

      <h1 className="iv-title">Invoice</h1>

      <div className="iv-meta">
        <div><span className="lao">ວັນທີ</span><b>{dateStr}</b></div>
        <div><span className="lao">ເລກທີ</span><b>{invoice.no}</b></div>
      </div>

      <div className="iv-to">
        <div><b>To:</b></div>
        <div>{customer?.name || '—'}</div>
        <div><b>Address:</b></div>
        <div>{customer?.address || '—'}</div>
      </div>

      <table className="iv-items">
        <thead>
          <tr>
            <th style={{ width: 50 }}><span className="lao">ລຳດັບ</span></th>
            <th><span className="lao">ລາຍການ</span></th>
            <th style={{ width: 80 }}><span className="lao">ຈຳນວນ</span></th>
            <th style={{ width: 140 }}><span className="lao">ຈຳນວນເງິນ</span> ({invoice.currency})</th>
          </tr>
        </thead>
        <tbody>
          {invoice.items.map((it, i) => (
            <tr key={i}>
              <td className="idx">{i+1}</td>
              <td>{it.desc}</td>
              <td className="qty">{it.qty}</td>
              <td className="num amt">{fmtMoneyPlain(it.qty * it.price, invoice.currency)}</td>
            </tr>
          ))}
          {Array.from({ length: emptyRows }).map((_, i) => (
            <tr key={'e'+i} className="empty-row">
              <td className="idx"></td>
              <td></td>
              <td className="qty"></td>
              <td className="num amt"></td>
            </tr>
          ))}
          <tr className="sum">
            <td colSpan="2"></td>
            <td><span className="lao">ລວມ</span></td>
            <td className="num amt">{fmtMoneyPlain(invoice.subtotal, invoice.currency)}</td>
          </tr>
          <tr className="sum">
            <td colSpan="2"></td>
            <td><span className="lao">ສ່ວນຫຼຸດ</span></td>
            <td className="num amt">{fmtMoneyPlain(invoice.discount || 0, invoice.currency)}</td>
          </tr>
          <tr className="sum">
            <td></td>
            <td style={{ textAlign: 'center' }}><span className="lao">ລວມທັງໝົດ</span></td>
            <td></td>
            <td className="num amt"><b>{fmtMoneyPlain(invoice.total, invoice.currency)}</b></td>
          </tr>
        </tbody>
      </table>

      <div className="iv-note">
        <div className="lao"><b>ໝາຍເຫດ</b></div>
        <div className="lao">ລົງແປປາສາເອກະສານ / ບໍ່ສາມາດຄືນເງິນກໍລະນີລະບົບບໍ່ຜ່ານ</div>
      </div>

      <div className="iv-foot">
        <div className="iv-bank">
          <div style={{
            width: 96, height: 96, background: '#f0f0f0',
            border: '1px solid #ccc', display: 'grid', placeItems: 'center',
            fontSize: 9, color: '#999', marginBottom: 6
          }}>
            QR
          </div>
          <div><b>Account Name:</b> {business.accountName}</div>
          <div><b>Bank Name:</b> {business.bankName}</div>
          <div><b>Account No.:</b> LAK {business.accountLak}</div>
          <div style={{ paddingLeft: 70 }}>USD {business.accountUsd}</div>
        </div>
        <div className="iv-sig">
          <div className="sig-line"><span className="lao">ຜູ້ອອກໃບບິນ</span></div>
        </div>
      </div>
    </div>
  );
}

function fmtMoneyPlain(n, ccy='USD') {
  if (n == null || isNaN(n)) return '';
  if (ccy === 'LAK') return Math.round(n).toLocaleString('en-US');
  return Number(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

/* ========== New / edit invoice modal ========== */
function NewInvoiceModal({ invoice, fromOrder, onClose, onCreated }) {
  const state = useStore();
  const [form, setForm] = useState(() => {
    if (invoice) return { ...invoice, dateStr: new Date(invoice.date).toISOString().slice(0,10) };
    if (fromOrder) {
      return {
        customerId: fromOrder.customerId,
        currency: 'USD',
        dateStr: new Date().toISOString().slice(0,10),
        items: [{ desc: fromOrder.title + ` @${fromOrder.amount}*1`, qty: 1, price: fromOrder.amount }],
        discount: 0,
        status: 'draft',
        orderId: fromOrder.id,
      };
    }
    return {
      customerId: state.customers[0]?.id || '',
      currency: 'USD',
      dateStr: new Date().toISOString().slice(0,10),
      items: [{ desc: '', qty: 1, price: 0 }],
      discount: 0,
      status: 'draft',
    };
  });

  const subtotal = form.items.reduce((s,i)=>s+(parseFloat(i.qty)||0)*(parseFloat(i.price)||0), 0);
  const total = subtotal - (parseFloat(form.discount)||0);

  const updateItem = (i, patch) => {
    setForm(f => ({ ...f, items: f.items.map((it, j) => j===i ? {...it, ...patch} : it) }));
  };
  const addItem = () => setForm(f => ({ ...f, items: [...f.items, { desc: '', qty: 1, price: 0 }] }));
  const removeItem = (i) => setForm(f => ({ ...f, items: f.items.filter((_,j)=>j!==i) }));

  const handleSave = () => {
    if (!form.customerId) { alert('Please select a customer'); return; }
    const items = form.items
      .filter(i => i.desc.trim())
      .map(i => ({ desc: i.desc, qty: parseFloat(i.qty)||0, price: parseFloat(i.price)||0 }));
    if (items.length === 0) { alert('Add at least one item'); return; }
    const payload = {
      customerId: form.customerId,
      currency: form.currency,
      date: new Date(form.dateStr).getTime(),
      items,
      discount: parseFloat(form.discount) || 0,
      status: form.status || 'draft',
      orderId: form.orderId || null,
    };
    if (invoice) {
      window.PVStore.updateInvoice(invoice.id, payload);
      onCreated && onCreated(invoice.id);
    } else {
      const inv = window.PVStore.addInvoice(payload);
      onCreated && onCreated(inv.id);
    }
  };

  return (
    <Modal
      open
      onClose={onClose}
      title={invoice ? `Edit invoice ${invoice.no}` : 'New invoice'}
      size="lg"
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={handleSave}>{invoice ? 'Save changes' : 'Create invoice'}</button>
      </>}
    >
      <div className="row-gap">
        <div className="form-row three">
          <div className="field">
            <label>Customer</label>
            <select value={form.customerId} onChange={e=>setForm({...form, customerId: e.target.value})}>
              <option value="">— Select —</option>
              {state.customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>
          <div className="field">
            <label>Date</label>
            <input type="date" value={form.dateStr} onChange={e=>setForm({...form, dateStr: e.target.value})}/>
          </div>
          <div className="field">
            <label>Currency</label>
            <select value={form.currency} onChange={e=>setForm({...form, currency: e.target.value})}>
              <option value="USD">USD ($)</option>
              <option value="LAK">LAK (₭)</option>
              <option value="THB">THB (฿)</option>
            </select>
          </div>
        </div>

        <div>
          <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-700)', marginBottom: 6, display: 'block' }}>Line items</label>
          <div className="card" style={{ overflow: 'visible' }}>
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{ width: 40 }}>#</th>
                  <th>Description</th>
                  <th style={{ width: 80 }} className="num">Qty</th>
                  <th style={{ width: 110 }} className="num">Unit price</th>
                  <th style={{ width: 110 }} className="num">Amount</th>
                  <th style={{ width: 40 }}></th>
                </tr>
              </thead>
              <tbody>
                {form.items.map((it, i) => (
                  <tr key={i}>
                    <td>{i+1}</td>
                    <td>
                      <input
                        value={it.desc}
                        onChange={e=>updateItem(i, { desc: e.target.value })}
                        placeholder="e.g. New Zealand Visa @430*1"
                        style={{ width: '100%', padding: '6px 8px', border: '1px solid var(--ink-200)', borderRadius: 5, outline: 'none' }}
                      />
                    </td>
                    <td>
                      <input
                        type="number"
                        value={it.qty}
                        onChange={e=>updateItem(i, { qty: e.target.value })}
                        style={{ width: '100%', padding: '6px 8px', border: '1px solid var(--ink-200)', borderRadius: 5, outline: 'none', textAlign: 'right' }}
                      />
                    </td>
                    <td>
                      <input
                        type="number"
                        step="0.01"
                        value={it.price}
                        onChange={e=>updateItem(i, { price: e.target.value })}
                        style={{ width: '100%', padding: '6px 8px', border: '1px solid var(--ink-200)', borderRadius: 5, outline: 'none', textAlign: 'right' }}
                      />
                    </td>
                    <td className="num">{fmtMoneyPlain((parseFloat(it.qty)||0)*(parseFloat(it.price)||0), form.currency)}</td>
                    <td>
                      <button className="btn ghost icon" onClick={() => removeItem(i)} disabled={form.items.length===1}>
                        <Icon name="trash" size={12}/>
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <button className="btn ghost sm" onClick={addItem} style={{ marginTop: 8 }}>
            <Icon name="plus" size={12}/> Add line
          </button>
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <div style={{ minWidth: 280 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontSize: 13 }}>
              <span>Subtotal</span>
              <b>{fmtMoneyPlain(subtotal, form.currency)}</b>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0', fontSize: 13 }}>
              <span>Discount</span>
              <input
                type="number"
                step="0.01"
                value={form.discount}
                onChange={e=>setForm({...form, discount: e.target.value})}
                style={{ width: 100, padding: '4px 8px', border: '1px solid var(--ink-200)', borderRadius: 5, outline: 'none', textAlign: 'right' }}
              />
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderTop: '1px solid var(--ink-200)', marginTop: 4, fontSize: 16 }}>
              <b>Total</b>
              <b>{fmtMoneyPlain(total, form.currency)}</b>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
}

window.InvoicesView = InvoicesView;
window.InvoicePreview = InvoicePreview;
window.NewInvoiceModal = NewInvoiceModal;
window.fmtMoneyPlain = fmtMoneyPlain;
