/* ============================================================
   ELECTROMED — Customer CRM module
   Hospital (B2B) + Individual (C2C) + Sub-Distributor profiles
   ============================================================ */
function CRM({ branch }) {
  const { PKR } = window.DATA;
  const [tab, setTab] = useState('All');
  const [q, setQ] = useState('');
  const [sel, setSel] = useState(null);
  const [showNew, setShowNew] = useState(false);
  const [stmt, setStmt] = useState(null);

  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const { data: customers, loading, error, refetch } = useCustomers(bf);

  // DB stores 'Hospital', 'Individual', 'Sub-Distributor'
  const tabMap = { All: null, Hospitals: 'Hospital', Individuals: 'Individual', Distributors: 'Sub-Distributor' };
  const typeBadge = (t) => ({ Hospital: 'info', Individual: 'idle', 'Sub-Distributor': 'warn' }[t] || 'idle');

  const list = customers.filter((c) =>
    (!tabMap[tab] || c.type === tabMap[tab]) &&
    (c.name.toLowerCase().includes(q.toLowerCase()) ||
     (c.id && c.id.toLowerCase().includes(q.toLowerCase())))
  );

  const totalOut = customers.reduce((s, c) => s + parseFloat(c.outstanding || 0), 0);

  if (loading) return <div className="view-enter"><div className="card card-pad" style={{ textAlign: 'center', padding: 40 }}>Loading customers…</div></div>;
  if (error)   return <div className="view-enter"><div className="card card-pad" style={{ color: 'var(--bad)' }}>Error loading customers: {error}</div></div>;

  return (
    <div className="view-enter">
      <PageHead eyebrow="01 · Customer CRM" title="Customer Relationships"
        sub="Hospitals, individual patients and sub-distributors across all branches."
        actions={<>
          <Btn variant="ghost" icon={<Icons.download size={16} />} onClick={() => setStmt({ cust: null })}>Statement</Btn>
          {window.can('customers','create') && <Btn variant="primary" icon={<Icons.plus size={16} stroke={2.6} />} onClick={() => setShowNew(true)}>Add Customer</Btn>}
        </>} />

      <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 20 }}>
        <StatCard icon={<Icons.crm size={18} />} label="Total Customers" value={customers.length} sub="active accounts" />
        <StatCard icon={<Icons.shield size={18} />} label="Hospitals (B2B)" value={customers.filter(c => c.type === 'Hospital').length} sub="institutional" />
        <StatCard icon={<Icons.truck size={18} />} label="Sub-Distributors" value={customers.filter(c => c.type === 'Sub-Distributor').length} sub="partner network" />
        <StatCard icon={<Icons.pay size={18} />} label="Total Outstanding" value={PKR(totalOut)} accent />
      </div>

      <div className="card">
        <div className="card-pad row" style={{ justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', paddingBottom: 14 }}>
          <Tabs tabs={['All', 'Hospitals', 'Individuals', 'Distributors']} value={tab} onChange={setTab} />
          <div className="row" style={{ gap: 10 }}>
            <SearchBox value={q} onChange={setQ} placeholder="Search name or ID…" w={240} />
            <Btn variant="ghost" sm icon={<Icons.filter size={15} />}>Filter</Btn>
          </div>
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl">
            <thead><tr>
              <th>Customer</th><th>Type</th><th>City / Branch</th><th>Devices</th><th>Outstanding</th><th>Since</th><th></th>
            </tr></thead>
            <tbody>
              {list.map((c) => (
                <tr key={c.id} style={{ cursor: 'pointer' }} onClick={() => setSel(c)}>
                  <td>
                    <div className="row" style={{ gap: 11 }}>
                      <div style={{ width: 38, height: 38, borderRadius: 11,
                        background: c.type === 'Hospital' ? 'var(--info-bg)' : c.type === 'Sub-Distributor' ? 'var(--warn-bg)' : 'var(--surface-3)',
                        color: c.type === 'Hospital' ? 'var(--info)' : c.type === 'Sub-Distributor' ? 'var(--warn)' : 'var(--ink-2)',
                        display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 13, flexShrink: 0 }}>
                        {c.name.split(' ').slice(0, 2).map(w => w[0]).join('')}
                      </div>
                      <div>
                        <div style={{ fontWeight: 700 }}>{c.name}</div>
                        <div className="tiny muted mono">{c.phone} · {c.email || c.city}</div>
                      </div>
                    </div>
                  </td>
                  <td><Badge kind={typeBadge(c.type)}>{c.tag || c.type}</Badge></td>
                  <td><div className="row" style={{ gap: 6 }}><Icons.pin size={14} style={{ color: 'var(--ink-3)' }} />{c.city}</div></td>
                  <td className="mono">{c.device_count ?? '—'}</td>
                  <td className="mono" style={{ fontWeight: 700, color: parseFloat(c.outstanding) > 0 ? 'var(--bad)' : 'var(--ink)' }}>
                    {parseFloat(c.outstanding) > 0 ? PKR(c.outstanding) : 'Clear'}
                  </td>
                  <td className="muted">{c.since}</td>
                  <td><Icons.chevR size={16} style={{ color: 'var(--ink-3)' }} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {!list.length && <div className="ph-img" style={{ height: 120, margin: 18 }}>no customers match</div>}
      </div>

      {sel && <CustomerDetail c={sel} onClose={() => setSel(null)} onStatement={(c) => { setSel(null); setStmt({ cust: c }); }} onDeleted={() => { setSel(null); refetch(); }} onEdited={() => { setSel(null); refetch(); }} />}
      {showNew && <NewCustomer onClose={() => { setShowNew(false); refetch(); }} />}
      {stmt && <StatementModal initCust={stmt.cust} customers={customers} onClose={() => setStmt(null)} />}
    </div>
  );
}

function CustomerDetail({ c, onClose, onStatement, onDeleted, onEdited }) {
  const { PKR } = window.DATA;
  const { data: invs }  = useInvoices({ customer_id: c.id });
  const { data: rents } = useRentals({ customer_id: c.id });
  const [confirmDel, setConfirmDel] = useState(false);
  const [delBusy,    setDelBusy]    = useState(false);
  const [editing,    setEditing]    = useState(false);

  if (editing) return <NewCustomer customer={c} onClose={() => setEditing(false)} onSaved={() => onEdited?.()} />;

  const doDelete = async () => {
    setDelBusy(true);
    try {
      await api.deleteCustomer(c.id);
      window.toast('Customer deleted', 'ok');
      onDeleted?.();
      onClose();
    } catch (err) {
      window.toast(err.message || 'Failed to delete customer', 'error');
      setDelBusy(false);
    }
  };

  if (confirmDel) return (
    <Modal title="Delete Customer?" sub={c.name} onClose={() => setConfirmDel(false)}
      foot={<>
        <Btn variant="ghost" onClick={() => setConfirmDel(false)}>Cancel</Btn>
        <Btn variant="danger" onClick={doDelete} disabled={delBusy}>{delBusy ? 'Deleting…' : 'Yes, Delete'}</Btn>
      </>}>
      <div style={{ padding: '8px 0' }}>
        <div style={{ marginBottom: 10 }}>This will permanently remove <strong>{c.name}</strong> from the system.</div>
        {(parseFloat(c.outstanding) > 0) && (
          <div style={{ background: 'var(--bad-bg)', color: 'var(--bad)', padding: '10px 14px', borderRadius: 10, fontSize: 13, fontWeight: 600 }}>
            Warning: this customer has an outstanding balance of {PKR(c.outstanding)}.
          </div>
        )}
        {(invs.length > 0 || rents.length > 0) && (
          <div style={{ background: 'var(--warn-bg)', color: 'var(--warn)', padding: '10px 14px', borderRadius: 10, fontSize: 13, fontWeight: 600, marginTop: 8 }}>
            Warning: {invs.length} invoice{invs.length !== 1 ? 's' : ''} and {rents.length} rental{rents.length !== 1 ? 's' : ''} are linked to this customer.
          </div>
        )}
      </div>
    </Modal>
  );

  return (
    <Modal wide title={c.name} sub={`${c.type} · ${c.city}`} onClose={onClose}
      foot={<>
        {window.can('customers','delete') && <Btn variant="danger" icon={<Icons.trash size={15} />} onClick={() => setConfirmDel(true)}>Delete</Btn>}
        <Btn variant="ghost" onClick={onClose}>Close</Btn>
        {window.can('customers','edit') && <Btn variant="ghost" icon={<Icons.gear size={15} />} onClick={() => setEditing(true)}>Edit</Btn>}
        <Btn variant="primary" icon={<Icons.doc size={16} />} onClick={() => onStatement(c)}>Account Statement</Btn>
      </>}>
      <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 18 }}>
        {[['Phone', c.phone], ['Email', c.email || '—'], ['Devices Owned', c.device_count ?? '0'], ['Customer Since', c.since || '—']].map(([k, v]) => (
          <div key={k} style={{ background: 'var(--surface-2)', borderRadius: 12, padding: '12px 14px' }}>
            <div className="tiny muted" style={{ fontWeight: 700 }}>{k}</div>
            <div style={{ fontWeight: 700, marginTop: 3 }}>{v}</div>
          </div>
        ))}
      </div>
      <div className="row" style={{ justifyContent: 'space-between', background: parseFloat(c.outstanding) > 0 ? 'var(--bad-bg)' : 'var(--ok-bg)', borderRadius: 12, padding: '14px 16px', marginBottom: 8 }}>
        <span style={{ fontWeight: 700, color: parseFloat(c.outstanding) > 0 ? 'var(--bad)' : 'var(--ok)' }}>Outstanding Balance</span>
        <span className="mono" style={{ fontWeight: 800, fontSize: 18, color: parseFloat(c.outstanding) > 0 ? 'var(--bad)' : 'var(--ok)' }}>
          {parseFloat(c.outstanding) > 0 ? PKR(c.outstanding) : 'All Clear'}
        </span>
      </div>
      {parseFloat(c.opening_balance) > 0 && invs.length === 0 && (
        <div className="row" style={{ gap: 8, padding: '8px 12px', marginBottom: 12, background: 'var(--warn-bg, #fff8e6)', borderRadius: 10, border: '1px solid var(--warn, #f5a623)' }}>
          <Icons.info size={15} style={{ color: 'var(--warn, #f5a623)', flexShrink: 0 }} />
          <span className="tiny" style={{ color: 'var(--ink-2)' }}>
            Opening balance of <strong>{PKR(c.opening_balance)}</strong> was entered when this customer was created. No invoice exists for it — create one to properly track this receivable.
          </span>
        </div>
      )}
      <div style={{ fontWeight: 800, marginBottom: 8 }}>Purchase History</div>
      {invs.length ? (
        <table className="tbl"><tbody>
          {invs.map(i => (
            <tr key={i.id}>
              <td className="mono" style={{ fontWeight: 700 }}>{i.invoice_number}</td>
              <td className="muted">{i.device}</td>
              <td className="mono">{PKR(i.amount)}</td>
              <td><Badge kind={window.statusKind(i.status)}>{i.status}</Badge></td>
            </tr>
          ))}
        </tbody></table>
      ) : <div className="tiny muted" style={{ padding: '6px 0 14px' }}>No sales on record.</div>}
      {rents.length > 0 && <>
        <div style={{ fontWeight: 800, margin: '16px 0 8px' }}>Rental History</div>
        <table className="tbl"><tbody>
          {rents.map(r => (
            <tr key={r.id}>
              <td className="mono" style={{ fontWeight: 700 }}>{r.rental_number}</td>
              <td className="muted">{r.device}</td>
              <td className="mono">{PKR(r.rate)}/{(r.plan || 'Monthly').toLowerCase()}</td>
              <td><Badge kind={window.statusKind(r.status)}>{r.status}</Badge></td>
            </tr>
          ))}
        </tbody></table>
      </>}
    </Modal>
  );
}

function NewCustomer({ onClose, customer, onSaved }) {
  const editing = !!customer;
  const { data: branches } = useBranches();

  // Non-admin users are locked to their own branch (server enforces this too)
  const currentUser = api.user || {};
  const ADMIN_ROLES = ['admin', 'owner', 'super admin', 'superadmin'];
  const isAdmin = ADMIN_ROLES.includes((currentUser.role || '').toLowerCase().trim());
  const lockedBranchId = !isAdmin ? (currentUser.branch_id || '') : '';

  const [type, setType] = useState(customer?.type || 'Hospital');
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState({
    name:      customer?.name      || '',
    phone:     customer?.phone     || '',
    email:     customer?.email     || '',
    city:      customer?.city      || '',
    address:   customer?.address   || '',
    branch_id: customer?.branch_id || lockedBranchId || '',
    tag:       customer?.tag       || '',
  });

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const save = async () => {
    if (!form.name || !form.phone) { window.toast('Name and phone are required', 'warn'); return; }
    setBusy(true);
    try {
      const payload = { ...form, type, tag: type === 'Hospital' ? 'B2B' : type === 'Sub-Distributor' ? 'Partner' : 'C2C' };
      if (editing) {
        await api.updateCustomer(customer.id, payload);
        window.toast('Customer updated', 'ok');
      } else {
        await api.createCustomer({ ...payload, status: 'active' });
        window.toast('Customer saved successfully', 'ok');
      }
      (onSaved || onClose)();
    } catch (err) {
      window.toast(err.message || 'Failed to save customer', 'error');
    } finally {
      setBusy(false);
    }
  };

  return (
    <Modal title={editing ? 'Edit Customer' : 'Add Customer'} sub={editing ? 'Update this CRM profile' : 'Create a new CRM profile'} onClose={onClose}
      foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon={<Icons.check size={16} />} onClick={save} disabled={busy}>{busy ? 'Saving…' : editing ? 'Save Changes' : 'Save Customer'}</Btn></>}>
      <div style={{ display: 'grid', gap: 14 }}>
        <label className="fld"><span>Customer Type</span>
          <div className="tabs" style={{ width: '100%', display: 'flex' }}>
            {['Hospital', 'Individual', 'Sub-Distributor'].map(t => (
              <button key={t} className={cls('tab', type === t && 'active')} style={{ flex: 1 }} onClick={() => setType(t)}>{t}</button>
            ))}
          </div>
        </label>
        <label className="fld"><span>Name / Institution</span>
          <input className="input-block" value={form.name} onChange={set('name')} placeholder={type === 'Hospital' ? 'e.g. Aga Khan University Hospital' : 'e.g. Mr. Imran Sheikh'} />
        </label>
        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <label className="fld"><span>Phone</span><input className="input-block" value={form.phone} onChange={set('phone')} placeholder="+92 3xx xxxxxxx" /></label>
          <label className="fld"><span>Email</span><input className="input-block" type="email" value={form.email} onChange={set('email')} placeholder="optional" /></label>
        </div>
        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <label className="fld"><span>City</span><input className="input-block" value={form.city} onChange={set('city')} placeholder="e.g. Karachi" /></label>
          <label className="fld"><span>Branch</span>
            {!isAdmin && lockedBranchId ? (
              <div className="input-block" style={{ background: 'var(--surface-2)', color: 'var(--ink-2)', cursor: 'default', display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icons.pin size={14} style={{ color: 'var(--ink-3)', flexShrink: 0 }} />
                {(branches.find(b => String(b.id) === String(lockedBranchId)) || {}).city ||
                 (branches.find(b => String(b.id) === String(lockedBranchId)) || {}).name || 'Your branch'}
                <span className="tiny muted" style={{ marginLeft: 'auto' }}>locked to your branch</span>
              </div>
            ) : (
              <select className="input-block" value={form.branch_id} onChange={set('branch_id')}>
                <option value="">— Select branch —</option>
                {branches.map(b => <option key={b.id} value={b.id}>{b.city || b.name}</option>)}
              </select>
            )}
          </label>
        </div>
        <label className="fld"><span>Address</span><textarea className="input-block" rows="2" value={form.address} onChange={set('address')} placeholder="Optional" /></label>
      </div>
    </Modal>
  );
}

function StatementModal({ initCust, customers, onClose }) {
  const { PKR } = window.DATA;
  const co = (window.DATA.companies && window.DATA.companies[0]) || { name: 'Electromed Corporation', addr: 'Karachi', ntn: '—', color: 'var(--forest-2)' };
  const [custId, setCustId] = useState(initCust ? initCust.id : '');
  const c = customers.find((x) => x.id === custId) || null;

  const { data: custInvoices } = useInvoices(c ? { customer_id: c.id } : {});

  const fmtDate = (s) => { try { return new Date(s).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }); } catch { return s || '—'; } };
  const today = new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });

  const ledger = useMemo(() => {
    if (!c || !custInvoices.length) return null;
    const rows = [];
    custInvoices.forEach((i) => {
      rows.push({ date: i.date, ref: i.invoice_number, desc: i.device || 'Invoice', debit: parseFloat(i.amount), credit: 0 });
      if (parseFloat(i.received) > 0) rows.push({ date: i.date, ref: i.invoice_number, desc: `Payment against ${i.invoice_number}`, debit: 0, credit: parseFloat(i.received), pay: true });
    });
    rows.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : a.debit ? -1 : 1));
    const invNet = rows.reduce((s, r) => s + r.debit - r.credit, 0);
    const opening = parseFloat(c.outstanding || 0) - invNet;
    let bal = opening;
    rows.forEach((r) => { bal += r.debit - r.credit; r.bal = bal; });
    const billed   = rows.reduce((s, r) => s + r.debit, 0);
    const paid     = rows.reduce((s, r) => s + r.credit, 0);
    return { rows, opening, billed, paid, closing: bal };
  }, [c, custInvoices]);

  return (
    <Modal wide title="Account Statement"
      sub={c ? `${c.type} · ${c.city}` : 'Select a customer to generate a statement'}
      onClose={onClose}
      foot={<>
        <Btn variant="ghost" onClick={onClose}>Close</Btn>
        <Btn variant="ghost" icon={<Icons.print size={16} />} onClick={() => window.print()} disabled={!c}>Print</Btn>
        <Btn variant="primary" icon={<Icons.download size={16} />} disabled={!c}>Download PDF</Btn>
      </>}>

      <label className="fld" style={{ marginBottom: c ? 18 : 0 }}>
        <span>Customer</span>
        <select className="input-block" value={custId} onChange={(e) => setCustId(e.target.value)}>
          <option value="">— Choose a customer —</option>
          {customers.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}
        </select>
      </label>

      {!c ? (
        <div className="ph-img" style={{ height: 140, marginTop: 16 }}>pick a customer to preview their statement</div>
      ) : !ledger ? (
        <div className="ph-img" style={{ height: 140, marginTop: 16 }}>no invoice records found for this customer</div>
      ) : (
        <div style={{ border: '1px solid var(--line)', borderRadius: 16, overflow: 'hidden' }}>
          <div className="row" style={{ gap: 12, padding: '16px 18px', background: co.color, color: '#fff', alignItems: 'flex-start' }}>
            <div style={{ width: 38, height: 38, borderRadius: 10, background: 'rgba(255,255,255,.12)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--lime)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12h4l2-6 4 13 3-9 2 2h5" /></svg>
            </div>
            <div className="grow"><div style={{ fontWeight: 800, fontSize: 15 }}>{co.name}</div><div className="tiny" style={{ color: 'rgba(255,255,255,.7)' }}>{co.addr}</div></div>
            <div style={{ textAlign: 'right' }}><div style={{ fontWeight: 800, fontSize: 13, letterSpacing: '.04em' }}>STATEMENT</div><div className="tiny" style={{ color: 'rgba(255,255,255,.7)' }}>as of {today}</div></div>
          </div>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 0, borderBottom: '1px solid var(--line)' }}>
            <div style={{ padding: '13px 18px', borderRight: '1px solid var(--line)' }}>
              <div className="tiny muted" style={{ fontWeight: 700 }}>STATEMENT FOR</div>
              <div style={{ fontWeight: 800, marginTop: 3 }}>{c.name}</div>
              <div className="tiny muted" style={{ marginTop: 2 }}>{c.phone} · {c.city}</div>
            </div>
            <div style={{ padding: '13px 18px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
              <div className="row" style={{ justifyContent: 'space-between' }}><span className="tiny muted">Total Billed</span><span className="mono" style={{ fontWeight: 700 }}>{PKR(ledger.billed)}</span></div>
              <div className="row" style={{ justifyContent: 'space-between', marginTop: 4 }}><span className="tiny muted">Total Received</span><span className="mono" style={{ fontWeight: 700, color: 'var(--ok)' }}>{PKR(ledger.paid)}</span></div>
            </div>
          </div>
          <table className="tbl">
            <thead><tr>
              <th>Date</th><th>Reference</th><th>Description</th>
              <th style={{ textAlign: 'right' }}>Debit</th><th style={{ textAlign: 'right' }}>Credit</th><th style={{ textAlign: 'right' }}>Balance</th>
            </tr></thead>
            <tbody>
              {ledger.opening !== 0 && (
                <tr>
                  <td className="tiny muted" style={{ whiteSpace: 'nowrap' }}>—</td>
                  <td className="mono tiny" style={{ fontWeight: 700 }}>—</td>
                  <td className="tiny" style={{ fontStyle: 'italic' }}>Opening balance brought forward</td>
                  <td className="mono tiny" style={{ textAlign: 'right' }}>{ledger.opening > 0 ? PKR(ledger.opening) : '—'}</td>
                  <td className="mono tiny" style={{ textAlign: 'right', color: ledger.opening < 0 ? 'var(--ok)' : 'inherit' }}>{ledger.opening < 0 ? PKR(-ledger.opening) : '—'}</td>
                  <td className="mono tiny" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(ledger.opening)}</td>
                </tr>
              )}
              {ledger.rows.map((r, ix) => (
                <tr key={ix}>
                  <td className="tiny muted" style={{ whiteSpace: 'nowrap' }}>{fmtDate(r.date)}</td>
                  <td className="mono tiny" style={{ fontWeight: 700 }}>{r.ref}</td>
                  <td className="tiny">{r.desc}</td>
                  <td className="mono tiny" style={{ textAlign: 'right' }}>{r.debit ? PKR(r.debit) : '—'}</td>
                  <td className="mono tiny" style={{ textAlign: 'right', color: r.credit ? 'var(--ok)' : 'inherit' }}>{r.credit ? PKR(r.credit) : '—'}</td>
                  <td className="mono tiny" style={{ textAlign: 'right', fontWeight: 700 }}>{PKR(r.bal)}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="row" style={{ justifyContent: 'space-between', padding: '14px 18px', borderTop: '2px solid var(--line)', background: ledger.closing > 0 ? 'var(--bad-bg)' : 'var(--ok-bg)' }}>
            <span style={{ fontWeight: 800, color: ledger.closing > 0 ? 'var(--bad)' : 'var(--ok)' }}>{ledger.closing > 0 ? 'Balance Due' : 'Account Settled'}</span>
            <span className="mono" style={{ fontWeight: 800, fontSize: 18, color: ledger.closing > 0 ? 'var(--bad)' : 'var(--ok)' }}>{PKR(Math.max(0, ledger.closing))}</span>
          </div>
        </div>
      )}
    </Modal>
  );
}
window.CRM = CRM;
