// Quote Builder — line-item editor · live preview · send & e-sign

function qbParseJson(raw) {
  if (!raw) return null;
  let s = String(raw).trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim();
  const i = s.indexOf('{'); if (i > 0) s = s.slice(i);
  const j = s.lastIndexOf('}'); if (j !== -1) s = s.slice(0, j + 1);
  try { return JSON.parse(s); } catch (e) { return null; }
}

const QB_PRODUCTS = [
  { id:'p1', cat:'Cabinets', name:'Base cabinet 600mm', unit:1, price:620 },
  { id:'p2', cat:'Cabinets', name:'Wall cabinet 600mm', unit:1, price:480 },
  { id:'p3', cat:'Cabinets', name:'Corner cabinet lazy susan', unit:1, price:890 },
  { id:'p4', cat:'Cabinets', name:'Pantry tower 600×2100mm', unit:1, price:1240 },
  { id:'p5', cat:'Benchtops', name:'Stone benchtop 20mm Calacatta', unit:'m²', price:480 },
  { id:'p6', cat:'Benchtops', name:'Waterfall end panel', unit:1, price:680 },
  { id:'p7', cat:'Benchtops', name:'Splashback 10mm toughened glass', unit:'m²', price:320 },
  { id:'p8', cat:'Appliances', name:'Fisher & Paykel 60cm induction', unit:1, price:1890 },
  { id:'p9', cat:'Appliances', name:'Integrated dishwasher 60cm', unit:1, price:1650 },
  { id:'p10', cat:'Hardware', name:'Blum soft-close hinges (set)', unit:1, price:48 },
  { id:'p11', cat:'Hardware', name:'Handle bar 160mm (each)', unit:1, price:22 },
  { id:'p12', cat:'Installation', name:'Full installation & labour', unit:1, price:4200 },
  { id:'p13', cat:'Installation', name:'Site preparation', unit:1, price:800 },
];

const QB_STATES = ['building', 'preview', 'sent'];

function QuoteBuilder({ deals, contacts, showToast }) {
  const toast = showToast || (() => {});
  const LIVE = !!window.STAGEVO_AUTHED && !!window.StagevoData;
  const AI_OK = window.claude && typeof window.claude.complete === 'function';
  const [qstate, setQstate] = React.useState('building');
  const [selectedDeal, setSelectedDeal] = React.useState(deals.filter(d=>d.stage!=='sold'&&d.stage!=='lost')[0]);
  const [lineItems, setLineItems] = React.useState([
    { id:'li1', productId:'p1', name:'Base cabinet 600mm', qty:8, unit:1, price:620, note:'' },
    { id:'li2', productId:'p4', name:'Pantry tower 600×2100mm', qty:1, unit:1, price:1240, note:'' },
    { id:'li5', productId:'p5', name:'Stone benchtop 20mm Calacatta', qty:7.2, unit:'m²', price:480, note:'Waterfall edge both ends' },
    { id:'li8', productId:'p8', name:'Fisher & Paykel 60cm induction', qty:1, unit:1, price:1890, note:'' },
    { id:'li12', productId:'p12', name:'Full installation & labour', qty:1, unit:1, price:4200, note:'' },
  ]);
  const [showCatalog, setShowCatalog] = React.useState(false);
  const [discount, setDiscount] = React.useState(0);
  const [note, setNote] = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const [aiBusy, setAiBusy] = React.useState(false);
  const [aiTip, setAiTip] = React.useState('');

  const subtotal = lineItems.reduce((a, li) => a + (li.price * li.qty), 0);
  const discountAmt = subtotal * discount / 100;
  const gst = (subtotal - discountAmt) * 0.1;
  const total = subtotal - discountAmt + gst;
  const fmt = v => '$' + v.toLocaleString('en-AU', {minimumFractionDigits:2, maximumFractionDigits:2});

  const addProduct = (p) => {
    setLineItems(prev => [...prev, { id:'li'+Date.now(), productId:p.id, name:p.name, qty:1, unit:p.unit, price:p.price, note:'' }]);
    setShowCatalog(false);
  };
  const removeItem = (id) => setLineItems(prev => prev.filter(li=>li.id!==id));
  const updateItem = (id, field, val) => setLineItems(prev => prev.map(li => li.id===id ? {...li, [field]:val} : li));

  const cats = [...new Set(QB_PRODUCTS.map(p=>p.cat))];
  const activeDeal = selectedDeal;

  const STATUS_LABELS = { building:'Building', preview:'Preview', sent:'Sent / Signed' };

  async function suggestDiscount() {
    if (!AI_OK || aiBusy) return;
    setAiBusy(true);
    try {
      const items = lineItems.map(li => `${li.qty}x ${li.name} @ $${li.price}`).join('; ');
      const prompt = `A kitchen/cabinetry quote for ${activeDeal ? activeDeal.customer : 'a customer'} totals $${subtotal.toFixed(0)} before discount. The deal estimate is $${(activeDeal && activeDeal.value) || 0}. Line items: ${items}. As a sales manager, recommend a single discount percentage between 0 and 15 that protects margin while helping the deal close. Return STRICT JSON only: {"pct":NUMBER,"why":"one short sentence"}.`;
      const raw = await window.claude.complete({ messages: [{ role: 'user', content: prompt }] });
      const p = qbParseJson(raw);
      if (p && typeof p.pct === 'number') { setDiscount(Math.max(0, Math.min(30, Math.round(p.pct)))); if (p.why) setAiTip(p.why); }
    } catch (e) {}
    setAiBusy(false);
  }

  async function sendQuote() {
    if (saving) return;
    setSaving(true);
    try {
      if (LIVE && activeDeal) {
        const items = lineItems.map(li => ({ name: li.name, qty: li.qty, unit: typeof li.unit === 'string' ? li.unit : 'ea', unit_price: li.price, note: li.note }));
        const match = (contacts || []).find(c => activeDeal.contactId ? c.id === activeDeal.contactId : (c.name || '').toLowerCase() === (activeDeal.customer || '').toLowerCase());
        const q = await window.StagevoData.createQuote(activeDeal.id, match ? match.id : null, items, { notes: note, discountPct: discount, validDays: 30 });
        if (q && q.id) await window.StagevoData.updateQuoteStatus(q.id, 'sent');
      }
      setQstate('sent');
    } catch (e) { alert('Could not save the quote: ' + (e.message || e)); }
    setSaving(false);
  }

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
      {/* Stage bar */}
      <div style={{ display:'flex', alignItems:'center', gap:0, marginBottom:18, background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-lg)', overflow:'hidden' }}>
        {QB_STATES.map((s,i) => (
          <React.Fragment key={s}>
            <button onClick={() => setQstate(s)}
              style={{ flex:1, padding:'10px 16px', border:'none', fontSize:13, fontWeight:qstate===s?600:400,
                background: qstate===s ? 'var(--accent)' : 'transparent',
                color: qstate===s ? 'white' : 'var(--ink-3)',
                cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
              <span style={{ width:18, height:18, borderRadius:99, background: qstate===s ? 'rgba(255,255,255,0.25)' : 'var(--surface-3)',
                display:'inline-flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, flexShrink:0 }}>{i+1}</span>
              {STATUS_LABELS[s]}
            </button>
            {i < QB_STATES.length - 1 && <div style={{ width:1, height:40, background:'var(--border)' }} />}
          </React.Fragment>
        ))}
      </div>

      {/* ── STAGE 1: Building ── */}
      {qstate === 'building' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 280px', gap:16 }}>
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {/* Deal selector */}
            <div className="card card-pad" style={{ display:'flex', alignItems:'center', gap:12 }}>
              <div style={{ flex:1 }}>
                <label style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600, display:'block', marginBottom:6 }}>Linked Deal</label>
                <select className="sel" style={{ width:'100%', padding:'7px 10px', borderRadius:6, border:'1px solid var(--border)', background:'var(--surface-2)', fontSize:13 }}
                  value={activeDeal?.id||''} onChange={e => setSelectedDeal(deals.find(d=>d.id===e.target.value))}>
                  {deals.filter(d=>d.stage!=='sold'&&d.stage!=='lost').slice(0,12).map(d => (
                    <option key={d.id} value={d.id}>{d.customer} — {d.id}</option>
                  ))}
                </select>
              </div>
              {activeDeal && (
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontSize:11, color:'var(--ink-3)' }}>Current deal value</div>
                  <div style={{ fontSize:18, fontWeight:700, color:'var(--accent)', fontFamily:'var(--mono)' }}>${(activeDeal.value||0).toLocaleString()}</div>
                </div>
              )}
            </div>

            {/* Line items */}
            <div className="card">
              <div className="card-hd">
                <div className="card-title">Line Items</div>
                <button className="btn sm primary" onClick={() => setShowCatalog(true)}>+ Add product</button>
              </div>
              <table className="tbl">
                <thead>
                  <tr>
                    <th style={{ width:36 }}></th>
                    <th>Description</th>
                    <th style={{ width:60 }}>Qty</th>
                    <th style={{ width:80 }}>Unit</th>
                    <th className="num-col" style={{ width:90 }}>Price</th>
                    <th className="num-col" style={{ width:90 }}>Total</th>
                  </tr>
                </thead>
                <tbody>
                  {lineItems.map(li => (
                    <tr key={li.id}>
                      <td>
                        <button onClick={() => removeItem(li.id)} style={{ background:'none', border:'none', cursor:'pointer', color:'var(--ink-4)', fontSize:15, lineHeight:1, padding:'0 2px' }}>×</button>
                      </td>
                      <td>
                        <div style={{ fontWeight:600, color:'var(--ink)', fontSize:13 }}>{li.name}</div>
                        <input value={li.note} onChange={e=>updateItem(li.id,'note',e.target.value)} placeholder="Add note…"
                          style={{ border:'none', background:'none', fontSize:11, color:'var(--ink-3)', outline:'none', width:'100%', padding:0 }} />
                      </td>
                      <td>
                        <input type="number" value={li.qty} min={0.1} step={0.1} onChange={e=>updateItem(li.id,'qty',Number(e.target.value))}
                          style={{ width:50, border:'1px solid var(--border)', borderRadius:4, padding:'3px 6px', fontSize:12, textAlign:'right', background:'var(--surface-2)' }} />
                      </td>
                      <td style={{ fontSize:11, color:'var(--ink-3)' }}>{typeof li.unit==='string'?li.unit:'ea'}</td>
                      <td className="num-col" style={{ fontFamily:'var(--mono)', fontSize:12 }}>{fmt(li.price)}</td>
                      <td className="num-col" style={{ fontFamily:'var(--mono)', fontWeight:600, fontSize:13 }}>{fmt(li.price*li.qty)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>

              {/* Totals */}
              <div style={{ padding:'14px 20px', borderTop:'1px solid var(--border)', display:'flex', flexDirection:'column', gap:6, alignItems:'flex-end' }}>
                <div style={{ display:'flex', gap:24, fontSize:13, color:'var(--ink-3)' }}>
                  <span>Subtotal</span><span style={{ fontFamily:'var(--mono)', color:'var(--ink)' }}>{fmt(subtotal)}</span>
                </div>
                <div style={{ display:'flex', gap:12, alignItems:'center' }}>
                  <span style={{ fontSize:13, color:'var(--ink-3)' }}>Discount</span>
                  <input type="number" min={0} max={30} value={discount} onChange={e=>setDiscount(Number(e.target.value))}
                    style={{ width:44, border:'1px solid var(--border)', borderRadius:4, padding:'2px 6px', fontSize:12, textAlign:'right' }} />
                  <span style={{ fontSize:12, color:'var(--ink-3)' }}>%</span>
                  <span style={{ fontFamily:'var(--mono)', fontSize:13, color:'var(--lost)' }}>({fmt(discountAmt)})</span>
                </div>
                <div style={{ display:'flex', gap:24, fontSize:13, color:'var(--ink-3)' }}>
                  <span>GST 10%</span><span style={{ fontFamily:'var(--mono)', color:'var(--ink)' }}>{fmt(gst)}</span>
                </div>
                <div style={{ display:'flex', gap:24, fontSize:16, fontWeight:700, color:'var(--ink)', paddingTop:8, borderTop:'2px solid var(--border)' }}>
                  <span>Total AUD</span><span style={{ fontFamily:'var(--mono)' }}>{fmt(total)}</span>
                </div>
              </div>
            </div>

            <div style={{ display:'flex', gap:8 }}>
              <button className="btn" onClick={()=>setQstate('preview')}>Preview quote →</button>
              <button className="btn sm" style={{ marginLeft:'auto', fontSize:12, color:'#7C3AED', borderColor:'#DDD6FE', background:'#F3EEFF' }} disabled={aiBusy || !AI_OK} onClick={suggestDiscount}>{aiBusy ? '✦ Thinking…' : '✦ AI suggest discount'}</button>
            </div>
          </div>

          {/* Sidebar totals */}
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            <div className="card card-pad">
              <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600, marginBottom:10 }}>Quote Summary</div>
              <div style={{ fontSize:32, fontWeight:700, color:'var(--accent)', letterSpacing:'-0.02em', fontFamily:'var(--mono)' }}>{fmt(total)}</div>
              <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:4 }}>{lineItems.length} line items · incl. GST</div>
              {activeDeal && (
                <div style={{ marginTop:12, padding:'8px 10px', background: total > (activeDeal.value||0) ? 'var(--warn-soft)' : 'var(--won-soft)', borderRadius:6 }}>
                  <div style={{ fontSize:11, fontWeight:600, color: total > (activeDeal.value||0) ? 'var(--warn)' : 'var(--won)' }}>
                    {total > (activeDeal.value||0) ? '↑ Quote above deal estimate' : '✓ Within deal estimate'}
                  </div>
                  <div style={{ fontSize:11, color:'var(--ink-3)', marginTop:2 }}>Deal: ${(activeDeal.value||0).toLocaleString()}</div>
                </div>
              )}
            </div>
            <div className="card card-pad">
              <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600, marginBottom:8 }}>Quote Notes</div>
              <textarea value={note} onChange={e=>setNote(e.target.value)} placeholder="Add terms, inclusions, or special notes…"
                rows={5} style={{ width:'100%', border:'1px solid var(--border)', borderRadius:6, padding:'8px 10px', fontSize:12.5, resize:'none', background:'var(--surface-2)', color:'var(--ink-2)', outline:'none', fontFamily:'var(--font)', lineHeight:1.6, boxSizing:'border-box' }} />
            </div>
          </div>

          {/* Catalog drawer */}
          {showCatalog && (
            <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.35)', zIndex:100, display:'flex', justifyContent:'flex-end' }} onClick={()=>setShowCatalog(false)}>
              <div style={{ width:360, background:'var(--surface)', height:'100%', overflowY:'auto', borderLeft:'1px solid var(--border)', padding:'20px 0' }} onClick={e=>e.stopPropagation()}>
                <div style={{ padding:'0 20px 16px', borderBottom:'1px solid var(--border)', marginBottom:8 }}>
                  <div style={{ fontSize:15, fontWeight:600, color:'var(--ink)' }}>Product Catalog</div>
                  <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>Click to add to quote</div>
                </div>
                {cats.map(cat => (
                  <div key={cat}>
                    <div style={{ padding:'10px 20px 4px', fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600 }}>{cat}</div>
                    {QB_PRODUCTS.filter(p=>p.cat===cat).map(p => (
                      <div key={p.id} onClick={()=>addProduct(p)}
                        style={{ padding:'9px 20px', cursor:'pointer', display:'flex', justifyContent:'space-between', alignItems:'center', borderBottom:'1px solid var(--border)' }}
                        onMouseEnter={e=>e.currentTarget.style.background='var(--surface-2)'}
                        onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                        <div style={{ fontSize:13, color:'var(--ink-2)' }}>{p.name}</div>
                        <div style={{ fontSize:12, fontFamily:'var(--mono)', color:'var(--accent)', fontWeight:600 }}>${p.price.toLocaleString()}</div>
                      </div>
                    ))}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* ── STAGE 2: Preview ── */}
      {qstate === 'preview' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 240px', gap:16 }}>
          {/* PDF-style quote */}
          <div style={{ background:'white', border:'1px solid var(--border)', borderRadius:'var(--r-lg)', overflow:'hidden', boxShadow:'var(--shadow-md)' }}>
            <div style={{ background:'var(--accent)', color:'white', padding:'28px 32px', display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
              <div>
                <div style={{ fontSize:22, fontWeight:700, letterSpacing:'-0.02em' }}>Kitchen Proposal</div>
                <div style={{ opacity:0.8, fontSize:13, marginTop:4 }}>Quote #{activeDeal?.id || 'QT-00001'}</div>
              </div>
              <div style={{ textAlign:'right', opacity:0.85, fontSize:12 }}>
                <div style={{ fontWeight:600 }}>Issued 11 Jun 2026</div>
                <div>Valid for 30 days</div>
              </div>
            </div>
            <div style={{ padding:'24px 32px' }}>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:24, marginBottom:24, paddingBottom:24, borderBottom:'1px solid var(--border)' }}>
                <div>
                  <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600, marginBottom:6 }}>Prepared for</div>
                  <div style={{ fontSize:15, fontWeight:600, color:'var(--ink)' }}>{activeDeal?.customer || 'Client Name'}</div>
                  <div style={{ fontSize:13, color:'var(--ink-3)', marginTop:2 }}>{activeDeal?.suburb || 'Location'}</div>
                </div>
                <div>
                  <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600, marginBottom:6 }}>Prepared by</div>
                  <div style={{ fontSize:15, fontWeight:600, color:'var(--ink)' }}>{activeDeal?.repName || 'Designer'}</div>
                  <div style={{ fontSize:13, color:'var(--ink-3)', marginTop:2 }}>Kitchen Design Consultant</div>
                </div>
              </div>
              <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13 }}>
                <thead>
                  <tr style={{ background:'var(--surface-2)', borderRadius:6 }}>
                    {['Description', 'Qty', 'Unit Price', 'Total'].map(h => (
                      <th key={h} style={{ padding:'9px 12px', textAlign:h==='Description'?'left':'right', fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.04em', color:'var(--ink-3)' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {lineItems.map((li,i) => (
                    <tr key={li.id} style={{ borderBottom:'1px solid var(--border)' }}>
                      <td style={{ padding:'10px 12px' }}>
                        <div style={{ fontWeight:500, color:'var(--ink)' }}>{li.name}</div>
                        {li.note && <div style={{ fontSize:11, color:'var(--ink-3)', marginTop:2 }}>{li.note}</div>}
                      </td>
                      <td style={{ padding:'10px 12px', textAlign:'right', fontFamily:'var(--mono)' }}>{li.qty}</td>
                      <td style={{ padding:'10px 12px', textAlign:'right', fontFamily:'var(--mono)' }}>${li.price.toLocaleString()}</td>
                      <td style={{ padding:'10px 12px', textAlign:'right', fontFamily:'var(--mono)', fontWeight:600 }}>${(li.price*li.qty).toLocaleString('en-AU',{minimumFractionDigits:2})}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div style={{ marginTop:16, display:'flex', flexDirection:'column', gap:6, alignItems:'flex-end' }}>
                <div style={{ display:'flex', gap:32, fontSize:13, color:'var(--ink-3)' }}><span>Subtotal</span><span style={{ fontFamily:'var(--mono)', color:'var(--ink)' }}>{fmt(subtotal)}</span></div>
                {discount>0 && <div style={{ display:'flex', gap:32, fontSize:13, color:'var(--lost)' }}><span>Discount {discount}%</span><span style={{ fontFamily:'var(--mono)' }}>({fmt(discountAmt)})</span></div>}
                <div style={{ display:'flex', gap:32, fontSize:13, color:'var(--ink-3)' }}><span>GST 10%</span><span style={{ fontFamily:'var(--mono)', color:'var(--ink)' }}>{fmt(gst)}</span></div>
                <div style={{ display:'flex', gap:32, fontSize:17, fontWeight:700, color:'var(--ink)', paddingTop:10, borderTop:'2px solid var(--ink)', marginTop:4 }}><span>Total AUD</span><span style={{ fontFamily:'var(--mono)', color:'var(--accent)' }}>{fmt(total)}</span></div>
              </div>
              {note && <div style={{ marginTop:20, padding:'12px 14px', background:'var(--surface-2)', borderRadius:6, fontSize:12.5, color:'var(--ink-2)', lineHeight:1.6 }}>{note}</div>}
            </div>
          </div>
          {/* Actions */}
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            <button className="btn primary" style={{ justifyContent:'center' }} disabled={saving} onClick={sendQuote}>{saving ? 'Saving…' : 'Send to client ↗'}</button>
            <button className="btn" style={{ justifyContent:'center' }} onClick={() => toast('Generating PDF… quote downloaded')}>Download PDF</button>
            <button className="btn sm" style={{ justifyContent:'center' }} onClick={() => { try { navigator.clipboard && navigator.clipboard.writeText('https://app.stagevo.io/quote/' + (activeDeal?.id || 'QT-00001')); } catch(e){} toast('Quote link copied to clipboard'); }}>Copy link</button>
            <button className="btn sm" onClick={()=>setQstate('building')} style={{ justifyContent:'center', color:'var(--ink-3)' }}>← Edit</button>
            <div style={{ marginTop:8, padding:'10px 12px', background:'#F3EEFF', border:'1px solid #DDD6FE', borderRadius:8, fontSize:12, color:'#5B21B6', lineHeight:1.6 }}>
              <div style={{ fontWeight:700, marginBottom:4 }}>✦ AI Insight</div>
              {aiTip || 'Deals at this value range close 40% faster when sent within 24 hours of the design appointment.'}
            </div>
          </div>
        </div>
      )}

      {/* ── STAGE 3: Sent / Signed ── */}
      {qstate === 'sent' && (
        <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:16, padding:'32px 0' }}>
          <div style={{ width:64, height:64, borderRadius:99, background:'var(--won-soft)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:28 }}>✓</div>
          <div style={{ textAlign:'center' }}>
            <div style={{ fontSize:20, fontWeight:700, color:'var(--ink)', letterSpacing:'-0.02em' }}>Quote sent to {activeDeal?.customer || 'client'}</div>
            <div style={{ fontSize:13, color:'var(--ink-3)', marginTop:4 }}>Sent 11 Jun 2026 · {fmt(total)} · awaiting signature</div>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12, width:'100%', maxWidth:560 }}>
            {[{ label:'Delivered', status:'done' }, { label:'Opened', status:'pending' }, { label:'Signed', status:'pending' }].map(step => (
              <div key={step.label} className="card card-pad" style={{ textAlign:'center' }}>
                <div style={{ fontSize:20, marginBottom:6 }}>{step.status==='done' ? '✅' : '⏳'}</div>
                <div style={{ fontSize:13, fontWeight:600, color: step.status==='done' ? 'var(--won)' : 'var(--ink-3)' }}>{step.label}</div>
              </div>
            ))}
          </div>
          <div style={{ display:'flex', gap:8 }}>
            <button className="btn sm" onClick={() => toast('Reminder sent to ' + (activeDeal?.customer || 'client'))}>Send reminder</button>
            <button className="btn sm" onClick={() => toast('Opening customer portal…')}>View in portal</button>
            <button className="btn sm" onClick={()=>setQstate('building')} style={{ color:'var(--ink-3)' }}>← Edit quote</button>
          </div>
        </div>
      )}
    </div>
  );
}

window.QuoteBuilder = QuoteBuilder;
