// crm-rental.jsx — Hardware Rental (manufacturer's Shipping Information Form)
//
// Lives beside Order Forms on the account. The form is the manufacturer's own
// PDF, filled server-side (GET /api/rental-forms/{id}/pdf) so what the customer
// signs and what the manufacturer receives is exactly their document. Two
// separate steps from an order: a rental form is created on demand and can be
// pre-filled from any order form on the account — or started blank.

const RENTAL_SHIP_METHODS = ['UPS Ground', 'UPS Next Day', 'FedEx 2nd Day', 'Other'];

const blankRentalShipment = () => ({
  part1:'', qty1:'', part2:'', qty2:'', company:'', contact:'', address:'', address2:'', cityStateZip:'',
});

const rentalCsz = (city, state, zip) =>
  [city, [state, zip].filter(Boolean).join(' ')].filter(Boolean).join(', ');

// Order-form line → "PART (Description)" as written on the manufacturer's form.
// The Part No. field is ~3" wide, so keep the label to ~38 characters: the part
// number always, then as much of the description as fits.
const RENTAL_PART_MAX = 38;
const rentalPartLabel = l => {
  const p = (l.partNumber || '').trim(), d = (l.description || '').trim();
  if (!p) return d.slice(0, RENTAL_PART_MAX);
  if (!d) return p;
  const room = RENTAL_PART_MAX - p.length - 3;           // " (" + ")"
  if (room < 4) return p;
  const desc = d.length > room ? d.slice(0, room - 1).trimEnd() + '…' : d;
  return `${p} (${desc})`;
};

// Map a full order form onto rental-form fields. Rental hardware = monthly
// lines first, then anything else with a part number; the form holds two
// part lines per shipment block.
function rentalFromOrder(order) {
  const csz = rentalCsz(order.billToCity, order.billToState, order.billToZip);
  const ship = order.shipSameAsBill
    ? { company: order.billToCompany, contact: order.billToName, address: order.billToAddress, csz }
    : { company: order.shipToCompany, contact: order.shipToName, address: order.shipToAddress,
        csz: rentalCsz(order.shipToCity, order.shipToState, order.shipToZip) };
  const lines = (order.lines || []).filter(l => (l.partNumber || '').trim() || (l.description || '').trim());
  const hw = [...lines.filter(l => l.billingType === 'Monthly'), ...lines.filter(l => l.billingType !== 'Monthly')].slice(0, 2);
  const qty = l => (l.quantity == null ? '' : String(Number(l.quantity)));
  return {
    orderFormId:  order.id,
    poNumber:     (typeof toOrderNumber === 'function' ? toOrderNumber(order.createdAt) : '') || order.custPo || '',
    poDate:       order.orderDate || '',
    customerName: order.billToCompany || '',
    address:      order.billToAddress || '',
    cityStateZip: csz,
    shipments: [{
      ...blankRentalShipment(),
      part1: hw[0] ? rentalPartLabel(hw[0]) : '', qty1: hw[0] ? qty(hw[0]) : '',
      part2: hw[1] ? rentalPartLabel(hw[1]) : '', qty2: hw[1] ? qty(hw[1]) : '',
      company: ship.company || '', contact: ship.contact || '', address: ship.address || '', cityStateZip: ship.csz || '',
    }],
  };
}

// ══════════════════════════════════════════════════════════
// ACCOUNT HARDWARE RENTAL TAB
// ══════════════════════════════════════════════════════════
function AccountRentalFormsTab({ account, user, showToast, onChanged }) {
  const [rows,     setRows]     = useState([]);
  const [loading,  setLoading]  = useState(true);
  const [view,     setView]     = useState(null);   // {mode:'new'} | {mode:'edit', form} | {mode:'preview', form}
  const [deleting, setDeleting] = useState(null);

  const load = async () => {
    setLoading(true);
    try { setRows(await CRM.RentalFormsAPI.getByAccount(account.id)); }
    catch (e) { showToast('Failed to load rental forms: ' + e.message, 'error'); }
    finally { setLoading(false); }
  };
  useEffect(() => { load(); }, [account.id]);

  const refresh = () => { load(); onChanged && onChanged(); };

  const handleSaved = (saved) => {
    refresh();
    setView({ mode:'preview', form: saved });
  };

  const openPreview = async (row) => {
    try { setView({ mode:'preview', form: await CRM.RentalFormsAPI.getOne(row.id) }); }
    catch (e) { showToast('Failed to load the form: ' + e.message, 'error'); }
  };

  const doDelete = async (row) => {
    if (!confirm('Delete this hardware rental form? This cannot be undone.')) return;
    setDeleting(row.id);
    try {
      await CRM.RentalFormsAPI.delete(row.id);
      refresh();
      showToast('Rental form deleted.', 'success');
    } catch (e) { showToast('Delete failed: ' + e.message, 'error'); }
    finally { setDeleting(null); }
  };

  if (view?.mode === 'new' || view?.mode === 'edit') {
    return (
      <RentalFormIntake account={account} user={user} existing={view.form || null}
        onSaved={handleSaved} onCancel={() => setView(view.form ? { mode:'preview', form: view.form } : null)}
        showToast={showToast} />
    );
  }
  if (view?.mode === 'preview') {
    return (
      <RentalFormPreview form={view.form} account={account}
        onBack={() => { refresh(); setView(null); }}
        onEdit={() => setView({ mode:'edit', form: view.form })}
        onNewForm={() => setView({ mode:'new' })}
        onChanged={updated => setView({ mode:'preview', form: updated })}
        showToast={showToast} />
    );
  }

  const status = r => r.signedAt
    ? <span style={{ background:'#F0FDF4', color:'#166534', border:'1px solid #BBF7D0', borderRadius:4, padding:'2px 7px', fontSize:11, fontWeight:700 }}>
        ✔ Signed {r.signedMethod === 'offline' ? 'on paper' : 'online'}
      </span>
    : r.sentAt
      ? <span style={{ background:'#FFFBEB', color:'#92400E', border:'1px solid #FDE68A', borderRadius:4, padding:'2px 7px', fontSize:11, fontWeight:700 }}>
          ✉ Sent {new Date(r.sentAt).toLocaleDateString()}
        </span>
      : <span style={{ background:'var(--off)', color:'var(--g600)', border:'1px solid var(--g200)', borderRadius:4, padding:'2px 7px', fontSize:11, fontWeight:700 }}>
          Draft
        </span>;

  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6 }}>
        <h3 style={{ margin:0, fontSize:15, fontWeight:700, color:'var(--navy)' }}>Hardware Rental</h3>
        <button className="btn btn-primary btn-sm" onClick={() => setView({ mode:'new' })}>
          + New Shipping Form
        </button>
      </div>
      <div style={{ fontSize:12, color:'var(--g400)', marginBottom:16 }}>
        The manufacturer's shipping authorization form for rented hardware — generated from their own template and e-signed by the customer.
        Pre-fill it from an order form or start blank; not every rental needs one.
      </div>

      {loading ? (
        <div className="empty"><div className="empty-icon">⏳</div><div className="empty-text">Loading…</div></div>
      ) : rows.length === 0 ? (
        <div className="empty">
          <div className="empty-icon">🚚</div>
          <div className="empty-text">No hardware rental forms yet.</div>
        </div>
      ) : (
        <div className="card">
          <table className="tbl">
            <thead>
              <tr>
                <th>PO #</th>
                <th>PO Date</th>
                <th>Customer</th>
                <th>Shipping</th>
                <th style={{textAlign:'center'}}>Ship-to</th>
                <th>Status</th>
                <th>Created By</th>
                <th style={{width:130}}></th>
              </tr>
            </thead>
            <tbody>
              {rows.map(r => (
                <tr key={r.id}>
                  <td style={{ fontWeight:600, color:'var(--navy)' }}>{r.poNumber || '—'}</td>
                  <td>{r.poDate ? new Date(r.poDate + 'T00:00:00').toLocaleDateString() : '—'}</td>
                  <td style={{ color:'var(--navy)', fontWeight:500 }}>{r.customerName || '—'}</td>
                  <td style={{ color:'var(--g600)' }}>{r.shipMethod}</td>
                  <td style={{ textAlign:'center', color:'var(--g400)' }}>{r.shipmentCount}</td>
                  <td>{status(r)}</td>
                  <td style={{ color:'var(--g400)' }}>{r.createdByName || '—'}</td>
                  <td>
                    <div style={{ display:'flex', gap:5, justifyContent:'flex-end' }}>
                      <button className="btn btn-ghost btn-xs" onClick={() => openPreview(r)}>📄 Open</button>
                      <button className="btn btn-xs" disabled={deleting === r.id}
                        style={{ background:'#FEF2F2', color:'#991B1B', border:'1px solid #FECACA' }}
                        onClick={() => doDelete(r)}>
                        {deleting === r.id ? '…' : '🗑'}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════
// INTAKE (new / edit)
// ══════════════════════════════════════════════════════════
function RentalFormIntake({ account, user, existing, onSaved, onCancel, showToast }) {
  const today = new Date().toISOString().slice(0, 10);

  // Account defaults for a blank form: structured address first, legacy string second.
  const _parsed = (account.address1 || account.city || account.state || account.zip)
    ? { address: [account.address1, account.address2].filter(Boolean).join(', '),
        city: account.city || '', state: account.state || '', zip: account.zip || '' }
    : (typeof parseAccountAddress === 'function' ? parseAccountAddress(account.address) : { address: account.address || '', city:'', state:'', zip:'' });
  const acctCsz = rentalCsz(_parsed.city, _parsed.state, _parsed.zip);

  const initial = existing ? {
    orderFormId:  existing.orderFormId || null,
    poNumber:     existing.poNumber || '',
    poDate:       existing.poDate || '',
    customerName: existing.customerName || '',
    address:      existing.address || '',
    cityStateZip: existing.cityStateZip || '',
    shipMethod:   existing.shipMethod || 'UPS Ground',
    shipOther:    existing.shipOther || '',
    shipments:    (existing.shipments && existing.shipments.length ? existing.shipments : [blankRentalShipment()])
                    .map(s => ({ ...blankRentalShipment(), ...Object.fromEntries(Object.entries(s).map(([k, v]) => [k, v || ''])) })),
  } : {
    orderFormId:  null,
    poNumber:     '',
    poDate:       today,
    customerName: account.companyName || '',
    address:      _parsed.address,
    cityStateZip: acctCsz,
    shipMethod:   'UPS Ground',
    shipOther:    '',
    shipments:    [{ ...blankRentalShipment(), company: account.companyName || '', address: _parsed.address, cityStateZip: acctCsz }],
  };

  const [form,    setForm]    = useState(initial);
  const [orders,  setOrders]  = useState([]);
  const [orderSel, setOrderSel] = useState(existing?.orderFormId || '');
  const [saving,  setSaving]  = useState(false);
  const [prefilling, setPrefilling] = useState(false);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const setShip = (i, k, v) => setForm(f => ({ ...f, shipments: f.shipments.map((s, j) => j === i ? { ...s, [k]: v } : s) }));

  useEffect(() => {
    CRM.OrderFormsAPI.listForAccount(account.id).then(setOrders).catch(() => {});
    if (!existing) {
      // Primary contact → contact name on the first ship-to block
      CRM.ContactsAPI.getByAccount(account.id).then(list => {
        const primary = list.find(c => c.isPrimary) || list.find(c => c.primary);
        if (primary?.name) setForm(f => ({ ...f, shipments: f.shipments.map((s, i) => i === 0 && !s.contact ? { ...s, contact: primary.name } : s) }));
      }).catch(() => {});
    }
  }, [account.id]);

  const prefill = async (orderId) => {
    setOrderSel(orderId);
    if (!orderId) { set('orderFormId', null); return; }
    setPrefilling(true);
    try {
      const full = await CRM.OrderFormsAPI.getOne(orderId);
      const mapped = rentalFromOrder(full);
      // Keep the contact name we already have if the order has none
      setForm(f => ({ ...f, ...mapped,
        shipments: mapped.shipments.map((s, i) => ({ ...s, contact: s.contact || f.shipments[i]?.contact || '' })) }));
      showToast('Pre-filled from the order form — review before saving.', 'success');
    } catch (e) { showToast('Could not load that order: ' + e.message, 'error'); }
    finally { setPrefilling(false); }
  };

  const addShipment = () => setForm(f => f.shipments.length >= 3 ? f : ({ ...f, shipments: [...f.shipments, blankRentalShipment()] }));
  const removeShipment = i => setForm(f => ({ ...f, shipments: f.shipments.filter((_, j) => j !== i) }));
  const copyCustomer = i => setForm(f => ({ ...f, shipments: f.shipments.map((s, j) => j === i
    ? { ...s, company: f.customerName, address: f.address, cityStateZip: f.cityStateZip } : s) }));

  const doSave = async () => {
    if (!form.customerName.trim()) return showToast('Customer name is required.', 'error');
    if (form.shipMethod === 'Other' && !form.shipOther.trim()) return showToast('Describe the "Other" shipping method.', 'error');
    setSaving(true);
    try {
      const payload = {
        orderFormId:  form.orderFormId || null,
        poNumber:     form.poNumber || null,
        poDate:       form.poDate || null,
        customerName: form.customerName || null,
        address:      form.address || null,
        cityStateZip: form.cityStateZip || null,
        shipMethod:   form.shipMethod,
        shipOther:    form.shipMethod === 'Other' ? (form.shipOther || null) : null,
        shipments:    form.shipments.map(s => Object.fromEntries(Object.entries(s).map(([k, v]) => [k, (v || '').trim() || null]))),
      };
      const saved = existing
        ? await CRM.RentalFormsAPI.update(existing.id, payload)
        : await CRM.RentalFormsAPI.create(account.id, payload);
      showToast('Shipping form saved.', 'success');
      onSaved(saved);
    } catch (e) {
      showToast('Save failed: ' + e.message, 'error');
    } finally { setSaving(false); }
  };

  const sectionHd = (label, extra) => (
    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8, marginTop:18 }}>
      <div style={{ fontWeight:700, fontSize:12, color:'var(--g400)', textTransform:'uppercase', letterSpacing:'0.05em' }}>{label}</div>
      {extra}
    </div>
  );
  const orderLabel = o => `#${typeof toOrderNumber === 'function' ? toOrderNumber(o.createdAt) : ''} — ${o.orderDate ? new Date(o.orderDate + 'T00:00:00').toLocaleDateString() : ''}${o.custPo ? ` (PO ${o.custPo})` : ''} · ${o.lineCount} line${o.lineCount === 1 ? '' : 's'}`;

  return (
    <div style={{ position:'fixed', inset:0, zIndex:1100, background:'var(--folio-bg, #F7F7F5)', overflowY:'auto' }}>
    <div style={{ maxWidth:980, margin:'0 auto', padding:'28px 24px 60px' }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6 }}>
        <div>
          <div style={{ fontSize:20, fontWeight:800, color:'var(--navy)' }}>{existing ? 'Edit' : 'New'} Hardware Rental Shipping Form</div>
          <div style={{ fontSize:13, color:'var(--g400)' }}>{account.companyName} · manufacturer's Shipping Information Form</div>
        </div>
        <button className="btn btn-ghost" onClick={onCancel} disabled={saving}>✕ Cancel</button>
      </div>

      {!existing && (
        <div className="card card-pad" style={{ marginTop:14, marginBottom:4, background:'var(--off)', display:'flex', gap:14, alignItems:'center', flexWrap:'wrap' }}>
          <div style={{ fontWeight:700, fontSize:13, color:'var(--navy)' }}>Pre-fill from an order form</div>
          <select value={orderSel} onChange={e => prefill(e.target.value)} disabled={prefilling} style={{ minWidth:320 }}>
            <option value="">— Start blank (account details only) —</option>
            {orders.map(o => <option key={o.id} value={o.id}>{orderLabel(o)}</option>)}
          </select>
          {prefilling && <span style={{ fontSize:12, color:'var(--g400)' }}>Loading…</span>}
          <span style={{ fontSize:12, color:'var(--g400)' }}>Optional — copies PO #, customer, ship-to and the hardware lines.</span>
        </div>
      )}

      {sectionHd('Customer & PO')}
      <div className="card card-pad" style={{ marginBottom:4 }}>
        <div className="fg fg-3" style={{ marginBottom:12 }}>
          <div className="field"><label>PO Number <span style={{ fontWeight:400, color:'var(--g400)' }}>(same as on the order form)</span></label>
            <input value={form.poNumber} onChange={e => set('poNumber', e.target.value)} placeholder="Order # / PO #" /></div>
          <div className="field"><label>PO Date</label>
            <input type="date" value={form.poDate} onChange={e => set('poDate', e.target.value)} /></div>
          <div className="field"><label>Customer Name *</label>
            <input value={form.customerName} onChange={e => set('customerName', e.target.value)} /></div>
        </div>
        <div className="fg fg-2" style={{ marginBottom:0 }}>
          <div className="field"><label>Address</label>
            <input value={form.address} onChange={e => set('address', e.target.value)} /></div>
          <div className="field"><label>City, State, Zip</label>
            <input value={form.cityStateZip} onChange={e => set('cityStateZip', e.target.value)} placeholder="Brooklyn, NY 11201" /></div>
        </div>
      </div>

      {sectionHd('Shipping Method')}
      <div className="card card-pad" style={{ marginBottom:4 }}>
        <div style={{ display:'flex', gap:22, flexWrap:'wrap', alignItems:'center' }}>
          {RENTAL_SHIP_METHODS.map(m => (
            <label key={m} style={{ display:'flex', alignItems:'center', gap:6, cursor:'pointer', fontSize:13 }}>
              <input type="radio" name="rental-ship" checked={form.shipMethod === m} onChange={() => set('shipMethod', m)} /> {m}
            </label>
          ))}
          {form.shipMethod === 'Other' && (
            <input value={form.shipOther} onChange={e => set('shipOther', e.target.value)} placeholder="Please specify" style={{ maxWidth:260 }} />
          )}
        </div>
        <div style={{ fontSize:11, color:'var(--g400)', marginTop:8 }}>
          All clocks ship UPS Ground unless otherwise specified and paid for by the customer. Anything other than UPS Ground requires the customer's signature — which this form collects.
        </div>
      </div>

      {sectionHd('Hardware Rental Shipping Information (Part No. fields hold about 38 characters — longer text is shrunk, then trimmed with …)',
        form.shipments.length < 3 && <button className="btn btn-ghost btn-sm" onClick={addShipment}>+ Add ship-to location</button>)}
      {form.shipments.map((s, i) => (
        <div key={i} className="card card-pad" style={{ marginBottom:12 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10 }}>
            <div style={{ fontWeight:700, fontSize:13, color:'var(--navy)' }}>Ship-to {form.shipments.length > 1 ? `#${i + 1}` : ''}</div>
            <div style={{ display:'flex', gap:6 }}>
              <button className="btn btn-ghost btn-xs" onClick={() => copyCustomer(i)}>Same as customer</button>
              {form.shipments.length > 1 && <button className="btn btn-ghost btn-xs" onClick={() => removeShipment(i)}>Remove</button>}
            </div>
          </div>
          <div className="fg fg-4" style={{ marginBottom:8 }}>
            <div className="field" style={{ gridColumn:'span 3' }}><label>Part No.</label>
              <input value={s.part1} onChange={e => setShip(i, 'part1', e.target.value)} placeholder="e.g. TC-GT8-SFR (GT8 w/Fingerprint)" maxLength={60} /></div>
            <div className="field"><label>Qty</label>
              <input value={s.qty1} onChange={e => setShip(i, 'qty1', e.target.value)} /></div>
          </div>
          <div className="fg fg-4" style={{ marginBottom:12 }}>
            <div className="field" style={{ gridColumn:'span 3' }}><label>Part No.</label>
              <input value={s.part2} onChange={e => setShip(i, 'part2', e.target.value)} maxLength={60} /></div>
            <div className="field"><label>Qty</label>
              <input value={s.qty2} onChange={e => setShip(i, 'qty2', e.target.value)} /></div>
          </div>
          <div className="fg fg-2" style={{ marginBottom:8 }}>
            <div className="field"><label>Company Name</label>
              <input value={s.company} onChange={e => setShip(i, 'company', e.target.value)} /></div>
            <div className="field"><label>Contact Name</label>
              <input value={s.contact} onChange={e => setShip(i, 'contact', e.target.value)} /></div>
          </div>
          <div className="fg fg-3" style={{ marginBottom:0 }}>
            <div className="field"><label>Address</label>
              <input value={s.address} onChange={e => setShip(i, 'address', e.target.value)} /></div>
            <div className="field"><label>Address 2</label>
              <input value={s.address2} onChange={e => setShip(i, 'address2', e.target.value)} placeholder="Suite, floor, attn…" /></div>
            <div className="field"><label>City, State, Zip</label>
              <input value={s.cityStateZip} onChange={e => setShip(i, 'cityStateZip', e.target.value)} /></div>
          </div>
        </div>
      ))}

      <div style={{ display:'flex', gap:10, justifyContent:'flex-end', marginTop:18, marginBottom:30 }}>
        <button className="btn btn-ghost" onClick={onCancel} disabled={saving}>Cancel</button>
        <button className="btn btn-primary" onClick={doSave} disabled={saving}>
          {saving ? 'Saving…' : '💾 Save & Preview'}
        </button>
      </div>
    </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════
// PREVIEW — the server-rendered PDF, plus send / sign actions
// ══════════════════════════════════════════════════════════
function RentalFormPreview({ form, account, onBack, onEdit, onNewForm, onChanged, showToast }) {
  const fileBase = `${String(form.accountName || account?.companyName || 'Rental').replace(/[\\/:*?"<>|]+/g, '').trim().slice(0, 60)} Hardware Rental Shipping Form ${form.poDate || ''}`.trim();
  const bust = `${form.updatedAt || ''}-${form.signedAt || ''}`;
  const pdfUrl = CRM.RentalFormsAPI.pdfUrl(form.id, bust);

  const reload = async () => {
    try { onChanged && onChanged(await CRM.RentalFormsAPI.getOne(form.id)); } catch { /* keep current */ }
  };

  // E-signature: email the customer a secure link (sign-rental.html?t=token) with the PDF attached.
  const [signBusy, setSignBusy] = useState(false);
  const sendForSign = async () => {
    const email = (prompt('Send the signature request to:', form.sentTo || account?.email || '') || '').trim();
    if (!email) return;
    const message = (prompt('Optional note to include in the email (leave blank for none):') || '').trim();
    setSignBusy(true);
    try {
      const r = await CRM.RentalFormsAPI.sendSign(form.id, email, message || null);
      showToast(`Signature request sent to ${r.to}.`, 'success');
      await reload();
    } catch (e) { showToast('Send failed: ' + e.message, 'error'); }
    finally { setSignBusy(false); }
  };

  const copyLink = async () => {
    try {
      const r = await CRM.RentalFormsAPI.signLink(form.id);
      await navigator.clipboard.writeText(r.url);
      showToast('Sign link copied to the clipboard.', 'success');
    } catch (e) { showToast('Could not copy the link: ' + e.message, 'error'); }
  };

  // Email the PDF through the shared email modal
  const [emailFile, setEmailFile] = useState(null);
  const [pdfBusy, setPdfBusy] = useState(false);
  const doEmail = async () => {
    setPdfBusy(true);
    try { setEmailFile(await CRM.RentalFormsAPI.fetchPdfFile(form.id, `${fileBase}${form.signedAt ? ' (signed)' : ''}.pdf`)); }
    catch (e) { showToast(e.message, 'error'); }
    finally { setPdfBusy(false); }
  };

  // Offline sign-off (paper copy returned)
  const [offlineOpen, setOfflineOpen] = useState(false);
  const [offBusy, setOffBusy] = useState(false);
  const [off, setOff] = useState({ name:'', date: new Date().toISOString().split('T')[0] });
  const offFileRef = React.useRef();
  const saveOffline = async () => {
    if (!off.name.trim()) { showToast('Enter the signer\'s name.', 'error'); return; }
    setOffBusy(true);
    try {
      const r = await CRM.RentalFormsAPI.signOffline(form.id, off.name.trim(), off.date || null, offFileRef.current?.files?.[0] || null);
      showToast(`Recorded — signed on paper by ${off.name.trim()}${r.scan ? ` (scan "${r.scan}" attached)` : ''}.`, 'success');
      setOfflineOpen(false);
      await reload();
    } catch (e) { showToast('Failed: ' + e.message, 'error'); }
    finally { setOffBusy(false); }
  };

  const barBtn = { background:'transparent', color:'#fff', border:'1px solid rgba(255,255,255,0.5)', fontSize:13 };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:9000, overflowY:'auto', padding:'24px 20px 90px' }}>
      <div style={{ position:'fixed', bottom:0, left:0, right:0, background:'#162534', padding:'12px 24px', display:'flex', justifyContent:'space-between', alignItems:'center', zIndex:9001, gap:10, flexWrap:'wrap' }}>
        <div style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
          <button className="btn" style={barBtn} onClick={onBack}>← Back to Hardware Rental</button>
          {!form.signedAt && onEdit && <button className="btn" style={barBtn} onClick={onEdit}>✏ Edit</button>}
          {onNewForm && <button className="btn" style={barBtn} onClick={onNewForm}>+ New Shipping Form</button>}
        </div>
        <div style={{ display:'flex', gap:10, alignItems:'center', flexWrap:'wrap' }}>
          {form.signedAt ? (
            <span style={{ background:'#F0FDF4', color:'#166534', border:'1px solid #BBF7D0', borderRadius:6, padding:'8px 14px', fontSize:13, fontWeight:700 }}>
              ✔ Signed {form.signedMethod === 'offline' ? 'on paper' : 'online'} by {form.signedByName} · {new Date(form.signedAt).toLocaleDateString()}
              {form.signedScanName && (
                <a href={`/api/rental-forms/${form.id}/signed-scan`} target="_blank" rel="noopener"
                  style={{ marginLeft:8, color:'#166534', textDecoration:'underline', fontWeight:600 }}>view scan</a>
              )}
            </span>
          ) : (
            <React.Fragment>
              {form.sentAt && <span style={{ color:'#FDE68A', fontSize:12 }}>Sent to {form.sentTo} · {new Date(form.sentAt).toLocaleDateString()}{form.signViewedAt ? ' · opened' : ''}</span>}
              <button className="btn" style={barBtn} onClick={() => setOfflineOpen(true)}>📄 Signed on paper?</button>
              <button className="btn" style={barBtn} onClick={copyLink}>🔗 Copy sign link</button>
              <button className="btn" style={{ background:'#BC141E', color:'#fff', fontSize:15, padding:'10px 22px' }}
                onClick={sendForSign} disabled={signBusy}>
                {signBusy ? 'Sending…' : (form.sentAt ? '✍ Re-send for signature' : '✍ Send for signature')}
              </button>
            </React.Fragment>
          )}
          <a className="btn" style={{ ...barBtn, textDecoration:'none' }} href={pdfUrl} target="_blank" rel="noopener">⬇ Download PDF</a>
          <button className="btn" style={barBtn} onClick={doEmail} disabled={pdfBusy}>{pdfBusy ? 'Preparing…' : '✉ Email PDF'}</button>
        </div>
      </div>

      <div style={{ maxWidth:900, margin:'0 auto', background:'#fff', borderRadius:8, boxShadow:'0 10px 40px rgba(0,0,0,0.35)', overflow:'hidden' }}>
        <div style={{ padding:'10px 16px', borderBottom:'1px solid #E2E8F0', display:'flex', justifyContent:'space-between', alignItems:'center', fontSize:12, color:'#64748B' }}>
          <span><strong style={{ color:'#162534' }}>{form.accountName || account?.companyName}</strong> · Hardware Rental Shipping Form{form.poNumber ? ` · PO ${form.poNumber}` : ''}</span>
          <span>{form.signedAt ? 'Executed copy' : 'Generated from the manufacturer\'s template'}</span>
        </div>
        <iframe title="Shipping form" src={pdfUrl} style={{ width:'100%', height:'calc(100vh - 170px)', minHeight:640, border:'none', display:'block' }} />
      </div>

      {offlineOpen && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.55)', zIndex:9500, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}
          onClick={() => setOfflineOpen(false)}>
          <div style={{ background:'#fff', borderRadius:12, padding:'24px 28px', width:'min(440px,100%)', fontFamily:'var(--font)' }}
            onClick={e => e.stopPropagation()}>
            <div style={{ fontSize:16, fontWeight:800, color:'var(--navy)', marginBottom:4 }}>Record paper sign-off</div>
            <div style={{ fontSize:12, color:'var(--g600)', marginBottom:16 }}>
              The customer signed a printed copy. Record who signed and, if you have it, attach the scan — a PDF scan becomes the executed document.
            </div>
            <div className="field"><label>Signer's name *</label>
              <input value={off.name} onChange={e => setOff(o => ({...o, name: e.target.value}))} placeholder="As written on the paper copy" /></div>
            <div className="field"><label>Date signed</label>
              <input type="date" value={off.date} onChange={e => setOff(o => ({...o, date: e.target.value}))} /></div>
            <div className="field"><label>Scan of the signed copy <span style={{fontWeight:400,color:'var(--g400)'}}>(optional, PDF or image)</span></label>
              <input type="file" ref={offFileRef} accept=".pdf,image/*" /></div>
            <div style={{ display:'flex', justifyContent:'flex-end', gap:8, marginTop:18 }}>
              <button className="btn btn-ghost" onClick={() => setOfflineOpen(false)}>Cancel</button>
              <button className="btn btn-primary" onClick={saveOffline} disabled={offBusy}>
                {offBusy ? 'Saving…' : '✔ Record sign-off'}
              </button>
            </div>
          </div>
        </div>
      )}

      {emailFile && (
        <SendEmailModal
          toEmail={form.sentTo || account?.email || ''}
          toName={form.customerName || account?.companyName || ''}
          accountId={form.accountId || account?.id || null}
          initialFiles={[emailFile]}
          initialSubject={`Hardware Rental Shipping Form — ${form.customerName || account?.companyName || ''}`.trim()}
          zIndex={9500}
          onClose={() => setEmailFile(null)}
          showToast={showToast}
        />
      )}
    </div>
  );
}

Object.assign(window, { AccountRentalFormsTab, RentalFormIntake, RentalFormPreview });
