// ════════════ INVOICE EDITOR · genuinely editable creator ════════════
// Replaces the old read-only InvoiceCreate. Recipient picked from the
// CRM, line items you can add / edit / remove with live totals, a
// products picker, editable tax / discount / terms, and real delivery
// fields. Exported as window.InvoiceEditor (used by the Money router).
const { Icon, Spark, Pex, Avatar, Card, Btn, Pill, Label, Num, Toggle } = window;

const PX_PRODUCTS = [
  { name: 'Sourdough bâtard · 24 ct', rate: 42 },
  { name: 'Baguette · 36 ct', rate: 38 },
  { name: 'Pain de mie · 8 loaves', rate: 32 },
  { name: 'Rye & caraway · 12 ct', rate: 48 },
  { name: 'Croissant · 6-pack', rate: 18 },
  { name: 'Delivery · local', rate: 25 },
  { name: 'Sourdough class · seat', rate: 80 },
];
const TERMS = [['receipt', 'Due on receipt', 0], ['net15', 'Net 15', 15], ['net30', 'Net 30', 30], ['net60', 'Net 60', 60]];
let __li = 0; const liId = () => 'li' + (++__li);
const fmt = (n) => '$' + (Number(n) || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const addDays = (label, d) => { const base = new Date(2025, 2, 12); base.setDate(base.getDate() + d); return base.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); };
const dueShort = (d) => { const base = new Date(2025, 2, 12); base.setDate(base.getDate() + d); return base.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); };

// Module-scope so React keeps the same component type across renders —
// defined inside InvoiceEditor it remounted on every keystroke and dropped focus.
function PaperIn(props) {
  const P = window.PX;
  const base = { border: 'none', borderBottom: '1px solid transparent', background: 'transparent', outline: 'none', fontFamily: P.sans, color: P.ink, fontSize: 13, padding: '3px 2px', width: '100%' };
  return <input {...props} style={{ ...base, ...(props.style || {}) }} onFocus={e => e.target.style.borderBottomColor = P.spark} onBlur={e => e.target.style.borderBottomColor = 'transparent'}/>;
}

window.InvoiceEditor = function InvoiceEditor() {
  const P = window.PX; const { go, toast, pexOpen, setPexOpen } = window.useApp();
  // Focused creation flow — give the document room (matches the original
  // moodboard: document + delivery panel, no competing Pex rail).
  React.useEffect(() => { const prev = pexOpen; if (prev) setPexOpen(false); return () => { if (prev) setPexOpen(true); }; }, []);
  const people = window.PEOPLE || [];
  const num = React.useMemo(() => window.PXInvoices.nextNumber(), []);
  const [recipient, setRecipient] = React.useState(people.find(p => p.id === 'marcus') || people[0] || null);
  const [items, setItems] = React.useState([
    { id: liId(), desc: 'Sourdough bâtard · 24 ct', qty: '15', rate: '42' },
    { id: liId(), desc: 'Baguette · 36 ct', qty: '10', rate: '38' },
    { id: liId(), desc: 'Pain de mie · 8 loaves', qty: '8', rate: '32' },
  ]);
  const [taxOn, setTaxOn] = React.useState(true);
  const [taxRate, setTaxRate] = React.useState('8.875');
  const [discountOn, setDiscountOn] = React.useState(false);
  const [discount, setDiscount] = React.useState('0');
  const [terms, setTerms] = React.useState('net30');
  const [subject, setSubject] = React.useState('Invoice #' + num + ' from Honest Loaves');
  const [message, setMessage] = React.useState("Hi — here's the invoice for your order. Everything's baking beautifully. Thanks, and let me know if anything's off. — Amara");
  const [opts, setOpts] = React.useState({ pdf: true, link: true, schedule: false, remind: true });
  const [pickRecip, setPickRecip] = React.useState(false);
  const [recipQ, setRecipQ] = React.useState('');
  const [pickProd, setPickProd] = React.useState(false);

  const termDays = (TERMS.find(t => t[0] === terms) || TERMS[2])[2];
  const subtotal = items.reduce((a, it) => a + (parseFloat(it.qty) || 0) * (parseFloat(it.rate) || 0), 0);
  const discAmt = discountOn ? (parseFloat(discount) || 0) : 0;
  const taxable = Math.max(0, subtotal - discAmt);
  const taxAmt = taxOn ? taxable * (parseFloat(taxRate) || 0) / 100 : 0;
  const total = taxable + taxAmt;

  const setItem = (id, k, v) => setItems(its => its.map(it => it.id === id ? { ...it, [k]: v } : it));
  const addItem = (p) => { setItems(its => [...its, p ? { id: liId(), desc: p.name, qty: '1', rate: String(p.rate) } : { id: liId(), desc: '', qty: '1', rate: '' }]); setPickProd(false); };
  const removeItem = (id) => setItems(its => its.filter(it => it.id !== id));

  const buildRecord = (status) => ({
    id: num,
    who: recipient ? recipient.name : 'No customer yet',
    contact: recipient ? recipient.id : null,
    email: recipient ? recipient.email : '',
    addr: (recipient && recipient.addr) || '',
    amt: Math.round(total * 100) / 100,
    status, date: 'Mar 12', due: dueShort(termDays), terms,
    items: items.map(it => ({ desc: it.desc || 'Item', qty: parseFloat(it.qty) || 0, rate: parseFloat(it.rate) || 0 })),
    subtotal: Math.round(subtotal * 100) / 100,
    discount: Math.round(discAmt * 100) / 100,
    taxRate: taxOn ? (parseFloat(taxRate) || 0) : 0,
    tax: Math.round(taxAmt * 100) / 100,
    subject, message, opts: { ...opts },
    timeline: status === 'draft'
      ? [{ t: 'Created', d: 'Today', icon: 'check' }]
      : [{ t: 'Created', d: 'Today', icon: 'check' }, { t: `Sent to ${recipient ? recipient.name : '—'}`, d: 'Today', icon: 'send' }],
  });

  const send = () => {
    if (!recipient) { setPickRecip(true); toast('Pick a customer to bill first.', { tone: 'rose', icon: 'alert' }); return; }
    if (!items.length || subtotal <= 0) { toast('Add at least one line item with a price.', { tone: 'rose', icon: 'alert' }); return; }
    window.PXInvoices.add(buildRecord('sent'));
    toast(`Invoice #${num} sent to ${recipient.name} · ${fmt(total)}.`, { tone: 'sage', icon: 'check' });
    go('money/invoices');
  };
  const saveDraft = () => {
    window.PXInvoices.add(buildRecord('draft'));
    toast(`Draft #${num} saved.`, { icon: 'check' });
    go('money/invoices');
  };

  const filtered = people.filter(p => !recipQ || (p.name + ' ' + p.co).toLowerCase().includes(recipQ.toLowerCase()));

  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      {/* action bar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
        <Btn kind="ghost" size="sm" icon="chevL" onClick={() => go('money/invoices')}>Cancel</Btn>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 24, color: P.ink, lineHeight: 1.1, whiteSpace: 'nowrap' }}>New invoice</div>
          <div style={{ fontSize: 11.5, color: P.ink3 }}>{recipient ? `For ${recipient.name}` : 'Choose a customer to bill'}</div>
        </div>
        <Pill tone="neutral">Draft</Pill>
        <Btn kind="default" size="sm" onClick={saveDraft}>Save draft</Btn>
        <Btn kind="default" size="sm" icon="download" onClick={() => toast('Invoice PDF generated.', { icon: 'download' })}>Preview PDF</Btn>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 324px', gap: 20, alignItems: 'start' }}>
        {/* ── the editable invoice document ── */}
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div style={{ width: '100%', maxWidth: 660, background: '#fff', borderRadius: 6, boxShadow: P.shLg, padding: 44, border: `1px solid ${P.line}` }}>
            {/* head */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', paddingBottom: 22, borderBottom: `2px solid ${P.ink}` }}>
              <div>
                <div style={{ width: 40, height: 40, background: '#3A2A1C', borderRadius: 7, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontFamily: P.serif, color: '#F5D8A8', fontSize: 21, fontStyle: 'italic', marginBottom: 10 }}>hl</div>
                <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 25, color: P.ink, letterSpacing: -0.5, lineHeight: 1, whiteSpace: 'nowrap' }}>Honest Loaves</div>
                <div style={{ fontSize: 11, color: P.ink3, marginTop: 4, lineHeight: 1.5 }}>241 Metropolitan Ave<br/>Brooklyn, NY 11211<br/>amara@honestloaves.com</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <Label>Invoice</Label>
                <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 32, color: P.ink, lineHeight: 1 }}>#{num}</div>
                <div style={{ fontSize: 11, color: P.ink3, marginTop: 8 }}>Issued <b style={{ color: P.ink }}>Mar 12, 2025</b></div>
                <div style={{ fontSize: 11, color: P.ink3 }}>Due <b style={{ color: P.ink }}>{addDays('', termDays)}</b></div>
              </div>
            </div>

            {/* bill to — recipient picker */}
            <div style={{ padding: '18px 0', borderBottom: `1px solid ${P.line}`, position: 'relative' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                <Label>Bill to</Label>
                <span onClick={() => setPickRecip(v => !v)} style={{ fontSize: 11, color: P.spark, cursor: 'pointer', fontWeight: 500 }}>{recipient ? 'Change' : 'Choose customer'}</span>
              </div>
              {recipient ? (
                <>
                  <div style={{ fontSize: 14, fontWeight: 600, color: P.ink }}>{recipient.name}{recipient.co && recipient.co !== '—' ? ` · ${recipient.co}` : ''}</div>
                  <div style={{ fontSize: 11.5, color: P.ink3, marginTop: 2 }}>{recipient.email}</div>
                </>
              ) : (
                <div onClick={() => setPickRecip(true)} style={{ fontSize: 13, color: P.ink3, cursor: 'pointer', padding: '6px 0' }}>+ Select a customer from your CRM</div>
              )}
              {pickRecip && (
                <div style={{ position: 'absolute', top: 56, left: 0, width: 320, background: P.card, border: `1px solid ${P.line}`, borderRadius: 12, boxShadow: P.shPop, zIndex: 20, overflow: 'hidden' }}>
                  <div style={{ padding: 10, borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Icon name="search" size={15} color={P.ink3}/>
                    <input autoFocus value={recipQ} onChange={e => setRecipQ(e.target.value)} placeholder="Search contacts…" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 13, color: P.ink, fontFamily: P.sans }}/>
                  </div>
                  <div style={{ maxHeight: 240, overflow: 'auto' }}>
                    {filtered.map(p => (
                      <div key={p.id} onClick={() => { setRecipient(p); setPickRecip(false); setRecipQ(''); }} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', cursor: 'pointer' }}
                        onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                        <Avatar name={p.name} size={28}/>
                        <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13, color: P.ink, fontWeight: 500 }}>{p.name}</div><div style={{ fontSize: 11, color: P.ink3 }}>{p.co !== '—' ? p.co + ' · ' : ''}{p.email}</div></div>
                      </div>
                    ))}
                    {filtered.length === 0 && <div style={{ padding: 14, fontSize: 12.5, color: P.ink3, textAlign: 'center' }}>No matches.</div>}
                  </div>
                  <div style={{ padding: 8, borderTop: `1px solid ${P.line}` }}><Btn kind="ghost" size="sm" icon="plus" full onClick={() => { toast('Add-contact form would open here.', { icon: 'userPlus' }); }}>New customer</Btn></div>
                </div>
              )}
            </div>

            {/* line items header */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 64px 84px 90px 22px', gap: 8, padding: '12px 0 8px', borderBottom: `1px solid ${P.line}` }}>
              {['Item', 'Qty', 'Rate', 'Amount', ''].map((h, i) => <Label key={i} style={{ textAlign: i >= 1 && i <= 3 ? 'right' : 'left' }}>{h}</Label>)}
            </div>
            {/* line item rows (editable) */}
            {items.map((it) => {
              const amt = (parseFloat(it.qty) || 0) * (parseFloat(it.rate) || 0);
              return (
                <div key={it.id} style={{ display: 'grid', gridTemplateColumns: '1fr 64px 84px 90px 22px', gap: 8, padding: '7px 0', borderBottom: `1px solid ${P.line}`, alignItems: 'center' }}>
                  <PaperIn value={it.desc} placeholder="Description" onChange={e => setItem(it.id, 'desc', e.target.value)}/>
                  <PaperIn value={it.qty} onChange={e => setItem(it.id, 'qty', e.target.value.replace(/[^0-9.]/g, ''))} style={{ textAlign: 'right', fontFamily: P.mono, fontSize: 12.5 }}/>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                    <span style={{ fontSize: 12.5, color: P.ink3 }}>$</span>
                    <PaperIn value={it.rate} onChange={e => setItem(it.id, 'rate', e.target.value.replace(/[^0-9.]/g, ''))} style={{ textAlign: 'right', fontFamily: P.mono, fontSize: 12.5, width: 60 }}/>
                  </div>
                  <span style={{ textAlign: 'right', fontFamily: P.mono, fontSize: 12.5, color: P.ink }}>{fmt(amt)}</span>
                  <span onClick={() => removeItem(it.id)} title="Remove" style={{ display: 'flex', justifyContent: 'center', color: P.ink4, cursor: 'pointer' }} onMouseEnter={e => e.currentTarget.style.color = P.rose} onMouseLeave={e => e.currentTarget.style.color = P.ink4}><Icon name="x" size={14}/></span>
                </div>
              );
            })}

            {/* add line item / from products */}
            <div style={{ display: 'flex', gap: 14, padding: '10px 0', position: 'relative' }}>
              <span onClick={() => addItem()} style={{ fontSize: 12.5, color: P.spark, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="plus" size={14}/>Add line item</span>
              <span onClick={() => setPickProd(v => !v)} style={{ fontSize: 12.5, color: P.ink2, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="tag" size={14}/>From products</span>
              {pickProd && (
                <div style={{ position: 'absolute', top: 36, left: 90, width: 280, background: P.card, border: `1px solid ${P.line}`, borderRadius: 12, boxShadow: P.shPop, zIndex: 20, overflow: 'hidden' }}>
                  <Label style={{ padding: '10px 12px 4px' }}>Products &amp; prices</Label>
                  <div style={{ maxHeight: 220, overflow: 'auto', paddingBottom: 6 }}>
                    {PX_PRODUCTS.map((p, i) => (
                      <div key={i} onClick={() => addItem(p)} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', cursor: 'pointer' }}
                        onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                        <span style={{ flex: 1, fontSize: 12.5, color: P.ink }}>{p.name}</span><span style={{ fontFamily: P.mono, fontSize: 12, color: P.ink3 }}>{fmt(p.rate)}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* totals */}
            <div style={{ display: 'flex', justifyContent: 'flex-end', paddingTop: 8 }}>
              <div style={{ width: 260 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: P.ink3, padding: '4px 0' }}><span>Subtotal</span><span style={{ fontFamily: P.mono }}>{fmt(subtotal)}</span></div>
                {/* discount */}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12.5, color: P.ink3, padding: '4px 0' }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Toggle on={discountOn} size="sm" onClick={() => setDiscountOn(v => !v)}/>Discount</span>
                  {discountOn ? <span style={{ display: 'flex', alignItems: 'center' }}><span>−$</span><PaperIn value={discount} onChange={e => setDiscount(e.target.value.replace(/[^0-9.]/g, ''))} style={{ width: 56, textAlign: 'right', fontFamily: P.mono, fontSize: 12.5 }}/></span> : <span style={{ color: P.ink4 }}>—</span>}
                </div>
                {/* tax */}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12.5, color: P.ink3, padding: '4px 0' }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Toggle on={taxOn} size="sm" onClick={() => setTaxOn(v => !v)}/>Tax
                    {taxOn && <span style={{ display: 'flex', alignItems: 'center' }}><PaperIn value={taxRate} onChange={e => setTaxRate(e.target.value.replace(/[^0-9.]/g, ''))} style={{ width: 44, textAlign: 'right', fontFamily: P.mono, fontSize: 12 }}/><span>%</span></span>}
                  </span>
                  <span style={{ fontFamily: P.mono }}>{taxOn ? fmt(taxAmt) : '—'}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', paddingTop: 9, borderTop: `1px solid ${P.line}`, marginTop: 5 }}><span style={{ fontSize: 13, fontWeight: 600, color: P.ink }}>Total due</span><Num size={22}>{fmt(total)}</Num></div>
              </div>
            </div>

            {/* terms */}
            <div style={{ marginTop: 18, paddingTop: 14, borderTop: `1px solid ${P.line}`, display: 'flex', alignItems: 'center', gap: 10 }}>
              <Label>Terms</Label>
              <div style={{ display: 'flex', gap: 4, background: P.sunk, borderRadius: 8, padding: 3 }}>
                {TERMS.map(t => {
                  const on = terms === t[0];
                  return <span key={t[0]} onClick={() => setTerms(t[0])} style={{ padding: '4px 10px', borderRadius: 6, fontSize: 11.5, fontWeight: 600, cursor: 'pointer', background: on ? P.card : 'transparent', boxShadow: on ? P.shSm : 'none', color: on ? P.ink : P.ink3 }}>{t[1]}</span>;
                })}
              </div>
            </div>
          </div>
        </div>

        {/* ── delivery panel ── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card pad={16}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: P.ink, marginBottom: 12 }}>Delivery</div>
            <Label style={{ marginBottom: 5 }}>To</Label>
            <div style={{ padding: '8px 10px', background: P.sunk, borderRadius: 8, border: `1px solid ${P.line}`, fontSize: 12.5, color: recipient ? P.ink : P.ink3, marginBottom: 11 }}>{recipient ? recipient.email : 'Pick a customer first'}</div>
            <Label style={{ marginBottom: 5 }}>Subject</Label>
            <input value={subject} onChange={e => setSubject(e.target.value)} style={{ width: '100%', padding: '8px 10px', background: P.card, borderRadius: 8, border: `1px solid ${P.line}`, fontSize: 12.5, color: P.ink, marginBottom: 11, fontFamily: P.sans, outline: 'none' }}/>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 5 }}><Label>Message</Label><span style={{ fontSize: 10.5, color: P.spark, display: 'inline-flex', alignItems: 'center', gap: 3 }}><Spark size={9}/>Pex drafted</span></div>
            <textarea value={message} onChange={e => setMessage(e.target.value)} rows={4} style={{ width: '100%', resize: 'vertical', padding: 10, background: P.sparkWash, border: `1px solid ${P.sparkTint}`, borderRadius: 8, fontSize: 12.5, color: P.ink2, lineHeight: 1.5, fontFamily: P.sans, outline: 'none' }}/>
          </Card>

          <Card pad={16}>
            <Label style={{ marginBottom: 10 }}>Options</Label>
            {[['pdf', 'Attach PDF'], ['link', 'Include payment link (Stripe)'], ['schedule', 'Schedule send'], ['remind', 'Auto-remind at d+7, d+14']].map((o, i) => (
              <div key={o[0]} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: i < 3 ? `1px solid ${P.line}` : 'none' }}>
                <span style={{ flex: 1, fontSize: 12.5, color: P.ink }}>{o[1]}</span><Toggle on={opts[o[0]]} size="sm" onClick={() => setOpts(s => ({ ...s, [o[0]]: !s[o[0]] }))}/>
              </div>
            ))}
          </Card>

          <Card pad={14} style={{ background: P.sageWash, border: `1px solid ${P.sageTint}` }}>
            <div style={{ fontSize: 12, color: P.ink2, lineHeight: 1.5 }}><b style={{ color: P.ink }}>Pex tip:</b> new cafés pay ~40% faster on Net 15. Want me to switch the terms?</div>
            <Btn kind="default" size="sm" full style={{ marginTop: 10 }} onClick={() => setTerms('net15')}>Apply Net 15</Btn>
          </Card>

          <Btn kind="spark" size="lg" full icon="send" onClick={send}>Send invoice · {fmt(total)}</Btn>
          <div style={{ fontSize: 10.5, color: P.ink3, textAlign: 'center', marginTop: -4 }}>Free · no Sparks charged</div>
        </div>
      </div>
    </div>
  );
};
