// ════════════ ORDERS · order management & fulfillment ════════════
// Own secondary sidebar (like Marketing/Money). Covers the full surface:
// order lifecycle tracking (Cart → Quote → Production → Shipped →
// Delivered), product mockup previews, supplier/managed-service partners,
// and quotes awaiting customer approval. Local state only — this is a
// visual prototype, nothing here talks to a backend.
const { Icon, Spark, Pex, Avatar, Card, Btn, Pill, Label, Num, Toggle, Field, Select, TextArea, Tabs, money } = window;

// ── Shared lifecycle model ─────────────────────────────────────
const STAGES = [
  { k: 'cart', label: 'Cart', icon: 'bag', tone: 'neutral' },
  { k: 'quote_requested', label: 'Quote requested', icon: 'fileText', tone: 'amber' },
  { k: 'quote_approved', label: 'Quote approved', icon: 'check', tone: 'sky' },
  { k: 'in_production', label: 'In production', icon: 'settings', tone: 'spark' },
  { k: 'shipped', label: 'Shipped', icon: 'truck', tone: 'plum' },
  { k: 'delivered', label: 'Delivered', icon: 'package', tone: 'sage' },
];

const ORDER_SEED = [
  { id: 'ORD-1042', customer: 'Daniel Reyes', company: 'Reyes Coffee Roasters', email: 'daniel@reyescoffee.com', stage: 4, items: [{ n: 'Custom tote bag', qty: 150, price: 6.2 }], updated: '2h ago' },
  { id: 'ORD-1041', customer: 'Priya Shah', company: '—', email: 'priya.shah@gmail.com', stage: 3, items: [{ n: 'Ceramic mug · 12oz', qty: 75, price: 8.4 }], updated: '5h ago' },
  { id: 'ORD-1038', customer: 'Marcus Tran', company: 'Tran & Co. Café', email: 'marcus@trancafe.com', stage: 5, items: [{ n: 'Kraft mailer box', qty: 300, price: 1.85 }, { n: 'Interior tissue print', qty: 300, price: 0.35 }], updated: '1 day ago' },
  { id: 'ORD-1035', customer: 'Amara Okafor', company: '—', email: 'amara.ok@gmail.com', stage: 2, items: [{ n: 'Custom tote bag', qty: 40, price: 6.8 }], updated: '2 days ago' },
  { id: 'ORD-1030', customer: 'Lena Fischer', company: 'Fischer Design Studio', email: 'lena@fischerdesign.co', stage: 1, items: [{ n: 'Ceramic mug · 12oz', qty: 120, price: 7.9 }], updated: '3 days ago' },
  { id: 'ORD-1022', customer: 'James Okoye', company: '—', email: 'jokoye@outlook.com', stage: 0, items: [{ n: 'Kraft mailer box', qty: 80, price: 2.1 }], updated: '4 days ago' },
  { id: 'ORD-1015', customer: 'Sofia Martins', company: 'Martins Retail Co.', email: 'sofia@martinsretail.com', stage: 5, items: [{ n: 'Custom tote bag', qty: 220, price: 5.9 }], updated: '6 days ago' },
  { id: 'ORD-1008', customer: 'Ben Carter', company: '—', email: 'ben.carter@icloud.com', stage: 5, items: [{ n: 'Ceramic mug · 12oz', qty: 50, price: 9.2 }], updated: '9 days ago' },
];

const SUPPLIERS = [
  { id: 's1', name: 'Brightline Print Co.', spec: 'Apparel & tote printing', turnaround: '5–7 days', status: 'active', email: 'orders@brightlineprint.com', phone: '(718) 555-0142', activeOrders: 3, notes: 'Reliable for rush apparel runs — ask for the matte finish upgrade, no extra charge over 50 units.' },
  { id: 's2', name: 'Cobalt Ceramics', spec: 'Mugs & drinkware', turnaround: '10–14 days', status: 'active', email: 'hello@cobaltceramics.co', phone: '(347) 555-0198', activeOrders: 1, notes: 'Best unit price above a 250pc minimum. Runs slower during the Nov–Dec holiday rush.' },
  { id: 's3', name: 'Anchor Packaging', spec: 'Custom boxes & mailers', turnaround: '3–5 days', status: 'active', email: 'fulfillment@anchorpkg.com', phone: '(212) 555-0110', activeOrders: 2, notes: 'Fastest turnaround of the group — good default for time-sensitive orders.' },
  { id: 's4', name: 'Northside Embroidery', spec: 'Embroidered goods', turnaround: '14–21 days', status: 'paused', email: 'studio@northsideembro.com', phone: '(929) 555-0176', activeOrders: 0, notes: 'Paused for the season — resumes bookings in March.' },
];

const QUOTE_SEED = [
  { id: 'q1', customer: 'Daniel Reyes', company: 'Reyes Coffee Roasters', items: [{ n: 'Custom tote bag', qty: 150, price: 6.2 }, { n: 'Screen print setup', qty: 1, price: 65 }], sent: '2 days ago', status: 'pending' },
  { id: 'q2', customer: 'Priya Shah', company: '—', items: [{ n: 'Ceramic mug · 12oz', qty: 75, price: 8.4 }], sent: 'Yesterday', status: 'pending' },
  { id: 'q3', customer: 'Marcus Tran', company: 'Tran & Co. Café', items: [{ n: 'Kraft mailer box', qty: 300, price: 1.85 }, { n: 'Interior tissue print', qty: 300, price: 0.35 }], sent: '4 days ago', status: 'pending' },
  { id: 'q4', customer: 'Sofia Martins', company: 'Martins Retail Co.', items: [{ n: 'Custom tote bag', qty: 220, price: 5.9 }], sent: '6 days ago', status: 'approved' },
  { id: 'q5', customer: 'Ben Carter', company: '—', items: [{ n: 'Ceramic mug · 12oz', qty: 50, price: 9.2 }], sent: '9 days ago', status: 'declined' },
];

const quoteTotal = (q) => q.items.reduce((s, it) => s + it.qty * it.price, 0);

// Shared session store — orders, quotes and suppliers all live here so an
// advanced order, an approved quote (which spawns an order), or a newly added
// supplier persists as you move between the Orders sub-screens. Resets on reload.
window.PXOrders = window.makeStore({ orders: ORDER_SEED, quotes: QUOTE_SEED, suppliers: SUPPLIERS, focus: null });
Object.assign(window.PXOrders, {
  addOrder: (o) => window.PXOrders.set(s => ({ ...s, orders: [o, ...s.orders] })),
  advanceOrder: (id) => window.PXOrders.set(s => ({ ...s, orders: s.orders.map(o => o.id === id ? { ...o, stage: Math.min(o.stage + 1, STAGES.length - 1), updated: 'just now' } : o) })),
  addQuote: (q) => window.PXOrders.set(s => ({ ...s, quotes: [q, ...s.quotes] })),
  setQuoteStatus: (id, status) => window.PXOrders.set(s => ({ ...s, quotes: s.quotes.map(q => q.id === id ? { ...q, status } : q) })),
  // Approve a quote → mark it approved AND create the matching order at the
  // 'Quote approved' stage. Returns the new order so the caller can announce it.
  approveQuote: (id) => {
    const st = window.PXOrders.get();
    const q = st.quotes.find(x => x.id === id);
    if (!q) return null;
    const order = { id: window.pxid('ORD'), customer: q.customer, company: q.company || '—', email: q.email || '—', stage: 2, items: q.items, updated: 'just now' };
    window.PXOrders.set(s => ({ ...s, quotes: s.quotes.map(x => x.id === id ? { ...x, status: 'approved' } : x), orders: [order, ...s.orders] }));
    return order;
  },
  addSupplier: (sp) => window.PXOrders.set(s => ({ ...s, suppliers: [...s.suppliers, sp] })),
  updateSupplier: (id, patch) => window.PXOrders.set(s => ({ ...s, suppliers: s.suppliers.map(x => x.id === id ? { ...x, ...patch } : x) })),
  focusOrder: (id) => window.PXOrders.set(s => ({ ...s, focus: id })),
});

// Producible products the order + quote builders draw from.
const PRODUCTS = [
  { n: 'Custom tote bag', price: 6.2 },
  { n: 'Ceramic mug · 12oz', price: 8.4 },
  { n: 'Kraft mailer box', price: 1.85 },
  { n: 'Interior tissue print', price: 0.35 },
  { n: 'Screen print setup', price: 65 },
];
const productForType = { tote: 'Custom tote bag', mug: 'Ceramic mug · 12oz', box: 'Kraft mailer box' };

// New-order dialog — drops a fresh order into the pipeline at the Cart stage.
function NewOrderModal({ onClose }) {
  const P = window.PX; const { toast } = window.useApp();
  const [customer, setCustomer] = React.useState('');
  const [company, setCompany] = React.useState('');
  const [prod, setProd] = React.useState(PRODUCTS[0].n);
  const [qty, setQty] = React.useState('50');
  const create = () => {
    if (!customer.trim()) { toast('Add a customer name.', { tone: 'rose', icon: 'alert' }); return; }
    const q = parseInt(qty, 10);
    if (!q || q < 1) { toast('Enter a quantity.', { tone: 'rose', icon: 'alert' }); return; }
    const p = PRODUCTS.find(x => x.n === prod) || PRODUCTS[0];
    const order = { id: window.pxid('ORD'), customer: customer.trim(), company: company.trim() || '—', email: '—', stage: 0, items: [{ n: p.n, qty: q, price: p.price }], updated: 'just now' };
    window.PXOrders.addOrder(order);
    onClose(); toast(`Order ${order.id} created — starts in Cart.`, { tone: 'sage', icon: 'check' });
  };
  return (
    <window.Modal title="New order" sub="Create an order and drop it into the fulfillment pipeline." w={520} onClose={onClose}
      foot={<><Btn kind="ghost" size="md" onClick={onClose}>Cancel</Btn><div style={{ flex: 1 }}/><Btn kind="primary" size="md" icon="plus" onClick={create}>Create order</Btn></>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
        <Field label="Customer" placeholder="Jordan Rivera" value={customer} onChange={setCustomer}/>
        <Field label="Company" placeholder="Optional" value={company} onChange={setCompany}/>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 14 }}>
        <Select label="Product" value={prod} onChange={setProd} options={PRODUCTS.map(p => p.n)}/>
        <Field label="Quantity" type="number" value={qty} onChange={setQty}/>
      </div>
    </window.Modal>
  );
}

// Line-item quote builder — used by both "New quote" and "Attach to quote".
function NewQuoteModal({ onClose, initItems, initCustomer }) {
  const P = window.PX; const { toast, go } = window.useApp();
  const [customer, setCustomer] = React.useState(initCustomer || '');
  const [company, setCompany] = React.useState('');
  const [lines, setLines] = React.useState(initItems && initItems.length ? initItems : [{ n: PRODUCTS[0].n, qty: 100, price: PRODUCTS[0].price }]);
  const setLine = (i, patch) => setLines(ls => ls.map((l, j) => j === i ? { ...l, ...patch } : l));
  const addLine = () => setLines(ls => [...ls, { n: PRODUCTS[0].n, qty: 50, price: PRODUCTS[0].price }]);
  const removeLine = (i) => setLines(ls => ls.length > 1 ? ls.filter((_, j) => j !== i) : ls);
  const total = lines.reduce((s, l) => s + (parseInt(l.qty, 10) || 0) * (parseFloat(l.price) || 0), 0);
  const create = () => {
    if (!customer.trim()) { toast('Add a customer name.', { tone: 'rose', icon: 'alert' }); return; }
    const quote = { id: window.pxid('q'), customer: customer.trim(), company: company.trim() || '—', email: '—', items: lines.map(l => ({ n: l.n, qty: parseInt(l.qty, 10) || 1, price: parseFloat(l.price) || 0 })), sent: 'Just now', status: 'pending' };
    window.PXOrders.addQuote(quote);
    onClose(); toast(`Quote for ${quote.customer} created — it's in Pending.`, { tone: 'sage', icon: 'check' }); go('orders/quotes');
  };
  return (
    <window.Modal title="New quote" sub="Build a line-item quote to send for approval." w={600} onClose={onClose}
      foot={<><Btn kind="ghost" size="md" onClick={onClose}>Cancel</Btn><div style={{ flex: 1 }}/><span style={{ fontSize: 13, color: P.ink3, alignSelf: 'center', marginRight: 4 }}>Total <b style={{ color: P.ink }}>{money(total)}</b></span><Btn kind="primary" size="md" icon="check" onClick={create}>Create quote</Btn></>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 16 }}>
        <Field label="Customer" placeholder="Jordan Rivera" value={customer} onChange={setCustomer}/>
        <Field label="Company" placeholder="Optional" value={company} onChange={setCompany}/>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 70px 84px 30px', gap: 8, marginBottom: 4 }}>
        {['Product', 'Qty', 'Price', ''].map((h, i) => <Label key={i} style={{ textAlign: i > 0 && i < 3 ? 'right' : 'left' }}>{h}</Label>)}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {lines.map((l, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 70px 84px 30px', gap: 8, alignItems: 'center' }}>
            <Select value={l.n} onChange={v => { const p = PRODUCTS.find(x => x.n === v); setLine(i, { n: v, price: p ? p.price : l.price }); }} options={PRODUCTS.map(p => p.n)}/>
            <Field type="number" value={String(l.qty)} onChange={v => setLine(i, { qty: v })}/>
            <Field type="number" value={String(l.price)} onChange={v => setLine(i, { price: v })}/>
            <Btn kind="ghost" size="sm" icon="x" onClick={() => removeLine(i)}/>
          </div>
        ))}
      </div>
      <Btn kind="default" size="sm" icon="plus" onClick={addLine} style={{ marginTop: 10 }}>Add line</Btn>
    </window.Modal>
  );
}

// Add-supplier dialog.
function AddSupplierModal({ onClose, onAdded }) {
  const P = window.PX; const { toast } = window.useApp();
  const [name, setName] = React.useState('');
  const [spec, setSpec] = React.useState('');
  const [turnaround, setTurnaround] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const add = () => {
    if (!name.trim()) { toast('Add a supplier name.', { tone: 'rose', icon: 'alert' }); return; }
    const id = window.pxid('s');
    window.PXOrders.addSupplier({ id, name: name.trim(), spec: spec.trim() || 'General fulfillment', turnaround: turnaround.trim() || '7–10 days', status: 'active', email: email.trim() || '—', phone: phone.trim() || '—', activeOrders: 0, notes: 'Newly added supplier — no notes yet.' });
    onClose(); onAdded && onAdded(id); toast(`${name.trim()} added to suppliers.`, { tone: 'sage', icon: 'check' });
  };
  return (
    <window.Modal title="Add supplier" sub="A managed fulfillment partner Pex can route orders to." w={520} onClose={onClose}
      foot={<><Btn kind="ghost" size="md" onClick={onClose}>Cancel</Btn><div style={{ flex: 1 }}/><Btn kind="primary" size="md" icon="plus" onClick={add}>Add supplier</Btn></>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="Name" placeholder="Brightline Print Co." value={name} onChange={setName} style={{ gridColumn: '1 / -1' }}/>
        <Field label="Specialty" placeholder="Apparel & tote printing" value={spec} onChange={setSpec}/>
        <Field label="Turnaround" placeholder="5–7 days" value={turnaround} onChange={setTurnaround}/>
        <Field label="Email" icon="mail" placeholder="orders@…" value={email} onChange={setEmail}/>
        <Field label="Phone" icon="phone" placeholder="(555) 555-0100" value={phone} onChange={setPhone}/>
      </div>
    </window.Modal>
  );
}

window.SCREENS['orders'] = function Orders({ sub }) {
  const P = window.PX; const { go } = window.useApp();
  const { orders, quotes } = window.useStore(window.PXOrders);
  const seg = (sub || '').split('/');
  const active = seg[0] || 'overview';
  const inProd = orders.filter(o => o.stage === 3).length;
  const pendingQuotes = quotes.filter(q => q.status === 'pending').length;
  const nav = [
    { items: [{ k: 'overview', icon: 'home', label: 'Overview' }] },
    { label: 'Fulfillment', items: [
      { k: 'list', icon: 'package', label: 'Orders', badge: inProd, tone: 'spark' },
      { k: 'mockups', icon: 'image', label: 'Product mockups' },
    ]},
    { label: 'Partners', items: [
      { k: 'suppliers', icon: 'truck', label: 'Suppliers' },
    ]},
    { label: 'Sales', items: [
      { k: 'quotes', icon: 'fileText', label: 'Quotes', badge: pendingQuotes, tone: 'amber' },
    ]},
  ];
  const onNav = (k) => go('orders' + (k === 'overview' ? '' : '/' + k));
  return (
    <window.SubLayout title="Orders" nav={nav} active={active} onNav={onNav}
      foot={<div style={{ background: P.sparkWash, border: `1px solid ${P.sparkTint}`, borderRadius: 10, padding: 11 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Pex size={18}/><span style={{ fontSize: 12, fontWeight: 600, color: P.ink }}>Pex is tracking fulfillment</span></div>
        <div style={{ fontSize: 11, color: P.ink3, marginTop: 4 }}>{inProd} in production · {pendingQuotes} quotes await approval</div>
      </div>}>
      {active === 'overview' && <OrdOverview onNav={onNav}/>}
      {active === 'list' && <OrdersList/>}
      {active === 'mockups' && <Mockups/>}
      {active === 'suppliers' && <Suppliers/>}
      {active === 'quotes' && <Quotes/>}
    </window.SubLayout>
  );
};

const OHead = ({ title, sub, children }) => {
  const P = window.PX;
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 18, gap: 12 }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink, letterSpacing: -0.4 }}>{title}</div>
        {sub && <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 2 }}>{sub}</div>}
      </div>
      {children && <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>{children}</div>}
    </div>
  );
};

// small pill for an order's current stage
const StagePill = ({ stage, style = {} }) => {
  const s = STAGES[stage];
  return <Pill tone={s.tone} style={{ fontSize: 10, ...style }}>{s.label}</Pill>;
};

// ── OVERVIEW ─────────────────────────────────────────────────
function OrdOverview({ onNav }) {
  const P = window.PX; const { go, toast } = window.useApp();
  const { orders, quotes } = window.useStore(window.PXOrders);
  const ordersThisMonth = orders.length;
  const inProduction = orders.filter(o => o.stage === 3).length;
  const fulfilled = orders.filter(o => o.stage >= 4);
  const revenue = fulfilled.reduce((s, o) => s + o.items.reduce((x, it) => x + it.qty * it.price, 0), 0);
  const recent = orders.slice(0, 5);
  const stuck = quotes.filter(q => q.status === 'pending');
  const openOrder = (id) => { window.PXOrders.focusOrder(id); go('orders/list'); };
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <OHead title="Orders" sub="Every order, from cart to delivered — tracked in one place.">
        <Btn kind="default" size="sm" icon="fileText" onClick={() => go('orders/quotes')}>Quotes</Btn>
        <Btn kind="spark" size="sm" icon="package" onClick={() => go('orders/list')}>View orders</Btn>
      </OHead>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14, marginBottom: 16 }}>
        {[['Orders · this month', ordersThisMonth, 'package'], ['In production', inProduction, 'settings'], ['Revenue · fulfilled', money(revenue), 'dollar'], ['Avg fulfillment time', '6.4 days', 'clock']].map((c, i) => (
          <Card key={i} pad={16}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}><Label>{c[0]}</Label><Icon name={c[2]} size={15} color={P.ink3}/></div>
            <Num size={24} style={{ marginTop: 6 }}>{c[1]}</Num>
          </Card>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 14 }}>
        <Card pad={0}>
          <div style={{ padding: '14px 18px', borderBottom: `1px solid ${P.line}`, fontSize: 14, fontWeight: 600, color: P.ink }}>Recent order activity</div>
          {recent.map((o, i) => (
            <div key={o.id} onClick={() => openOrder(o.id)} style={{ padding: '13px 18px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: i < recent.length - 1 ? `1px solid ${P.line}` : 'none', cursor: 'pointer' }}
              onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <div style={{ width: 34, height: 34, borderRadius: 9, background: P[STAGES[o.stage].tone + 'Tint'] || P.sunk, color: P[STAGES[o.stage].tone] || P.ink2, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={STAGES[o.stage].icon} size={16}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: P.ink, fontWeight: 500 }}>{o.id} · {o.customer}</div>
                <div style={{ fontSize: 11.5, color: P.ink3, marginTop: 1 }}>Moved to {STAGES[o.stage].label.toLowerCase()} · {o.updated}</div>
              </div>
              <StagePill stage={o.stage}/>
            </div>
          ))}
        </Card>
        <Card pad={18} style={{ background: P.sparkWash, border: `1px solid ${P.sparkTint}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 10 }}><Pex size={22}/><span style={{ fontSize: 14, fontWeight: 600, color: P.ink }}>Needs your attention</span></div>
          <div style={{ fontSize: 12.5, color: P.ink2, lineHeight: 1.55, marginBottom: 12 }}>
            <b style={{ color: P.ink }}>{stuck.length} quotes</b> are waiting on a customer decision. The oldest has been open for 6 days.
          </div>
          <Btn kind="spark" size="sm" full onClick={() => go('orders/quotes')}>Review quotes</Btn>
          <div style={{ height: 1, background: P.sparkTint, margin: '14px 0' }}/>
          <div style={{ fontSize: 12.5, color: P.ink2, lineHeight: 1.55, marginBottom: 12 }}>
            Want to preview a design before quoting? Pex can render a brand-applied mockup in seconds.
          </div>
          <Btn kind="default" size="sm" full icon="image" onClick={() => go('orders/mockups')}>Open mockups</Btn>
        </Card>
      </div>
    </div>
  );
}

// ── ORDERS LIST + detail drawer ─────────────────────────────
function OrdersList() {
  const P = window.PX; const { toast } = window.useApp();
  const { orders } = window.useStore(window.PXOrders);
  const [q, setQ] = React.useState('');
  const [tab, setTab] = React.useState('all');
  const [selectedId, setSelectedId] = React.useState(null);
  const [activeOnly, setActiveOnly] = React.useState(false);
  const [showNew, setShowNew] = React.useState(false);

  // Pull in an order the Overview asked us to open.
  React.useEffect(() => {
    const f = window.PXOrders.get().focus;
    if (f) { setSelectedId(f); window.PXOrders.set(s => ({ ...s, focus: null })); }
  }, []);

  const filtered = orders.filter(o => {
    const matchesTab = tab === 'all' || STAGES[o.stage].k === tab;
    const needle = q.trim().toLowerCase();
    const matchesQ = !needle || o.id.toLowerCase().includes(needle) || o.customer.toLowerCase().includes(needle) || o.company.toLowerCase().includes(needle);
    const matchesActive = !activeOnly || o.stage < STAGES.length - 1;
    return matchesTab && matchesQ && matchesActive;
  });

  const advance = (id) => { window.PXOrders.advanceOrder(id); toast('Order advanced.', { tone: 'sage', icon: 'check' }); };

  const selected = orders.find(o => o.id === selectedId) || null;

  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <OHead title="Orders" sub="Full lifecycle, cart to delivered.">
        <Btn kind={activeOnly ? 'spark' : 'default'} size="sm" icon="filter" onClick={() => setActiveOnly(a => !a)}>{activeOnly ? 'Active only' : 'Filter'}</Btn>
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setShowNew(true)}>New order</Btn>
      </OHead>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        <div style={{ flex: 1, maxWidth: 320, display: 'flex', alignItems: 'center', gap: 8, background: P.card, border: `1px solid ${P.lineStrong}`, borderRadius: P.rCtl, padding: '8px 11px' }}>
          <Icon name="search" size={15} color={P.ink3}/>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search order, customer, company…" style={{ flex: 1, border: 'none', background: 'transparent', outline: 'none', fontSize: 12.5, color: P.ink, fontFamily: P.sans, minWidth: 0 }}/>
        </div>
      </div>

      <Tabs tabs={[{ k: 'all', label: 'All', count: orders.length }, ...STAGES.map(s => ({ k: s.k, label: s.label, count: orders.filter(o => STAGES[o.stage].k === s.k).length }))]} active={tab} onChange={setTab}/>

      <Card pad={0} style={{ marginTop: 4 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1.6fr 1fr 1.3fr 90px 90px 30px', gap: 12, padding: '12px 18px', borderBottom: `1px solid ${P.line}` }}>
          {['Order', 'Customer', 'Items', 'Status', 'Total', 'Updated', ''].map((h, i) => <Label key={i} style={{ textAlign: i === 4 ? 'right' : 'left' }}>{h}</Label>)}
        </div>
        {filtered.length === 0 && <div style={{ padding: '28px 18px', textAlign: 'center', fontSize: 12.5, color: P.ink3 }}>No orders match.</div>}
        {filtered.map((o, i) => {
          const total = o.items.reduce((s, it) => s + it.qty * it.price, 0);
          return (
            <div key={o.id} onClick={() => setSelectedId(o.id)} style={{ display: 'grid', gridTemplateColumns: '1.1fr 1.6fr 1fr 1.3fr 90px 90px 30px', gap: 12, padding: '13px 18px', borderBottom: i < filtered.length - 1 ? `1px solid ${P.line}` : 'none', alignItems: 'center', cursor: 'pointer' }}
              onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <span style={{ fontSize: 12.5, color: P.ink, fontFamily: P.mono }}>{o.id}</span>
              <div><div style={{ fontSize: 13, color: P.ink, fontWeight: 500 }}>{o.customer}</div><div style={{ fontSize: 11, color: P.ink3 }}>{o.company}</div></div>
              <span style={{ fontSize: 12.5, color: P.ink3 }}>{o.items.reduce((s, it) => s + it.qty, 0).toLocaleString()} units</span>
              <span><StagePill stage={o.stage}/></span>
              <span style={{ fontSize: 12.5, color: P.ink, textAlign: 'right', fontFamily: P.mono, fontWeight: 500 }}>{money(total)}</span>
              <span style={{ fontSize: 12, color: P.ink3, textAlign: 'right' }}>{o.updated}</span>
              <Icon name="chevR" size={15} color={P.ink4}/>
            </div>
          );
        })}
      </Card>

      {selected && (
        <window.Drawer w={560} title={selected.id} sub={selected.customer + (selected.company !== '—' ? ' · ' + selected.company : '')}
          tag={<StagePill stage={selected.stage}/>} onClose={() => setSelectedId(null)}
          foot={selected.stage < STAGES.length - 1
            ? <Btn kind="spark" size="md" full icon="arrowRight" onClick={() => advance(selected.id)}>Advance to {STAGES[selected.stage + 1].label}</Btn>
            : <Btn kind="default" size="md" full disabled icon="check">Fulfilled</Btn>}>
          <OrderDetail order={selected}/>
        </window.Drawer>
      )}
      {showNew && <NewOrderModal onClose={() => setShowNew(false)}/>}
    </div>
  );
}

function OrderDetail({ order }) {
  const P = window.PX;
  const total = order.items.reduce((s, it) => s + it.qty * it.price, 0);
  return (
    <div>
      {/* step tracker */}
      <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 24 }}>
        {STAGES.map((s, i) => {
          const done = i < order.stage; const cur = i === order.stage;
          return (
            <React.Fragment key={s.k}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, width: 66 }}>
                <div style={{ width: 30, height: 30, borderRadius: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  background: done ? P.sage : cur ? P.spark : P.sunk, border: `1px solid ${done ? P.sage : cur ? P.spark : P.line}` }}>
                  {done ? <Icon name="check" size={14} color="#fff" stroke={2.5}/> : <Icon name={s.icon} size={14} color={cur ? '#fff' : P.ink4}/>}
                </div>
                <span style={{ fontSize: 10, color: cur ? P.ink : P.ink3, fontWeight: cur ? 600 : 500, textAlign: 'center', lineHeight: 1.25 }}>{s.label}</span>
              </div>
              {i < STAGES.length - 1 && <div style={{ flex: 1, height: 2, background: i < order.stage ? P.sage : P.line, marginTop: 14 }}/>}
            </React.Fragment>
          );
        })}
      </div>

      <Label style={{ marginBottom: 8 }}>Customer</Label>
      <Card pad={14} style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Avatar name={order.customer} size={34}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, color: P.ink, fontWeight: 600 }}>{order.customer}</div>
            <div style={{ fontSize: 11.5, color: P.ink3 }}>{order.company !== '—' ? order.company + ' · ' : ''}{order.email}</div>
          </div>
        </div>
      </Card>

      <Label style={{ marginBottom: 8 }}>Line items</Label>
      <Card pad={0} style={{ marginBottom: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 60px 70px 80px', gap: 8, padding: '10px 14px', borderBottom: `1px solid ${P.line}` }}>
          {['Item', 'Qty', 'Price', 'Subtotal'].map((h, i) => <Label key={i} style={{ textAlign: i > 0 ? 'right' : 'left' }}>{h}</Label>)}
        </div>
        {order.items.map((it, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 60px 70px 80px', gap: 8, padding: '11px 14px', borderBottom: i < order.items.length - 1 ? `1px solid ${P.line}` : 'none', fontSize: 12.5 }}>
            <span style={{ color: P.ink }}>{it.n}</span>
            <span style={{ color: P.ink3, textAlign: 'right', fontFamily: P.mono }}>{it.qty}</span>
            <span style={{ color: P.ink3, textAlign: 'right', fontFamily: P.mono }}>{money(it.price)}</span>
            <span style={{ color: P.ink, textAlign: 'right', fontFamily: P.mono, fontWeight: 500 }}>{money(it.qty * it.price)}</span>
          </div>
        ))}
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '11px 14px', background: P.sunk }}>
          <span style={{ fontSize: 12.5, color: P.ink2, fontWeight: 600 }}>Total</span>
          <span style={{ fontSize: 13.5, color: P.ink, fontWeight: 700, fontFamily: P.mono }}>{money(total)}</span>
        </div>
      </Card>

      <Label style={{ marginBottom: 8 }}>Timeline</Label>
      <div style={{ fontSize: 12, color: P.ink3, lineHeight: 1.6 }}>Last updated {order.updated}. Advancing this order simulates the next step in fulfillment for demo purposes — no supplier notification is actually sent.</div>
    </div>
  );
}

// ── PRODUCT MOCKUP PREVIEW ───────────────────────────────────
function ProductMock({ type, accent }) {
  const P = window.PX;
  const ac = accent || P.spark;
  if (type === 'mug') {
    return (
      <div style={{ position: 'relative', width: 190, height: 190, margin: '0 auto' }}>
        <div style={{ position: 'absolute', inset: 0, borderRadius: '16px 16px 12px 12px', background: '#fff', border: `1px solid ${P.line}`, boxShadow: P.shMd, overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 58, background: ac }}/>
          <div style={{ position: 'absolute', top: 78, left: 0, right: 0, textAlign: 'center' }}>
            <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 22, color: P.ink }}>Honest Loaves</div>
            <div style={{ fontSize: 9.5, color: P.ink3, letterSpacing: 1.5, textTransform: 'uppercase', marginTop: 6 }}>Est. Brooklyn</div>
          </div>
        </div>
        <div style={{ position: 'absolute', right: -24, top: 50, width: 30, height: 66, border: '9px solid #fff', borderLeft: 'none', borderRadius: '0 30px 30px 0', boxShadow: P.shSm }}/>
      </div>
    );
  }
  if (type === 'box') {
    return (
      <div style={{ width: 200, height: 200, position: 'relative', margin: '0 auto' }}>
        <div style={{ position: 'absolute', top: -8, left: 18, right: 18, height: 10, background: ac, borderRadius: '6px 6px 0 0' }}/>
        <div style={{ position: 'absolute', inset: 0, background: '#fff', border: `1px solid ${P.line}`, borderRadius: 10, boxShadow: P.shMd, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10 }}>
          <div style={{ width: 50, height: 50, borderRadius: 12, background: ac, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Spark size={22} color="#fff"/></div>
          <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 18, color: P.ink }}>Honest Loaves</div>
          <div style={{ width: 110, height: 1, background: P.line }}/>
          <div style={{ fontSize: 9.5, color: P.ink3, letterSpacing: 1.5, textTransform: 'uppercase' }}>Handmade · Small batch</div>
        </div>
      </div>
    );
  }
  // tote (default)
  return (
    <div style={{ position: 'relative', width: 200, height: 236, margin: '0 auto' }}>
      <svg width="200" height="48" viewBox="0 0 200 48" style={{ position: 'absolute', top: -4, left: 0 }}>
        <path d="M52 48 C52 8 82 8 82 48" fill="none" stroke={P.ink3} strokeWidth="7"/>
        <path d="M118 48 C118 8 148 8 148 48" fill="none" stroke={P.ink3} strokeWidth="7"/>
      </svg>
      <div style={{ position: 'absolute', top: 26, left: 0, right: 0, bottom: 0, background: '#F2E2C4', borderRadius: 10, boxShadow: P.shMd, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10 }}>
        <div style={{ width: 48, height: 48, borderRadius: 10, background: ac, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Spark size={20} color="#fff"/></div>
        <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 20, color: P.ink }}>Honest Loaves</div>
      </div>
    </div>
  );
}

function Mockups() {
  const P = window.PX; const { toast, sparks, setSparks, openOverlay } = window.useApp();
  const [type, setType] = React.useState('tote');
  const [accent, setAccent] = React.useState(P.spark);
  const [rev, setRev] = React.useState(1);
  const [attach, setAttach] = React.useState(false);
  const swatches = [['Brand accent', P.spark], ['Ink', P.ink], ['Sage', P.sage], ['Sky', P.sky]];
  const regen = () => {
    const cost = 2;
    if (cost > sparks) { openOverlay('creditGate', { needed: cost, balance: sparks }); return; }
    setSparks(s => Math.max(0, s - cost));
    const next = rev + 1;
    setRev(next);
    setAccent(swatches[next % swatches.length][1]);
    toast(`Rendered variation ${next}. ${cost} ⚡ spent.`, { tone: 'sage', icon: 'sparkles' });
  };
  const prodName = productForType[type];
  const prod = PRODUCTS.find(p => p.n === prodName) || PRODUCTS[0];
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <OHead title="Product mockups" sub="Pex renders your brand onto real product shapes before you commit to a print run.">
        <Btn kind="spark" size="sm" icon="sparkles" onClick={regen}>Regenerate · 2 ⚡</Btn>
      </OHead>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20 }}>
        <Card pad={0}>
          <Tabs tabs={[{ k: 'tote', label: 'Tote bag' }, { k: 'mug', label: 'Mug' }, { k: 'box', label: 'Packaging box' }]} active={type} onChange={setType} style={{ padding: '0 18px' }}/>
          <div style={{ padding: '44px 18px', background: P.sunk, position: 'relative' }}>
            <span style={{ position: 'absolute', top: 12, right: 16, fontSize: 10.5, color: P.ink3, fontFamily: P.mono }}>Variation {rev}</span>
            <ProductMock type={type} accent={accent}/>
          </div>
        </Card>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card pad={16}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}><Pex size={20}/><span style={{ fontSize: 13, fontWeight: 600, color: P.ink }}>AI-generated mockup</span></div>
            <div style={{ fontSize: 12, color: P.ink3, lineHeight: 1.55 }}>Pex applied your brand colors, font, and logomark to this product automatically from your Settings → Brand & theme configuration.</div>
          </Card>
          <Card pad={16}>
            <Label style={{ marginBottom: 10 }}>Brand tokens · tap to recolor</Label>
            {swatches.map((s, i) => {
              const on = accent === s[1];
              return (
                <div key={i} onClick={() => setAccent(s[1])} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 8px', margin: '0 -8px', borderRadius: 8, cursor: 'pointer', background: on ? P.sparkWash : 'transparent', borderBottom: i < swatches.length - 1 ? `1px solid ${P.line}` : 'none' }}>
                  <span style={{ width: 18, height: 18, borderRadius: 6, background: s[1], border: `2px solid ${on ? P.ink : P.line}`, flexShrink: 0 }}/>
                  <span style={{ flex: 1, fontSize: 12.5, color: P.ink }}>{s[0]}</span>
                  {on ? <Icon name="check" size={14} color={P.spark}/> : <span style={{ fontSize: 11.5, color: P.ink3, fontFamily: P.mono }}>{s[1]}</span>}
                </div>
              );
            })}
          </Card>
          <Card pad={16}>
            <Label style={{ marginBottom: 8 }}>Send to supplier</Label>
            <div style={{ fontSize: 12, color: P.ink3, lineHeight: 1.5, marginBottom: 10 }}>Attach this mockup to a new quote request — the {prodName.toLowerCase()} lands as the first line item.</div>
            <Btn kind="default" size="sm" full icon="send" onClick={() => setAttach(true)}>Attach to quote</Btn>
          </Card>
        </div>
      </div>
      {attach && <NewQuoteModal initItems={[{ n: prod.n, qty: 100, price: prod.price }]} onClose={() => setAttach(false)}/>}
    </div>
  );
}

// ── SUPPLIERS ────────────────────────────────────────────────
function Suppliers() {
  const P = window.PX; const { toast, go, openOverlay } = window.useApp();
  const { suppliers } = window.useStore(window.PXOrders);
  const [selId, setSelId] = React.useState(suppliers[0] && suppliers[0].id);
  const [showAdd, setShowAdd] = React.useState(false);
  const s = suppliers.find(x => x.id === selId) || suppliers[0];
  const toggleStatus = () => window.PXOrders.updateSupplier(s.id, { status: s.status === 'active' ? 'paused' : 'active' });
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <OHead title="Suppliers" sub="Managed fulfillment partners — Pex routes orders to the fastest fit.">
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setShowAdd(true)}>Add supplier</Btn>
      </OHead>
      <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 18 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {suppliers.map((sp) => {
            const on = sp.id === selId;
            return (
              <Card key={sp.id} pad={14} onClick={() => setSelId(sp.id)} hover style={{ cursor: 'pointer', border: `1.5px solid ${on ? P.spark : P.line}`, background: on ? P.sparkWash : P.card }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 8, background: sp.status === 'active' ? P.sage : P.ink4 }}/>
                  <span style={{ flex: 1, fontSize: 13.5, fontWeight: 600, color: P.ink }}>{sp.name}</span>
                </div>
                <div style={{ fontSize: 11.5, color: P.ink3 }}>{sp.spec}</div>
                <div style={{ fontSize: 11.5, color: P.ink3, marginTop: 2 }}>Turnaround · {sp.turnaround}</div>
              </Card>
            );
          })}
        </div>
        {s && <Card pad={22}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 18 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 22, color: P.ink }}>{s.name}</div>
              <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 3 }}>{s.spec}</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
              <span style={{ fontSize: 12, color: P.ink3 }}>{s.status === 'active' ? 'Active' : 'Paused'}</span>
              <Toggle on={s.status === 'active'} size="sm" onClick={toggleStatus}/>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14, marginBottom: 18 }}>
            {[['Turnaround', s.turnaround], ['Active orders', s.activeOrders], ['Status', s.status === 'active' ? 'Accepting orders' : 'Paused']].map((c, i) => (
              <Card key={i} pad={14} style={{ background: P.sunk, boxShadow: 'none' }}><Label>{c[0]}</Label><div style={{ fontSize: 15, color: P.ink, fontWeight: 600, marginTop: 5 }}>{c[1]}</div></Card>
            ))}
          </div>
          <Label style={{ marginBottom: 8 }}>Contact</Label>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13, color: P.ink2 }}><Icon name="mail" size={15} color={P.ink3}/>{s.email}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13, color: P.ink2 }}><Icon name="phone" size={15} color={P.ink3}/>{s.phone}</div>
          </div>
          <TextArea label="Notes" value={s.notes} onChange={v => window.PXOrders.updateSupplier(s.id, { notes: v })} rows={3} sub="Edits save as you type." style={{ marginBottom: 18 }}/>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn kind="default" size="sm" icon="mail" onClick={() => openOverlay('compose', { to: s.email !== '—' ? s.email : '', subject: `Production inquiry — Honest Loaves` })}>Email</Btn>
            <Btn kind="default" size="sm" icon="package" onClick={() => go('orders/list')}>View orders</Btn>
          </div>
        </Card>}
      </div>
      {showAdd && <AddSupplierModal onClose={() => setShowAdd(false)} onAdded={id => setSelId(id)}/>}
    </div>
  );
}

// ── QUOTES ───────────────────────────────────────────────────
function Quotes() {
  const P = window.PX; const { toast } = window.useApp();
  const { quotes } = window.useStore(window.PXOrders);
  const [tab, setTab] = React.useState('pending');
  const [showNew, setShowNew] = React.useState(false);
  const approve = (q) => { const o = window.PXOrders.approveQuote(q.id); if (o) toast(`Quote approved — order ${o.id} created for ${q.customer}.`, { tone: 'sage', icon: 'check' }); };
  const decline = (q) => { window.PXOrders.setQuoteStatus(q.id, 'declined'); toast('Quote declined.', { tone: 'rose', icon: 'x' }); };
  const list = quotes.filter(q => q.status === tab);
  const stTone = { pending: 'amber', approved: 'sage', declined: 'rose' };
  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <OHead title="Quotes" sub="Sent to customers, awaiting approval — approving moves an order into production.">
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setShowNew(true)}>New quote</Btn>
      </OHead>
      <Tabs tabs={[{ k: 'pending', label: 'Pending', count: quotes.filter(q => q.status === 'pending').length }, { k: 'approved', label: 'Approved', count: quotes.filter(q => q.status === 'approved').length }, { k: 'declined', label: 'Declined', count: quotes.filter(q => q.status === 'declined').length }]} active={tab} onChange={setTab}/>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 14 }}>
        {list.length === 0 && <div style={{ padding: '28px 0', textAlign: 'center', fontSize: 12.5, color: P.ink3 }}>No {tab} quotes.</div>}
        {list.map(q => {
          const total = quoteTotal(q);
          return (
            <Card key={q.id} pad={16}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <Avatar name={q.customer} size={32}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13.5, color: P.ink, fontWeight: 600 }}>{q.customer}</div>
                  <div style={{ fontSize: 11.5, color: P.ink3 }}>{q.company !== '—' ? q.company + ' · ' : ''}Sent {q.sent}</div>
                </div>
                <Pill tone={stTone[q.status]} style={{ fontSize: 10 }}>{q.status}</Pill>
              </div>
              <div style={{ border: `1px solid ${P.line}`, borderRadius: 9, overflow: 'hidden', marginBottom: 12 }}>
                {q.items.map((it, i) => (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 60px 70px 80px', gap: 8, padding: '9px 12px', borderBottom: i < q.items.length - 1 ? `1px solid ${P.line}` : 'none', fontSize: 12.5 }}>
                    <span style={{ color: P.ink }}>{it.n}</span>
                    <span style={{ color: P.ink3, textAlign: 'right', fontFamily: P.mono }}>{it.qty}</span>
                    <span style={{ color: P.ink3, textAlign: 'right', fontFamily: P.mono }}>{money(it.price)}</span>
                    <span style={{ color: P.ink, textAlign: 'right', fontFamily: P.mono, fontWeight: 500 }}>{money(it.qty * it.price)}</span>
                  </div>
                ))}
                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '9px 12px', background: P.sunk }}>
                  <span style={{ fontSize: 12, color: P.ink2, fontWeight: 600 }}>Total</span>
                  <span style={{ fontSize: 13, color: P.ink, fontWeight: 700, fontFamily: P.mono }}>{money(total)}</span>
                </div>
              </div>
              {q.status === 'pending' && (
                <div style={{ display: 'flex', gap: 8 }}>
                  <Btn kind="primary" size="sm" icon="check" onClick={() => approve(q)}>Approve</Btn>
                  <Btn kind="danger" size="sm" icon="x" onClick={() => decline(q)}>Decline</Btn>
                </div>
              )}
            </Card>
          );
        })}
      </div>
      {showNew && <NewQuoteModal onClose={() => setShowNew(false)}/>}
    </div>
  );
}
