// MaxAMove — Bill of Lading + Digital Signature Pad

const { useState, useRef, useEffect, useCallback } = React;

// ─── SIGNATURE PAD ───────────────────────────────────────────
function SignaturePad({ label, value, onChange, height = 140 }) {
  const canvasRef = useRef(null);
  const drawing = useRef(false);
  const lastPos = useRef(null);
  const [isEmpty, setIsEmpty] = useState(!value);

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    canvas.width = canvas.offsetWidth * window.devicePixelRatio;
    canvas.height = height * window.devicePixelRatio;
    ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    ctx.strokeStyle = '#0f172a';
    ctx.lineWidth = 2.5;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    if (value) {
      const img = new Image();
      img.onload = () => ctx.drawImage(img, 0, 0, canvas.offsetWidth, height);
      img.src = value;
    }
  }, []);

  const getPos = (e) => {
    const canvas = canvasRef.current;
    const rect = canvas.getBoundingClientRect();
    const touch = e.touches ? e.touches[0] : e;
    return { x: touch.clientX - rect.left, y: touch.clientY - rect.top };
  };

  const startDraw = (e) => {
    e.preventDefault();
    drawing.current = true;
    lastPos.current = getPos(e);
    const ctx = canvasRef.current.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(lastPos.current.x, lastPos.current.y);
  };

  const draw = (e) => {
    e.preventDefault();
    if (!drawing.current) return;
    const ctx = canvasRef.current.getContext('2d');
    const pos = getPos(e);
    ctx.lineTo(pos.x, pos.y);
    ctx.stroke();
    lastPos.current = pos;
    setIsEmpty(false);
  };

  const endDraw = (e) => {
    e.preventDefault();
    if (!drawing.current) return;
    drawing.current = false;
    onChange(canvasRef.current.toDataURL('image/png'));
  };

  const clear = () => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.offsetWidth, height);
    setIsEmpty(true);
    onChange(null);
  };

  return (
    <div>
      {label && <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)', marginBottom: 6 }}>{label}</div>}
      <div style={{ position: 'relative', border: `2px solid ${isEmpty ? 'var(--border)' : 'var(--accent)'}`, borderRadius: 10, background: '#fafafa', overflow: 'hidden', touchAction: 'none', cursor: 'crosshair' }}>
        <canvas
          ref={canvasRef}
          style={{ display: 'block', width: '100%', height }}
          onMouseDown={startDraw} onMouseMove={draw} onMouseUp={endDraw} onMouseLeave={endDraw}
          onTouchStart={startDraw} onTouchMove={draw} onTouchEnd={endDraw}
        />
        {isEmpty && (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none', color: '#ccc', fontSize: 14, fontWeight: 500, gap: 6 }}>
            <Icon name="signature" size={16} color="#ccc"/> Sign here
          </div>
        )}
        {!isEmpty && (
          <button onClick={clear} style={{ position: 'absolute', top: 8, right: 8, padding: '4px 10px', borderRadius: 6, border: 'none', background: '#fee2e2', color: '#ef4444', fontSize: 11, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>Clear</button>
        )}
      </div>
      {!isEmpty && <div style={{ fontSize: 11, color: '#16a34a', marginTop: 4, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="check" size={11}/> Signature captured</div>}
    </div>
  );
}

// ─── BOL LIST ────────────────────────────────────────────────
function BOLView({ jobs }) {
  const [bols, setBols] = useState(() => {
    try { return JSON.parse(localStorage.getItem('crm_bols')) || []; } catch { return []; }
  });
  const [selected, setSelected] = useState(null);
  const [creating, setCreating] = useState(false);
  const [newFromJob, setNewFromJob] = useState('');

  useEffect(() => { localStorage.setItem('crm_bols', JSON.stringify(bols)); }, [bols]);

  const createBOL = () => {
    const job = jobs.find(j => j.id === newFromJob) || null;
    const id = 'BOL-' + String(bols.length + 1).padStart(3, '0');
    const bol = {
      id, status: 'draft',
      created: new Date().toISOString().split('T')[0],
      customer: job?.customer || '',
      phone: job?.phone || '',
      email: '',
      moveDate: job?.date || '',
      moveTime: job?.time || '',
      fromAddress: job?.from || '',
      toAddress: job?.to || '',
      crew: job?.crew || [],
      truck: job?.truck || '',
      jobId: job?.id || '',
      inventory: [],
      services: [
        { desc: 'Loading & Unloading', included: true },
        { desc: 'Furniture Assembly/Disassembly', included: false },
        { desc: 'Packing Service', included: false },
        { desc: 'Long Carry', included: false },
        { desc: 'Stair Carry', included: false },
      ],
      declaredValue: '',
      valuationType: 'released', // released | full
      specialInstructions: '',
      customerSig: null,
      companySig: null,
      customerSigDate: null,
      companySigDate: null,
      estimatedTotal: job?.value || '',
    };
    setBols([bol, ...bols]);
    setSelected(bol.id);
    setCreating(false);
  };

  const updateBOL = (id, updates) => {
    setBols(prev => prev.map(b => b.id === id ? { ...b, ...updates } : b));
  };

  const deleteBOL = (id) => {
    if (confirm('Delete this BOL?')) {
      setBols(prev => prev.filter(b => b.id !== id));
      if (selected === id) setSelected(null);
    }
  };

  const sel = bols.find(b => b.id === selected);

  const statusMap = {
    draft: { label: 'Draft', bg: '#f3f4f6', color: '#6b7280' },
    sent: { label: 'Sent', bg: '#eff6ff', color: '#2563eb' },
    signed: { label: 'Signed', bg: '#f0fdf4', color: '#16a34a' },
  };

  if (sel) return <BOLEditor bol={sel} onUpdate={u => updateBOL(sel.id, u)} onBack={() => setSelected(null)} onDelete={() => deleteBOL(sel.id)} />;

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <div>
          <h1 style={{ fontSize: 22, fontWeight: 900, fontFamily: 'Poppins', marginBottom: 2 }}>Bill of Lading</h1>
          <p style={{ color: 'var(--muted)', fontSize: 14 }}>Legal moving documents with digital signatures</p>
        </div>
        <button onClick={() => setCreating(true)} style={{ padding: '9px 18px', borderRadius: 10, background: 'var(--accent)', color: '#fff', border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 13 }}>+ Create BOL</button>
      </div>

      {bols.length === 0 ? (
        <div style={{ background: 'var(--card)', borderRadius: 16, padding: '60px 40px', textAlign: 'center', border: '2px dashed var(--border)' }}>
          <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'center' }}><Icon name="file-text" size={48} color="var(--accent)"/></div>
          <div style={{ fontWeight: 800, fontSize: 18, fontFamily: 'Poppins', marginBottom: 8 }}>No Bills of Lading yet</div>
          <div style={{ color: 'var(--muted)', marginBottom: 20, fontSize: 14 }}>Create a BOL for each job — get digital signatures from customers on-site or via link</div>
          <button onClick={() => setCreating(true)} style={{ padding: '10px 24px', borderRadius: 10, background: 'var(--accent)', color: '#fff', border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 14 }}>Create First BOL</button>
        </div>
      ) : (
        <div style={{ background: 'var(--card)', borderRadius: 14, border: '1px solid var(--border)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bg)' }}>
                {['BOL #', 'Customer', 'Move Date', 'Route', 'Crew', 'Status', 'Signatures', ''].map(h => (
                  <th key={h} style={{ padding: '10px 14px', textAlign: 'left', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {bols.map((bol, i) => {
                const s = statusMap[bol.status] || statusMap.draft;
                return (
                  <tr key={bol.id} onClick={() => setSelected(bol.id)} style={{ borderTop: '1px solid var(--border)', cursor: 'pointer', background: i%2===0?'transparent':'var(--bg)' }}
                    onMouseOver={e => e.currentTarget.style.background = 'var(--accent-light)'}
                    onMouseOut={e => e.currentTarget.style.background = i%2===0?'transparent':'var(--bg)'}>
                    <td style={{ padding: '12px 14px', fontWeight: 800, color: 'var(--accent)' }}>{bol.id}</td>
                    <td style={{ padding: '12px 14px', fontWeight: 700 }}>{bol.customer || '—'}</td>
                    <td style={{ padding: '12px 14px', color: 'var(--muted)', fontSize: 12 }}>{fmtShortDate(bol.moveDate)}</td>
                    <td style={{ padding: '12px 14px', fontSize: 12 }}><div>{bol.fromAddress}</div><div style={{ color: 'var(--muted)' }}>→ {bol.toAddress}</div></td>
                    <td style={{ padding: '12px 14px', fontSize: 11, color: 'var(--muted)' }}>{bol.crew.join(', ') || '—'}</td>
                    <td style={{ padding: '12px 14px' }}><span style={{ background: s.bg, color: s.color, padding: '4px 10px', borderRadius: 20, fontSize: 11, fontWeight: 700 }}>{s.label}</span></td>
                    <td style={{ padding: '12px 14px' }}>
                      <div style={{ display: 'flex', gap: 6 }}>
                        <span title="Customer signature" style={{display:'inline-flex'}}>{bol.customerSig ? <Icon name="check-circle" size={16} color="#16a34a"/> : <Icon name="x" size={16} color="var(--muted)"/>}</span>
                        <span title="Company signature" style={{display:'inline-flex'}}>{bol.companySig ? <Icon name="check-circle" size={16} color="#16a34a"/> : <Icon name="x" size={16} color="var(--muted)"/>}</span>
                      </div>
                    </td>
                    <td style={{ padding: '12px 14px' }}><span style={{ color: 'var(--accent)', fontWeight: 700, fontSize: 12 }}>Open →</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* Create modal */}
      {creating && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={() => setCreating(false)}>
          <div style={{ background: 'var(--card)', borderRadius: 16, padding: 28, width: 400 }} onClick={e => e.stopPropagation()}>
            <h2 style={{ fontSize: 18, fontWeight: 900, fontFamily: 'Poppins', marginBottom: 16 }}>Create Bill of Lading</h2>
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: 'block', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)', marginBottom: 6 }}>Link to a Job (optional)</label>
              <select value={newFromJob} onChange={e => setNewFromJob(e.target.value)}
                style={{ width: '100%', padding: '10px 13px', borderRadius: 10, border: '1.5px solid var(--border)', background: 'var(--bg)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none' }}>
                <option value="">— Blank BOL —</option>
                {jobs.filter(j => j.status !== 'completed').map(j => (
                  <option key={j.id} value={j.id}>{j.id} · {j.customer} · {fmtShortDate(j.date)}</option>
                ))}
              </select>
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button onClick={() => setCreating(false)} style={{ flex: 1, padding: 10, borderRadius: 9, border: '1.5px solid var(--border)', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600 }}>Cancel</button>
              <button onClick={createBOL} style={{ flex: 2, padding: 10, borderRadius: 9, background: 'var(--accent)', border: 'none', color: '#fff', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14 }}>Create BOL</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── BOL EDITOR ──────────────────────────────────────────────
function BOLEditor({ bol, onUpdate, onBack, onDelete }) {
  const [tab, setTab] = useState('details');
  const u = (field, val) => onUpdate({ [field]: val });
  const [invItem, setInvItem] = useState({ item: '', qty: 1, condition: 'Good', notes: '' });

  const addInvItem = () => {
    if (!invItem.item) return;
    onUpdate({ inventory: [...(bol.inventory||[]), { ...invItem, id: Date.now() }] });
    setInvItem({ item: '', qty: 1, condition: 'Good', notes: '' });
  };
  const removeInvItem = (id) => onUpdate({ inventory: bol.inventory.filter(i => i.id !== id) });
  const toggleService = (idx) => {
    const svcs = [...bol.services];
    svcs[idx] = { ...svcs[idx], included: !svcs[idx].included };
    onUpdate({ services: svcs });
  };

  const allSigned = bol.customerSig && bol.companySig;
  const bothSigned = () => {
    onUpdate({ status: 'signed', customerSigDate: new Date().toLocaleDateString(), companySigDate: new Date().toLocaleDateString() });
  };

  const tabs = [
    { id: 'details', label: 'Details', icon: 'clipboard' },
    { id: 'inventory', label: 'Inventory', icon: 'box' },
    { id: 'services', label: 'Services', icon: 'gear' },
    { id: 'photos', label: 'Photos', icon: 'eye' },
    { id: 'signatures', label: 'Signatures', icon: 'signature', done: allSigned },
    { id: 'document', label: 'Document', icon: 'file-text' },
  ];

  const shareForSignature = () => {
    if (typeof createPortalLink !== 'function') return;
    const url = createPortalLink('bol', bol);
    try { navigator.clipboard.writeText(url); } catch {}
    if (typeof showToast === 'function') showToast('Signing link copied — text or email it to the customer');
    // Offer to open SMS on mobile
    const msg = encodeURIComponent(`Hi ${bol.customer || 'there'}, please review and sign your MaxAMove Bill of Lading here: ${url}`);
    if (bol.phone && /iPhone|iPad|iPod|Android/.test(navigator.userAgent)) {
      setTimeout(() => { window.location.href = `sms:${bol.phone.replace(/[^\d+]/g,'')}?body=${msg}`; }, 500);
    }
  };

  const FRow = ({ label, children }) => (
    <div style={{ marginBottom: 14 }}>
      <label style={{ display: 'block', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)', marginBottom: 5 }}>{label}</label>
      {children}
    </div>
  );
  const FInput = ({ field, type='text', placeholder='' }) => (
    <input type={type} value={bol[field]||''} onChange={e => u(field, e.target.value)} placeholder={placeholder}
      style={{ width: '100%', padding: '9px 13px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--input-bg)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none' }}
      onFocus={e => e.target.style.borderColor='var(--accent)'} onBlur={e => e.target.style.borderColor='var(--border)'} />
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, flexShrink: 0, flexWrap: 'wrap', gap: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <button onClick={onBack} style={{ padding: '7px 14px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 13 }}>← Back</button>
          <div>
            <h2 style={{ fontSize: 18, fontWeight: 900, fontFamily: 'Poppins' }}>{bol.id} {bol.customer ? `— ${bol.customer}` : ''}</h2>
            <div style={{ fontSize: 12, color: 'var(--muted)' }}>Created {fmtDate(bol.created)} · {bol.status}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {bol.status !== 'signed' && allSigned && <button onClick={bothSigned} style={{ padding: '8px 16px', borderRadius: 9, background: '#16a34a', color: '#fff', border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 13, display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="check" size={13} color="#fff"/> Mark Signed</button>}
          <button onClick={shareForSignature} style={{ padding: '8px 14px', borderRadius: 9, border: '1.5px solid var(--accent)', background: 'var(--accent-light)', color: 'var(--accent-dark)', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 13, display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="mobile" size={13}/> Text Link to Sign</button>
          <button onClick={() => window.print()} style={{ padding: '8px 14px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 13, display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="file-text" size={13}/> Print</button>
          <button onClick={onDelete} style={{ padding: '8px 14px', borderRadius: 9, border: 'none', background: '#fee2e2', color: '#ef4444', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 700, fontSize: 13 }}>Delete</button>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 18, borderBottom: '2px solid var(--border)', flexShrink: 0, overflowX: 'auto' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{ padding: '8px 14px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: tab===t.id ? 800 : 500, color: tab===t.id ? 'var(--accent)' : 'var(--muted)', borderBottom: tab===t.id ? '2px solid var(--accent)' : '2px solid transparent', marginBottom: -2, whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name={t.icon} size={13}/>{t.label}{t.done && <Icon name="check" size={12} color="#16a34a"/>}</button>
        ))}
      </div>

      {/* Tab content */}
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {tab === 'details' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, maxWidth: 800 }}>
            <div>
              <div style={{ fontWeight: 800, fontSize: 13, marginBottom: 14, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Customer</div>
              <FRow label="Customer Name"><FInput field="customer" placeholder="Jane Smith" /></FRow>
              <FRow label="Phone"><FInput field="phone" type="tel" placeholder="(555) 000-0000" /></FRow>
              <FRow label="Email"><FInput field="email" type="email" placeholder="jane@email.com" /></FRow>
            </div>
            <div>
              <div style={{ fontWeight: 800, fontSize: 13, marginBottom: 14, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Move Info</div>
              <FRow label="Move Date"><FInput field="moveDate" type="date" /></FRow>
              <FRow label="Start Time"><FInput field="moveTime" placeholder="8:00 AM" /></FRow>
              <FRow label="Truck / Vehicle"><FInput field="truck" placeholder="Truck #2 (20ft)" /></FRow>
            </div>
            <div>
              <div style={{ fontWeight: 800, fontSize: 13, marginBottom: 14, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Origin</div>
              <FRow label="Pickup Address"><FInput field="fromAddress" placeholder="123 Main St, Austin, TX" /></FRow>
            </div>
            <div>
              <div style={{ fontWeight: 800, fontSize: 13, marginBottom: 14, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Destination</div>
              <FRow label="Delivery Address"><FInput field="toAddress" placeholder="456 Oak Ave, Dallas, TX" /></FRow>
            </div>
            <div style={{ gridColumn: '1/-1' }}>
              <div style={{ fontWeight: 800, fontSize: 13, marginBottom: 14, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Valuation & Liability</div>
              <div style={{ display: 'flex', gap: 12, marginBottom: 12 }}>
                {[['released', 'Released Value (60¢/lb)', 'Basic protection included at no charge'], ['full', 'Full Value Protection', 'Carrier liable for full replacement value']].map(([val, title, sub]) => (
                  <div key={val} onClick={() => u('valuationType', val)}
                    style={{ flex: 1, padding: 14, borderRadius: 12, border: `2px solid ${bol.valuationType === val ? 'var(--accent)' : 'var(--border)'}`, background: bol.valuationType === val ? 'var(--accent-light)' : 'transparent', cursor: 'pointer' }}>
                    <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 4, color: bol.valuationType === val ? 'var(--accent-dark)' : 'var(--text)' }}>{title}</div>
                    <div style={{ fontSize: 11, color: 'var(--muted)' }}>{sub}</div>
                  </div>
                ))}
              </div>
              <FRow label="Declared Value ($)"><FInput field="declaredValue" type="number" placeholder="10000" /></FRow>
            </div>
            <div style={{ gridColumn: '1/-1' }}>
              <FRow label="Special Instructions / Notes">
                <textarea value={bol.specialInstructions||''} onChange={e => u('specialInstructions', e.target.value)} rows={3} placeholder="Fragile items, access restrictions, elevator needed..."
                  style={{ width: '100%', padding: '9px 13px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--input-bg)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none', resize: 'vertical' }} />
              </FRow>
            </div>
          </div>
        )}

        {tab === 'inventory' && (
          <div style={{ maxWidth: 800 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 60px 100px 2fr 36px', gap: 8, marginBottom: 10, alignItems: 'center' }}>
              {['Item', 'Qty', 'Condition', 'Notes', ''].map((h,i) => (
                <div key={i} style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--muted)' }}>{h}</div>
              ))}
              {[
                <input value={invItem.item} onChange={e => setInvItem(p=>({...p,item:e.target.value}))} placeholder="Item name..." style={{ padding: '8px 12px', borderRadius: 8, border: '1.5px solid var(--border)', background: 'var(--input-bg)', fontSize: 13, fontFamily: 'inherit', outline: 'none', width: '100%' }} />,
                <input type="number" value={invItem.qty} onChange={e => setInvItem(p=>({...p,qty:e.target.value}))} style={{ padding: '8px 8px', borderRadius: 8, border: '1.5px solid var(--border)', background: 'var(--input-bg)', fontSize: 13, fontFamily: 'inherit', outline: 'none', width: '100%' }} />,
                <select value={invItem.condition} onChange={e => setInvItem(p=>({...p,condition:e.target.value}))} style={{ padding: '8px 8px', borderRadius: 8, border: '1.5px solid var(--border)', background: 'var(--input-bg)', fontSize: 13, fontFamily: 'inherit', outline: 'none', width: '100%' }}>
                  {['Good','Fair','Poor','Damaged'].map(c => <option key={c}>{c}</option>)}
                </select>,
                <input value={invItem.notes} onChange={e => setInvItem(p=>({...p,notes:e.target.value}))} placeholder="Notes..." style={{ padding: '8px 12px', borderRadius: 8, border: '1.5px solid var(--border)', background: 'var(--input-bg)', fontSize: 13, fontFamily: 'inherit', outline: 'none', width: '100%' }} />,
                <button onClick={addInvItem} style={{ padding: '8px', borderRadius: 8, border: 'none', background: 'var(--accent)', color: '#fff', cursor: 'pointer', fontWeight: 800, fontSize: 16 }}>+</button>
              ].map((el,i) => <div key={i}>{el}</div>)}
            </div>
            {(bol.inventory||[]).length === 0 ? (
              <div style={{ textAlign: 'center', padding: '30px', color: 'var(--muted)', fontSize: 14, border: '2px dashed var(--border)', borderRadius: 10 }}>Add items above to build the inventory list</div>
            ) : (
              <div style={{ background: 'var(--card)', borderRadius: 12, border: '1px solid var(--border)', overflow: 'hidden' }}>
                {(bol.inventory||[]).map((item, i) => (
                  <div key={item.id} style={{ display: 'grid', gridTemplateColumns: '2fr 60px 100px 2fr 36px', gap: 8, padding: '10px 14px', borderBottom: i < bol.inventory.length-1 ? '1px solid var(--border)' : 'none', alignItems: 'center', background: i%2===0?'transparent':'var(--bg)' }}>
                    <span style={{ fontWeight: 600 }}>{item.item}</span>
                    <span style={{ textAlign: 'center' }}>{item.qty}</span>
                    <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 10, background: item.condition==='Good'?'#f0fdf4':item.condition==='Fair'?'#fffbeb':'#fef2f2', color: item.condition==='Good'?'#16a34a':item.condition==='Fair'?'#b45309':'#ef4444', fontWeight: 700 }}>{item.condition}</span>
                    <span style={{ fontSize: 12, color: 'var(--muted)' }}>{item.notes||'—'}</span>
                    <button onClick={() => removeInvItem(item.id)} style={{ padding: '4px 8px', borderRadius: 6, border: 'none', background: '#fee2e2', color: '#ef4444', cursor: 'pointer', fontWeight: 700 }}>×</button>
                  </div>
                ))}
              </div>
            )}
            <div style={{ marginTop: 12, fontSize: 12, color: 'var(--muted)', padding: '10px 14px', background: '#fffbeb', borderRadius: 8, display: 'flex', alignItems: 'flex-start', gap: 8 }}>
              <Icon name="info" size={14} style={{flexShrink:0,marginTop:1}}/>
              <div>Document the condition of each item BEFORE loading. This protects both you and the customer in case of disputes.</div>
            </div>
          </div>
        )}

        {tab === 'services' && (
          <div style={{ maxWidth: 600 }}>
            <div style={{ marginBottom: 16, fontSize: 14, color: 'var(--muted)' }}>Check all services included in this move:</div>
            {(bol.services||[]).map((svc, idx) => (
              <div key={idx} onClick={() => toggleService(idx)}
                style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px', borderRadius: 12, border: `1.5px solid ${svc.included?'var(--accent)':'var(--border)'}`, background: svc.included?'var(--accent-light)':'var(--card)', marginBottom: 10, cursor: 'pointer' }}>
                <div style={{ width: 22, height: 22, borderRadius: 6, border: `2px solid ${svc.included?'var(--accent)':'var(--border)'}`, background: svc.included?'var(--accent)':'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  {svc.included && <Icon name="check" size={13} color="#fff"/>}
                </div>
                <span style={{ fontWeight: svc.included?700:500, color: svc.included?'var(--accent-dark)':'var(--text)' }}>{svc.desc}</span>
              </div>
            ))}
            <FRow label="Estimated Total ($)">
              <input type="number" value={bol.estimatedTotal||''} onChange={e => u('estimatedTotal', e.target.value)} placeholder="0.00"
                style={{ width: '100%', padding: '9px 13px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--input-bg)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none' }} />
            </FRow>
          </div>
        )}

        {tab === 'signatures' && (
          <div style={{ maxWidth: 700 }}>
            <div style={{ marginBottom: 20, padding: 16, background: '#fffbeb', borderRadius: 12, border: '1px solid #fde68a', fontSize: 14, color: '#78350f', display: 'flex', alignItems: 'flex-start', gap: 8 }}>
              <Icon name="info" size={16} style={{flexShrink:0,marginTop:2}}/>
              <div><b>On-site signing:</b> Hand the customer your phone or tablet to sign. Both parties must sign to complete the BOL.</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
              <div style={{ background: 'var(--card)', borderRadius: 14, padding: 20, border: '1px solid var(--border)' }}>
                <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins', marginBottom: 4 }}>Customer Signature</div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 14 }}>{bol.customer || 'Customer'} acknowledges receipt of goods in stated condition and agrees to the terms of this BOL.</div>
                <SignaturePad label="Sign below" value={bol.customerSig} onChange={v => onUpdate({ customerSig: v, status: v && bol.companySig ? 'signed' : 'sent' })} />
                {bol.customerSig && <div style={{ marginTop: 10, fontSize: 12, color: 'var(--muted)' }}>Signed: {bol.customerSigDate || new Date().toLocaleDateString()}</div>}
              </div>
              <div style={{ background: 'var(--card)', borderRadius: 14, padding: 20, border: '1px solid var(--border)' }}>
                <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins', marginBottom: 4 }}>MaxAMove Representative</div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 14 }}>Authorized MaxAMove crew member confirms all items loaded and conditions documented.</div>
                <SignaturePad label="Sign below" value={bol.companySig} onChange={v => onUpdate({ companySig: v, status: v && bol.customerSig ? 'signed' : 'sent' })} />
                {bol.companySig && <div style={{ marginTop: 10, fontSize: 12, color: 'var(--muted)' }}>Signed: {bol.companySigDate || new Date().toLocaleDateString()}</div>}
              </div>
            </div>
            {bol.customerSig && bol.companySig && (
              <div style={{ marginTop: 20, padding: 16, background: '#f0fdf4', borderRadius: 12, border: '1px solid #bbf7d0', textAlign: 'center' }}>
                <div style={{ marginBottom: 6, display: 'flex', justifyContent: 'center' }}><Icon name="check-circle" size={32} color="#16a34a"/></div>
                <div style={{ fontWeight: 800, fontSize: 16, color: '#166534', fontFamily: 'Poppins' }}>Both Signatures Captured</div>
                <div style={{ fontSize: 13, color: '#16a34a', marginTop: 4 }}>This BOL is fully executed. Print or save for your records.</div>
              </div>
            )}
          </div>
        )}

        {tab === 'photos' && (
          <div style={{ maxWidth: 900 }}>
            <div style={{ padding: 14, background: 'var(--accent-light)', borderRadius: 10, border: '1px solid var(--accent)', fontSize: 13, color: 'var(--accent-dark)', marginBottom: 16, lineHeight: 1.5, display: 'flex', alignItems: 'flex-start', gap: 8 }}>
              <Icon name="info" size={15} style={{flexShrink:0,marginTop:2}}/>
              <div><b>Document conditions before & after.</b> Tap "Add Photos" to use your phone's camera. Tag each photo as <b>before</b>, <b>after</b>, <b>damage</b>, or <b>receipt</b> — these are legal proof in the event of a claim.</div>
            </div>
            {typeof JobPhotoGrid !== 'undefined' && <JobPhotoGrid jobId={bol.jobId || bol.id} label="BOL Photos & Documentation" />}
          </div>
        )}

        {tab === 'document' && <BOLDocument bol={bol} />}
      </div>
    </div>
  );
}

// ─── BOL DOCUMENT (PRINTABLE) ────────────────────────────────
function BOLDocument({ bol }) {
  const today = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', gap: 10 }}>
        <button onClick={() => window.print()} style={{ padding: '9px 18px', borderRadius: 10, background: 'var(--accent)', color: '#fff', border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 13, display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="file-text" size={14} color="#fff"/> Print / Save PDF</button>
        <div style={{ fontSize: 12, color: 'var(--muted)', alignSelf: 'center' }}>Preview of the document your customer will receive</div>
      </div>
      <div className="print-doc" style={{ background: '#fff', borderRadius: 16, border: '1.5px solid var(--border)', padding: '36px 44px', boxShadow: '0 4px 24px rgba(0,0,0,0.06)', color: '#1a1a1a', maxWidth: 800 }}>
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28, paddingBottom: 20, borderBottom: '2px solid var(--accent)' }}>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <div style={{ width: 38, height: 38, background: 'var(--accent)', borderRadius: 9, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="truck" size={22} color="#fff"/></div>
            <div>
              <div style={{ fontWeight: 900, fontSize: 19, letterSpacing: '-0.02em' }}>MaxAMove</div>
              <div style={{ fontSize: 10, color: '#999', letterSpacing: '0.06em' }}>LICENSED & INSURED · MAXAMOVE.COM</div>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 26, fontWeight: 900, color: 'var(--accent)', letterSpacing: '-0.02em' }}>BILL OF LADING</div>
            <div style={{ fontSize: 13, color: '#666', lineHeight: 1.7 }}><b>{bol.id}</b><br />Date: {today}<br />{bol.status === 'signed' ? <span style={{display:'inline-flex',alignItems:'center',gap:4,color:'#16a34a',fontWeight:700}}><Icon name="check-circle" size={13}/> SIGNED</span> : 'Status: ' + bol.status.toUpperCase()}</div>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28, marginBottom: 24 }}>
          <div>
            <div style={{ fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#999', marginBottom: 8 }}>Customer / Shipper</div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{bol.customer || '—'}</div>
            <div style={{ fontSize: 13, color: '#555', lineHeight: 1.8 }}>{bol.phone}<br />{bol.email}</div>
          </div>
          <div>
            <div style={{ fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#999', marginBottom: 8 }}>Move Details</div>
            <div style={{ fontSize: 13, lineHeight: 1.8 }}>
              <b>Date:</b> {fmtDate(bol.moveDate)}<br />
              <b>Start Time:</b> {bol.moveTime || '—'}<br />
              <b>Vehicle:</b> {bol.truck || '—'}
            </div>
          </div>
          <div>
            <div style={{ fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#999', marginBottom: 8 }}>Origin (Pickup)</div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{bol.fromAddress || '—'}</div>
          </div>
          <div>
            <div style={{ fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#999', marginBottom: 8 }}>Destination (Delivery)</div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{bol.toAddress || '—'}</div>
          </div>
        </div>

        {(bol.inventory||[]).length > 0 && (
          <div style={{ marginBottom: 24 }}>
            <div style={{ fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#999', marginBottom: 10 }}>Inventory & Condition at Pickup</div>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
              <thead>
                <tr style={{ background: '#f9f9f9', borderBottom: '2px solid #eee' }}>
                  {['#','Item','Qty','Condition','Notes'].map(h => (
                    <th key={h} style={{ padding: '7px 10px', textAlign: 'left', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', color: '#999' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {bol.inventory.map((item, i) => (
                  <tr key={item.id} style={{ borderBottom: '1px solid #f0f0f0' }}>
                    <td style={{ padding: '8px 10px', color: '#999' }}>{i+1}</td>
                    <td style={{ padding: '8px 10px', fontWeight: 600 }}>{item.item}</td>
                    <td style={{ padding: '8px 10px' }}>{item.qty}</td>
                    <td style={{ padding: '8px 10px' }}>{item.condition}</td>
                    <td style={{ padding: '8px 10px', color: '#666' }}>{item.notes || '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {(bol.services||[]).filter(s=>s.included).length > 0 && (
          <div style={{ marginBottom: 24 }}>
            <div style={{ fontSize: 10, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.1em', color: '#999', marginBottom: 8 }}>Services Included</div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {bol.services.filter(s=>s.included).map(s => (
                <span key={s.desc} style={{ background: '#f0fdf4', color: '#166534', padding: '4px 10px', borderRadius: 6, fontSize: 12, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="check" size={11}/> {s.desc}</span>
              ))}
            </div>
          </div>
        )}

        <div style={{ marginBottom: 24, display: 'flex', gap: 20 }}>
          <div style={{ flex: 1, padding: 14, background: '#f9f9f9', borderRadius: 10 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#999', textTransform: 'uppercase', marginBottom: 4 }}>Valuation Type</div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{bol.valuationType === 'released' ? 'Released Value (60¢/lb)' : 'Full Value Protection'}</div>
            {bol.declaredValue && <div style={{ fontSize: 12, color: '#666' }}>Declared Value: ${parseFloat(bol.declaredValue).toLocaleString()}</div>}
          </div>
          {bol.estimatedTotal && (
            <div style={{ flex: 1, padding: 14, background: '#f0fdf4', borderRadius: 10 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#999', textTransform: 'uppercase', marginBottom: 4 }}>Estimated Total</div>
              <div style={{ fontSize: 22, fontWeight: 900, color: 'var(--accent)' }}>${parseFloat(bol.estimatedTotal).toLocaleString()}</div>
            </div>
          )}
        </div>

        <div style={{ marginBottom: 24, padding: '14px 16px', background: '#f9f9f9', borderRadius: 10, fontSize: 11, color: '#666', lineHeight: 1.7 }}>
          <b style={{ color: '#333' }}>Terms & Conditions:</b> This Bill of Lading is the receipt of goods listed herein and constitutes the entire agreement between MaxAMove and the customer. MaxAMove shall not be liable for loss or damage of articles not listed on this BOL. Claims must be made within 9 months of delivery. Payment is due upon delivery. Customer signature below acknowledges all goods received in stated condition and agreement to terms.
        </div>

        {bol.specialInstructions && (
          <div style={{ marginBottom: 24, padding: '12px 16px', background: '#fffbeb', borderRadius: 10, fontSize: 13 }}>
            <b>Special Instructions:</b> {bol.specialInstructions}
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32, marginTop: 28 }}>
          <div>
            <div style={{ fontSize: 12, color: '#999', marginBottom: 8 }}>Customer Signature</div>
            {bol.customerSig
              ? <img src={bol.customerSig} style={{ width: '100%', height: 70, objectFit: 'contain', border: '1px solid #eee', borderRadius: 6 }} />
              : <div style={{ height: 70, border: '1.5px solid #ddd', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#ccc', fontSize: 13 }}>Not yet signed</div>}
            <div style={{ borderTop: '1px solid #ddd', marginTop: 6, paddingTop: 4, fontSize: 11, color: '#999' }}>{bol.customer || 'Customer'} · {bol.customerSigDate || '_______________'}</div>
          </div>
          <div>
            <div style={{ fontSize: 12, color: '#999', marginBottom: 8 }}>MaxAMove Representative</div>
            {bol.companySig
              ? <img src={bol.companySig} style={{ width: '100%', height: 70, objectFit: 'contain', border: '1px solid #eee', borderRadius: 6 }} />
              : <div style={{ height: 70, border: '1.5px solid #ddd', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#ccc', fontSize: 13 }}>Not yet signed</div>}
            <div style={{ borderTop: '1px solid #ddd', marginTop: 6, paddingTop: 4, fontSize: 11, color: '#999' }}>MaxAMove · {bol.companySigDate || '_______________'}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { BOLView, SignaturePad });
