/* ============================================================
   ELECTROMED — Inventory & Stock
   Parts catalogue · machines · serial register · low-stock alerts
   ============================================================ */

function normalizeInventory(i) {
  return {
    ...i,
    cat: i.category || i.cat,
    low: i.low_threshold != null ? i.low_threshold : (i.low || 0),
    sys: i.sys_stock != null ? i.sys_stock : (i.sys || 0),
    rentStock: i.rent_stock != null ? i.rent_stock : (i.rentStock || 0),
    rentSys: i.rent_sys != null ? i.rent_sys : (i.rentSys || 0),
  };
}

function normalizeStockMove(m) {
  return {
    ...m,
    no: m.move_number || m.no,
    from: m.from_loc || m.from,
    to: m.to_loc || m.to,
  };
}

function Inventory({ branch }) {
  const { PKR } = window.DATA;
  const [view, setView] = useState('Catalogue');
  const [tab, setTab] = useState('All');
  const [pool, setPool] = useState('All');
  const [q, setQ] = useState('');
  const [adj, setAdj] = useState(null);
  const [move, setMove] = useState(false);
  const [moveType, setMoveType] = useState('Branch Transfer');
  const [delItem, setDelItem] = useState(null);

  const openMove = (t = 'Branch Transfer') => { setMoveType(t); setMove(true); };
  const isMachine = (i) => i.cat === 'Machine';

  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const { data: branchList } = useBranches();
  const { data: rawInventory, refetch: refetchInventory } = useInventory(bf);
  const { data: rawMoves, refetch: refetchMoves } = useStockMoves(bf);

  const branchObj = branch === 'All' ? null
    : branchList.find(b => String(b.id) === String(branch));

  const allInventory = rawInventory.map(normalizeInventory);
  const branchInventory = branchObj ? allInventory.filter(i => i.branch_id === branchObj.id) : allInventory;
  const stockMoves = rawMoves.map(normalizeStockMove);

  const getBranchName = (id) => (branchList.find(b => b.id === id) || {}).city || id || '—';

  const list = branchInventory.filter((i) =>
    (tab === 'All' || (tab === 'Machines' ? i.cat === 'Machine' : tab === 'Spare Parts' ? i.cat === 'Spare Part' : i.cat === 'Accessory')) &&
    (pool === 'All' || (pool === 'Rental' ? (isMachine(i) && i.rentStock > 0) : true)) &&
    ((i.name||'').toLowerCase().includes(q.toLowerCase()) || (i.sku||'').toLowerCase().includes(q.toLowerCase()))
  );

  const lowCount = branchInventory.filter(i => i.stock <= i.low).length;
  const stockValue = branchInventory.reduce((s, i) => s + (i.stock||0) * (i.price||0), 0);
  const saleMachines = branchInventory.filter(i => i.cat === 'Machine').reduce((s,i)=>s+(i.stock||0),0);
  const rentMachines = branchInventory.filter(i => i.cat === 'Machine').reduce((s,i)=>s+(i.rentStock||0),0);
  const pendingReclass = stockMoves.filter(m => m.type === 'Reclassification' && m.status === 'Pending').length;

  return (
    <div className="view-enter">
      <PageHead eyebrow="05 · Inventory & Stock" title="Inventory & Stock"
        sub="Sale and rental pools, spare-parts catalogue, branch transfers and consignment stock."
        actions={<>
          <div className="tabs">
            <button className={cls('tab', view==='Catalogue'&&'active')} onClick={()=>setView('Catalogue')}>Catalogue</button>
            <button className={cls('tab', view==='Movements'&&'active')} onClick={()=>setView('Movements')}>Stock Movements</button>
          </div>
          {view === 'Catalogue'
            ? (window.can('inventory','create') && <Btn variant="primary" icon={<Icons.plus size={16} stroke={2.6} />} onClick={() => setAdj({ name: '', sku: 'NEW', stock: 0, low: 10, price: 0, cat: 'Spare Part', branch_id: null, sys: 0 })}>Add Item</Btn>)
            : (window.can('inventory','create') && <Btn variant="primary" icon={<Icons.swap size={16} stroke={2.4} />} onClick={() => openMove('Branch Transfer')}>Move Stock</Btn>)}
        </>} />

      {view === 'Movements' ? (
        <StockMovements stockMoves={stockMoves} branchList={branchList} onNew={openMove} refetch={refetchMoves} />
      ) : <>

      <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 20 }}>
        <StatCard icon={<Icons.sales size={18} />} label="Machines · For Sale" value={saleMachines} sub="sale pool" />
        <StatCard icon={<Icons.rental size={18} />} label="Machines · For Rent" value={rentMachines} sub="rental pool" />
        <StatCard icon={<Icons.bell size={18} />} label="Low Stock Alerts" value={lowCount} accent />
        <StatCard icon={<Icons.pay size={18} />} label="Stock Value" value={PKR(stockValue)} />
      </div>

      {pendingReclass > 0 && (
        <div className="card card-pad" style={{ marginBottom: 18, borderColor: 'var(--info)', background: 'var(--info-bg)' }}>
          <div className="row" style={{ gap: 12 }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, background: '#fff', display: 'grid', placeItems: 'center' }}><Icons.swap size={18} style={{ color: 'var(--info)' }} /></div>
            <div className="grow">
              <div style={{ fontWeight: 700 }}>{pendingReclass} pool reclassification{pendingReclass>1?'s':''} awaiting approval</div>
              <div className="tiny" style={{ color: 'var(--info)' }}>Sale ⇄ Rental moves change asset treatment — a Branch Manager must approve.</div>
            </div>
            <Btn variant="dark" sm onClick={() => setView('Movements')}>Review</Btn>
          </div>
        </div>
      )}

      {lowCount > 0 && (
        <div className="card card-pad" style={{ marginBottom: 18, borderColor: 'var(--warn)', background: 'linear-gradient(0deg, var(--warn-bg), var(--warn-bg))' }}>
          <div className="row" style={{ gap: 12 }}>
            <div style={{ width: 38, height: 38, borderRadius: 11, background: '#fff', display: 'grid', placeItems: 'center' }}><Icons.bell size={18} style={{ color: 'var(--warn)' }} /></div>
            <div className="grow">
              <div style={{ fontWeight: 700 }}>{lowCount} items below reorder threshold</div>
              <div className="tiny" style={{ color: '#9a6a10' }}>{branchInventory.filter(i=>i.stock<=i.low).map(i=>i.name).join(' · ')}</div>
            </div>
            <Btn variant="dark" sm>Create Purchase Order</Btn>
          </div>
        </div>
      )}

      <div className="card">
        <div className="card-pad row" style={{ justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', paddingBottom: 14 }}>
          <div className="row" style={{ gap: 12, flexWrap: 'wrap' }}>
            <Tabs tabs={['All', 'Machines', 'Spare Parts', 'Accessories']} value={tab} onChange={setTab} />
            <div className="row" style={{ gap: 6, alignItems: 'center' }}>
              <span className="tiny muted" style={{ fontWeight: 700 }}>Pool</span>
              <div className="tabs">{['All', 'Sale', 'Rental'].map(p => <button key={p} className={cls('tab', pool===p&&'active')} onClick={()=>setPool(p)}>{p==='All'?'All':p==='Sale'?'For Sale':'For Rent'}</button>)}</div>
            </div>
          </div>
          <SearchBox value={q} onChange={setQ} placeholder="Item or SKU…" w={220} />
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl">
            <thead><tr><th>Item</th><th>Category</th><th>Pool</th><th>Branch</th><th>Unit Price</th><th>Physical</th><th>System</th><th>Stock Level</th><th></th></tr></thead>
            <tbody>
              {list.map((i) => {
                const machine = isMachine(i);
                const showRent = pool === 'Rental';
                const phys = showRent ? i.rentStock : (i.stock||0);
                const sysv = showRent ? i.rentSys : i.sys;
                const low = !showRent && (i.stock||0) <= i.low;
                const mismatch = phys !== sysv;
                const pct = Math.min(100, (phys / (i.low * 2.5 || 1)) * 100);
                return (
                  <tr key={i.sku || i.id}>
                    <td><div style={{ fontWeight: 700 }}>{i.name}</div><div className="tiny muted mono">{i.sku}</div></td>
                    <td><Badge kind={i.cat==='Machine'?'info':i.cat==='Accessory'?'idle':'ok'}>{i.cat}</Badge></td>
                    <td>
                      {machine ? (
                        <div className="row" style={{ gap: 5 }}>
                          <span className="badge" title="Sale pool" style={{ background: 'var(--info-bg)', color: 'var(--info)' }}>Sale {i.stock}</span>
                          <span className="badge" title="Rental pool" style={{ background: 'var(--warn-bg)', color: 'var(--warn)' }}>Rent {i.rentStock}</span>
                        </div>
                      ) : <span className="tiny muted">Sale only</span>}
                    </td>
                    <td className="muted tiny">{getBranchName(i.branch_id)}</td>
                    <td className="mono">{PKR(i.price)}</td>
                    <td className="mono" style={{ fontWeight: 700 }}>{phys}</td>
                    <td className="mono" style={{ color: mismatch?'var(--bad)':'var(--ink-3)' }}>{sysv}{mismatch && <span className="tiny"> ⚠</span>}</td>
                    <td style={{ width: 150 }}>
                      {showRent
                        ? <div className="tiny muted">On rent / available split</div>
                        : <><div className="track" style={{ height: 7 }}><i style={{ width: pct+'%', background: low?'var(--warn)':'var(--grad-lime)' }} /></div>
                          <div className="tiny" style={{ marginTop: 4, color: low?'var(--warn)':'var(--ink-3)', fontWeight: low?700:500 }}>{low?`Low · reorder at ${i.low}`:`Healthy · min ${i.low}`}</div></>}
                    </td>
                    <td>
                      <div className="row" style={{ gap: 6 }}>
                        {machine && <Btn variant="ghost" sm icon={<Icons.swap size={14} />} onClick={() => openMove('Reclassification')}>Reclassify</Btn>}
                        <Btn variant="ghost" sm onClick={() => setAdj(i)}>Adjust</Btn>
                        {window.can('inventory','delete') && (
                          <Btn variant="ghost" sm icon={<Icons.trash size={13} />}
                            onClick={(e) => { e.stopPropagation(); setDelItem(i); }} />
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
              {!list.length && <tr><td colSpan={9} className="muted tiny" style={{ textAlign: 'center', padding: 20 }}>No items found.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
      </>}

      {adj && <StockAdjust item={adj} branch={branch} branchObj={branchObj} onClose={() => { setAdj(null); refetchInventory(); }} />}
      {move && <StockMove initType={moveType} branch={branch} branchObj={branchObj} onClose={() => { setMove(false); refetchMoves(); refetchInventory(); }} />}
      {delItem && (
        <ConfirmDeleteModal
          title="Delete Inventory Item"
          body={<>Remove <strong>{delItem.name}</strong> (SKU: {delItem.sku}) from inventory? This cannot be undone.</>}
          onCancel={() => setDelItem(null)}
          onConfirm={async () => {
            try {
              await api.deleteInventoryItem(delItem.id);
              window.toast('Item deleted', 'ok');
              setDelItem(null);
              refetchInventory();
            } catch (err) { window.toast(err.message || 'Failed to delete', 'error'); }
          }}
        />
      )}
    </div>
  );
}

/* ---------- Stock movements: branch transfer / consignment / reclassification ---------- */
function StockMovements({ stockMoves, branchList, onNew, refetch }) {
  const [tab, setTab] = useState('All');
  const list = stockMoves.filter((m) => tab === 'All' || m.type === tab);
  const consign = stockMoves.filter(m => m.type === 'Consignment');
  const reclass = stockMoves.filter(m => m.type === 'Reclassification');
  const pending = reclass.filter(m => m.status === 'Pending').length;

  const canApprove = window.can('inventory','approve');

  const approve = async (m) => {
    try {
      await api.updateStockMove(m.id, { status: 'Approved' });
      window.toast(`${m.no} approved — pools updated`, 'ok');
      refetch && refetch();
    } catch (err) {
      window.toast(err.message || 'Failed to approve', 'error');
    }
  };

  const markReceived = async (m) => {
    try {
      await api.updateStockMove(m.id, { status: 'Completed' });
      window.toast(`${m.no} marked as received`, 'ok');
      refetch && refetch();
    } catch (err) {
      window.toast(err.message || 'Failed to update', 'error');
    }
  };

  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 20 }}>
        <StatCard icon={<Icons.swap size={18} />} label="Movements (30d)" value={stockMoves.length} sub="transfers · consign · reclass" />
        <StatCard icon={<Icons.box size={18} />} label="On Consignment" value={consign.reduce((s, m) => s + (m.qty||0), 0)} sub="units with distributors" />
        <StatCard icon={<Icons.rental size={18} />} label="Pool Reclassifications" value={reclass.length} sub="sale ⇄ rental" />
        <StatCard icon={<Icons.bell size={18} />} label="Pending Approval" value={pending} accent />
      </div>
      <div className="card">
        <div className="card-pad row" style={{ justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', paddingBottom: 14 }}>
          <Tabs tabs={['All', 'Branch Transfer', 'Consignment', 'Reclassification']} value={tab} onChange={setTab} />
          <Btn variant="ghost" sm icon={<Icons.swap size={15} />} onClick={() => onNew('Branch Transfer')}>New Movement</Btn>
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl">
            <thead><tr><th>Ref</th><th>Item</th><th>Qty</th><th>From</th><th>To</th><th>Type</th><th>Date</th><th>Status</th></tr></thead>
            <tbody>
              {list.map((m) => {
                const isReclass = m.type === 'Reclassification';
                const poolPill = (v) => <span className="badge" style={{ background: v==='Rental'?'var(--warn-bg)':v==='Sale'?'var(--info-bg)':'var(--surface-3)', color: v==='Rental'?'var(--warn)':v==='Sale'?'var(--info)':'var(--ink-2)' }}>{v}</span>;
                return (
                  <tr key={m.no}>
                    <td className="mono" style={{ fontWeight: 700 }}>{m.no}</td>
                    <td><div style={{ fontWeight: 600 }}>{m.item}</div><div className="tiny muted mono">{m.sku}</div>{isReclass && m.condition && <div className="tiny" style={{ color: 'var(--ink-3)', marginTop: 2 }}>{m.condition}</div>}</td>
                    <td className="mono" style={{ fontWeight: 700 }}>{m.qty}</td>
                    <td>{poolPill(m.from)}</td>
                    <td><span className="row" style={{ gap: 5 }}><Icons.chevR size={13} style={{ color: 'var(--ink-3)' }} />{poolPill(m.to)}</span></td>
                    <td><Badge kind={isReclass ? 'info' : m.type === 'Consignment' ? 'warn' : 'idle'}>{isReclass ? 'Reclassify' : m.type}</Badge></td>
                    <td className="tiny muted">{m.date}</td>
                    <td>
                      <Badge kind={window.statusKind(m.status)}>{m.status}</Badge>
                      {m.type === 'Consignment' && <div className="tiny" style={{ color: m.settled ? 'var(--ok)' : 'var(--warn)', marginTop: 3, fontWeight: 600 }}>{m.settled ? 'Settled' : 'Awaiting settlement'}</div>}
                      {isReclass && <div className="tiny" style={{ color: m.status==='Pending'?'var(--warn)':'var(--ink-3)', marginTop: 3, fontWeight: 600 }}>{m.status==='Pending'?`Needs ${m.approver}`:`✓ ${m.approver}`}</div>}
                      {canApprove && isReclass && m.status === 'Pending' && (
                        <div style={{ marginTop: 6 }}>
                          <Btn variant="primary" sm icon={<Icons.check size={13} stroke={3} />} onClick={() => approve(m)}>Approve</Btn>
                        </div>
                      )}
                      {canApprove && m.type === 'Branch Transfer' && m.status === 'In Transit' && (
                        <div style={{ marginTop: 6 }}>
                          <Btn variant="ghost" sm icon={<Icons.check size={13} />} onClick={() => markReceived(m)}>Mark Received</Btn>
                        </div>
                      )}
                    </td>
                  </tr>
                );
              })}
              {!list.length && <tr><td colSpan={8} className="muted tiny" style={{ textAlign: 'center', padding: 20 }}>No movements found.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function StockMove({ initType = 'Branch Transfer', branch = 'All', branchObj = null, onClose }) {
  const [type, setType] = useState(initType);
  const [item, setItem] = useState('');
  const [fromPool, setFromPool] = useState('Sale');
  const toPool = fromPool === 'Sale' ? 'Rental' : 'Sale';
  const isReclass = type === 'Reclassification';

  const currentUser = api.user || {};
  const ADMIN_ROLES = ['admin', 'owner', 'super admin', 'superadmin'];
  const isAdmin = ADMIN_ROLES.includes((currentUser.role || '').toLowerCase().trim());
  const lockedBranchId = !isAdmin && branch !== 'All' ? branch : null;

  // Branch Transfer / Consignment state
  const [fromBranchId,     setFromBranchId]     = useState(lockedBranchId || '');
  const [toBranchOrDistId, setToBranchOrDistId] = useState('');
  const [moveQty,          setMoveQty]           = useState('');
  const [dispatchedById,   setDispatchedById]    = useState('');

  // Reclassification state
  const [reclassQty,        setReclassQty]        = useState('');
  const [reclassBranchId,   setReclassBranchId]   = useState(lockedBranchId || '');
  const [reclassRatePlan,   setReclassRatePlan]   = useState('Monthly · Rs 18,000');
  const [reclassCondition,  setReclassCondition]  = useState('Demo / Ex-sale');
  const [reclassReason,     setReclassReason]     = useState('');
  const [reclassApproverId, setReclassApproverId] = useState('');

  const [busy, setBusy] = useState(false);

  const { data: branchList } = useBranches();
  const bf = branch !== 'All' ? { branch_id: branch } : {};
  const { data: rawInventory } = useInventory(bf);
  const { data: customers } = useCustomers(bf);
  const { data: users } = useUsers();

  const allInventory = rawInventory.map(normalizeInventory);
  const machines = allInventory.filter(i => i.cat === 'Machine');

  React.useEffect(() => {
    if (!item && machines.length) setItem(machines[0].name);
  }, [machines.length]);

  React.useEffect(() => {
    if (!lockedBranchId && branchList.length && !fromBranchId) setFromBranchId(branchList[0].id);
  }, [branchList.length]);

  const selMachine = machines.find(m => m.name === item) || machines[0] || {};
  const distributors = customers.filter(c => c.type === 'Sub-Distributor');
  const approverUsers = users.filter(u =>
    ['manager', 'branch manager', 'admin', 'owner', 'super admin', 'superadmin'].includes((u.role || '').toLowerCase())
  );

  React.useEffect(() => {
    if (!reclassBranchId && selMachine.branch_id) setReclassBranchId(selMachine.branch_id);
  }, [selMachine.branch_id]);

  const save = async () => {
    setBusy(true);
    try {
      const selInventory = allInventory.find(i => i.name === item);
      const fromBranch   = branchList.find(b => b.id === fromBranchId);
      const toBranch     = branchList.find(b => b.id === toBranchOrDistId);
      const toDist       = distributors.find(d => d.id === toBranchOrDistId);
      const dispUser     = users.find(u => u.id === dispatchedById);
      const moveNum      = 'MV-' + Date.now().toString().slice(-6);
      const today        = new Date().toISOString().slice(0, 10);
      await api.createStockMove({
        move_number:  moveNum,
        item,
        sku:          selInventory ? selInventory.sku : '',
        qty:          parseInt(moveQty) || 0,
        from_loc:     fromBranch ? fromBranch.city : '',
        to_loc:       toBranch ? toBranch.city : (toDist ? toDist.name : ''),
        type,
        date:         today,
        status:       type === 'Branch Transfer' ? 'In Transit' : 'On Consignment',
        by:           dispUser ? dispUser.name : '',
        branch_id:    fromBranchId || null,
      });
      window.toast(`Stock movement ${moveNum} created`, 'ok');
      onClose();
    } catch (err) {
      window.toast(err.message || 'Failed to create movement', 'error');
      setBusy(false);
    }
  };

  const saveReclass = async () => {
    const qty = parseInt(reclassQty) || 0;
    if (!qty) { window.toast('Enter a quantity', 'warn'); return; }
    const avail = fromPool === 'Sale' ? (selMachine.stock || 0) : (selMachine.rentStock || 0);
    if (qty > avail) { window.toast(`Only ${avail} units available in ${fromPool} pool`, 'warn'); return; }
    if (!reclassApproverId) { window.toast('Select an approver', 'warn'); return; }
    setBusy(true);
    try {
      const selInventory = allInventory.find(i => i.name === item);
      const approverUser = users.find(u => u.id === reclassApproverId);
      const moveNum = 'MV-' + Date.now().toString().slice(-6);
      const today   = new Date().toISOString().slice(0, 10);
      await api.createStockMove({
        move_number:  moveNum,
        item,
        sku:          selInventory ? selInventory.sku : '',
        qty,
        from_loc:     fromPool,
        to_loc:       toPool,
        type:         'Reclassification',
        date:         today,
        status:       'Pending',
        by:           currentUser.name || '',
        approver:     approverUser ? approverUser.name : '',
        reason:       reclassReason,
        condition:    toPool === 'Rental' ? reclassCondition : 'Ex-rental / Refurbished',
        branch_id:    reclassBranchId || null,
      });
      window.toast(`Reclassification ${moveNum} submitted for approval`, 'ok');
      onClose();
    } catch (err) {
      window.toast(err.message || 'Failed to submit', 'error');
      setBusy(false);
    }
  };

  return (
    <Modal title="Move Stock" sub="Transfer between branches, place on consignment, or reclassify sale ⇄ rental" onClose={onClose} wide={isReclass}
      foot={<>
        <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
        {isReclass
          ? <Btn variant="primary" icon={<Icons.shield size={16} />} onClick={saveReclass} disabled={busy}>{busy ? 'Submitting…' : 'Submit for Approval'}</Btn>
          : <Btn variant="primary" icon={<Icons.check size={16} />} onClick={save} disabled={busy}>{busy ? 'Saving…' : 'Create Movement'}</Btn>}
      </>}>
      <div style={{ display: 'grid', gap: 14 }}>
        <label className="fld"><span>Movement Type</span>
          <div className="tabs" style={{ width: '100%', display: 'flex' }}>
            {['Branch Transfer', 'Consignment', 'Reclassification'].map(t => (
              <button key={t} className={cls('tab', type === t && 'active')} style={{ flex: 1 }} onClick={() => setType(t)}>{t === 'Reclassification' ? 'Reclassify' : t}</button>
            ))}
          </div>
        </label>

        {!isReclass && <>
          <label className="fld"><span>Item</span>
            <select className="input-block" value={item} onChange={e=>setItem(e.target.value)}>
              {allInventory.map(i => <option key={i.sku||i.id}>{i.name}</option>)}
            </select>
          </label>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="fld"><span>From Branch</span>
              {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 }} />
                  {(branchList.find(b => String(b.id) === String(lockedBranchId)) || branchObj || {}).city || lockedBranchId}
                  <span className="tiny muted" style={{ marginLeft: 'auto' }}>locked</span>
                </div>
              ) : (
                <select className="input-block" value={fromBranchId} onChange={e=>setFromBranchId(e.target.value)}>
                  {branchList.map(b => <option key={b.id} value={b.id}>{b.city} ({b.name})</option>)}
                </select>
              )}
            </label>
            <label className="fld"><span>Quantity</span><input className="input-block mono" value={moveQty} onChange={e=>setMoveQty(e.target.value)} placeholder="0" /></label>
          </div>
          <label className="fld"><span>{type === 'Consignment' ? 'To Distributor' : 'To Branch'}</span>
            <select className="input-block" value={toBranchOrDistId} onChange={e=>setToBranchOrDistId(e.target.value)}>
              <option value="">— Select —</option>
              {type === 'Consignment'
                ? distributors.map(c => <option key={c.id} value={c.id}>{c.name}</option>)
                : branchList.map(b => <option key={b.id} value={b.id}>{b.city} ({b.name})</option>)}
            </select>
          </label>
          {type === 'Consignment' && (
            <div className="row" style={{ gap: 10, padding: '12px 14px', background: 'var(--warn-bg)', borderRadius: 12 }}>
              <Icons.box size={18} style={{ color: 'var(--warn)' }} />
              <span className="tiny" style={{ fontWeight: 600 }}>Consignment stock stays on your books until sold &amp; settled by the distributor.</span>
            </div>
          )}
          <label className="fld"><span>Dispatched By</span>
            <select className="input-block" value={dispatchedById} onChange={e=>setDispatchedById(e.target.value)}>
              <option value="">— Select —</option>
              {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
            </select>
          </label>
        </>}

        {isReclass && <ReclassFields
          item={item} setItem={setItem}
          machines={machines} selMachine={selMachine}
          fromPool={fromPool} setFromPool={setFromPool} toPool={toPool}
          branchList={branchList}
          qty={reclassQty} setQty={setReclassQty}
          branchId={reclassBranchId} setBranchId={setReclassBranchId}
          ratePlan={reclassRatePlan} setRatePlan={setReclassRatePlan}
          condition={reclassCondition} setCondition={setReclassCondition}
          reason={reclassReason} setReason={setReclassReason}
          approverId={reclassApproverId} setApproverId={setReclassApproverId}
          approverUsers={approverUsers}
          lockedBranchId={lockedBranchId} branchObj={branchObj}
        />}
      </div>
    </Modal>
  );
}

function ReclassFields({
  item, setItem, machines, selMachine, fromPool, setFromPool, toPool, branchList,
  qty, setQty, branchId, setBranchId, ratePlan, setRatePlan, condition, setCondition,
  reason, setReason, approverId, setApproverId, approverUsers,
  lockedBranchId, branchObj,
}) {
  const avail = fromPool === 'Sale' ? (selMachine.stock || 0) : (selMachine.rentStock || 0);
  const toRental = toPool === 'Rental';
  return (
    <>
      <label className="fld"><span>Machine</span>
        <select className="input-block" value={item} onChange={e=>setItem(e.target.value)}>
          {machines.map(m => <option key={m.sku||m.id}>{m.name}</option>)}
        </select>
      </label>
      <div className="grid" style={{ gridTemplateColumns: '1fr auto 1fr', gap: 10, alignItems: 'end' }}>
        <label className="fld"><span>From Pool</span>
          <div className="tabs" style={{ width: '100%', display: 'flex' }}>
            {['Sale', 'Rental'].map(p => <button key={p} className={cls('tab', fromPool === p && 'active')} style={{ flex: 1 }} onClick={() => setFromPool(p)}>{p}</button>)}
          </div>
        </label>
        <div style={{ paddingBottom: 10, color: 'var(--ink-3)' }}><Icons.chevR size={18} /></div>
        <label className="fld"><span>To Pool</span>
          <div className="input-block" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', background: toRental?'var(--warn-bg)':'var(--info-bg)', color: toRental?'var(--warn)':'var(--info)', fontWeight: 800 }}>{toPool}</div>
        </label>
      </div>
      <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <label className="fld"><span>Quantity <span className="muted">({avail} in {fromPool.toLowerCase()} pool)</span></span>
          <input className="input-block mono" value={qty} onChange={e=>setQty(e.target.value)} placeholder="0" max={avail} />
        </label>
        <label className="fld"><span>Branch</span>
          {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 }} />
              {(branchList.find(b => String(b.id) === String(lockedBranchId)) || branchObj || {}).city || lockedBranchId}
              <span className="tiny muted" style={{ marginLeft: 'auto' }}>locked</span>
            </div>
          ) : (
            <select className="input-block" value={branchId} onChange={e=>setBranchId(e.target.value)}>
              {branchList.map(b => <option key={b.id} value={b.id}>{b.city} ({b.name})</option>)}
            </select>
          )}
        </label>
      </div>

      {toRental ? (
        <>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="fld"><span>Rental Rate Plan</span>
              <select className="input-block" value={ratePlan} onChange={e=>setRatePlan(e.target.value)}>
                <option>Daily · Rs 1,500</option><option>Weekly · Rs 7,000</option><option>Monthly · Rs 18,000</option>
              </select>
            </label>
            <label className="fld"><span>Condition Grade</span>
              <select className="input-block" value={condition} onChange={e=>setCondition(e.target.value)}>
                <option>Demo / Ex-sale</option><option>New (sealed)</option>
              </select>
            </label>
          </div>
          <div className="row" style={{ gap: 10, padding: '12px 14px', background: 'var(--info-bg)', borderRadius: 12 }}>
            <Icons.box size={18} style={{ color: 'var(--info)', flexShrink: 0 }} />
            <span className="tiny" style={{ fontWeight: 600 }}>Reclassifying to rental <b>capitalizes</b> the unit and starts a depreciation schedule. It leaves the sellable-as-new pool.</span>
          </div>
        </>
      ) : (
        <>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="fld"><span>Condition (locked)</span><input className="input-block" value="Ex-rental / Refurbished" readOnly style={{ background: 'var(--surface-3)', color: 'var(--ink-2)' }} /></label>
            <label className="fld"><span>Resale Price (net book value)</span><input className="input-block mono" placeholder="Rs" /></label>
          </div>
          <div className="row" style={{ gap: 10, padding: '12px 14px', background: 'var(--warn-bg)', borderRadius: 12 }}>
            <Icons.shield size={18} style={{ color: 'var(--warn)', flexShrink: 0 }} />
            <span className="tiny" style={{ fontWeight: 600 }}>A previously-rented unit <b>cannot be sold as new</b>. Run-hours &amp; service history will be attached to the invoice.</span>
          </div>
        </>
      )}

      <label className="fld"><span>Reason / Justification</span>
        <input className="input-block" value={reason} onChange={e=>setReason(e.target.value)} placeholder="e.g. demo unit, rental demand, ex-rental sale" />
      </label>

      <div style={{ border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
        <div className="row" style={{ gap: 9, padding: '11px 14px', background: 'var(--surface-2)', fontWeight: 800, fontSize: 13.5 }}>
          <Icons.shield size={16} style={{ color: 'var(--lime-700)' }} />Approval Required
        </div>
        <div style={{ padding: '12px 14px' }}>
          <label className="fld"><span>Approver</span>
            <select className="input-block" value={approverId} onChange={e=>setApproverId(e.target.value)}>
              <option value="">— Select approver —</option>
              {approverUsers.map(u => <option key={u.id} value={u.id}>{u.name} · {u.role}</option>)}
            </select>
          </label>
          <div className="tiny muted" style={{ marginTop: 8 }}>Submitting creates a <b>Pending</b> movement; pool counts update only once approved.</div>
        </div>
      </div>
    </>
  );
}

function StockAdjust({ item, branch = 'All', branchObj = null, onClose }) {
  const { PKR } = window.DATA;
  const { data: branchList } = useBranches();
  const isNew = item.sku === 'NEW';

  // Determine if current user is admin
  const currentUser = api.user || {};
  const ADMIN_ROLES = ['admin', 'owner', 'super admin', 'superadmin'];
  const isAdmin = ADMIN_ROLES.includes((currentUser.role || '').toLowerCase().trim());

  // For non-admins: branch is locked to their assigned branch
  const defaultBranch = !isAdmin && branch !== 'All' ? branch
    : item.branch_id || (branch !== 'All' ? branch : '');

  const [mode,     setMode]     = useState('Add');
  const [itemName, setItemName] = useState('');
  const [category, setCategory] = useState('Spare Part');
  const [price,    setPrice]    = useState(item.price != null ? String(item.price) : '');
  const [cost,     setCost]     = useState(item.cost_price != null ? String(item.cost_price) : '');
  const [qty,      setQty]      = useState('');
  const [reorder,  setReorder]  = useState(String(item.low_threshold || item.low || 10));
  const [branchId, setBranchId] = useState(defaultBranch);
  const [note,     setNote]     = useState('');
  const [busy,     setBusy]     = useState(false);

  const save = async () => {
    if (isNew && !itemName.trim()) { window.toast('Item name is required', 'warn'); return; }
    setBusy(true);
    try {
      if (isNew) {
        const sku = 'SKU-' + Date.now().toString().slice(-6);
        // Create product in catalogue so it appears in Sales / Quotations dropdowns
        await api.createProduct({
          sku,
          name: itemName.trim(),
          type: category,   // category matches product type values
          category,
          price: parseFloat(price) || 0,
          cost_price: parseFloat(cost) || 0,
          status: 'active',
        });
        // Create inventory stock record
        await api.createInventoryItem({
          name: itemName.trim(),
          category,
          price: parseFloat(price) || 0,
          cost_price: parseFloat(cost) || 0,
          stock: parseInt(qty) || 0,
          low_threshold: parseInt(reorder) || 10,
          branch_id: branchId || null,
          sku,
        });
        window.toast('Item added to catalogue and inventory', 'ok');
      } else {
        const qtyNum = parseInt(qty) || 0;
        const newStock = mode === 'Add'
          ? (item.stock || 0) + qtyNum
          : mode === 'Consume'
            ? Math.max(0, (item.stock || 0) - qtyNum)
            : qtyNum;
        await api.updateInventory(item.id, {
          stock: newStock,
          low_threshold: parseInt(reorder) || item.low_threshold,
          branch_id: branchId || item.branch_id,
          cost_price: cost !== '' ? (parseFloat(cost) || 0) : item.cost_price,
          price:      price !== '' ? (parseFloat(price) || 0) : item.price,
        });
        window.toast('Stock updated', 'ok');
      }
      onClose();
    } catch (err) {
      window.toast(err.message || 'Failed to save', 'error');
      setBusy(false);
    }
  };

  return (
    <Modal title={isNew ? 'Add Inventory Item' : `Adjust · ${item.name}`} sub={isNew ? 'New catalogue entry' : `${item.sku} · current ${item.stock} units`} onClose={onClose}
      foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon={<Icons.check size={16}/>} onClick={save} disabled={busy}>{busy?'Saving…':isNew?'Save Item':'Apply Adjustment'}</Btn></>}>
      <div style={{ display: 'grid', gap: 14 }}>
        {isNew && <>
          <label className="fld"><span>Item Name</span><input className="input-block" value={itemName} onChange={e=>setItemName(e.target.value)} placeholder="e.g. CPAP Air Filter" /></label>
          <label className="fld"><span>Category</span>
            <select className="input-block" value={category} onChange={e=>setCategory(e.target.value)}>
              <option>Spare Part</option><option>Accessory</option><option>Machine</option>
            </select>
          </label>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="fld"><span>Purchase Price <span className="tiny muted">(cost)</span></span><input className="input-block mono" value={cost} onChange={e=>setCost(e.target.value)} placeholder="Rs" /></label>
            <label className="fld"><span>Sale Price <span className="tiny muted">(unit)</span></span><input className="input-block mono" value={price} onChange={e=>setPrice(e.target.value)} placeholder="Rs" /></label>
          </div>
          {parseFloat(price) > 0 && parseFloat(cost) >= 0 && (
            <div className="tiny muted" style={{ marginTop: -6 }}>Margin per unit: <b style={{ color: (parseFloat(price)-parseFloat(cost||0))>=0?'var(--ok)':'var(--bad)' }}>Rs {Math.round(parseFloat(price)-parseFloat(cost||0)).toLocaleString('en-PK')}</b>{parseFloat(price)>0 && <> · {Math.round((parseFloat(price)-parseFloat(cost||0))/parseFloat(price)*100)}%</>}</div>
          )}
        </>}
        {!isNew && <>
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="fld"><span>Purchase Price <span className="tiny muted">(cost)</span></span><input className="input-block mono" value={cost} onChange={e=>setCost(e.target.value)} placeholder="Rs" /></label>
            <label className="fld"><span>Sale Price <span className="tiny muted">(unit)</span></span><input className="input-block mono" value={price} onChange={e=>setPrice(e.target.value)} placeholder="Rs" /></label>
          </div>
          <label className="fld"><span>Adjustment Type</span>
            <div className="tabs" style={{ width: '100%', display: 'flex' }}>{['Add','Consume','Audit Set'].map(t=><button key={t} className={cls('tab', mode===t&&'active')} style={{flex:1}} onClick={()=>setMode(t)}>{t}</button>)}</div>
          </label>
        </>}
        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <label className="fld"><span>Quantity</span><input className="input-block mono" value={qty} onChange={e=>setQty(e.target.value)} placeholder="0" /></label>
          <label className="fld"><span>Reorder Threshold</span><input className="input-block mono" value={reorder} onChange={e=>setReorder(e.target.value)} /></label>
        </div>
        <label className="fld"><span>Branch</span>
          {!isAdmin && branchId ? (
            <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 }} />
              {(branchList.find(b => String(b.id) === String(branchId)) || branchObj || {}).city || branchId}
              <span className="tiny muted" style={{ marginLeft: 'auto' }}>locked to your branch</span>
            </div>
          ) : (
            <select className="input-block" value={branchId} onChange={e=>setBranchId(e.target.value)}>
              <option value="">— Select Branch —</option>
              {branchList.map(b => <option key={b.id} value={b.id}>{b.city} ({b.name})</option>)}
            </select>
          )}
        </label>
        <label className="fld"><span>Reason / Note</span><input className="input-block" value={note} onChange={e=>setNote(e.target.value)} placeholder="Optional" /></label>
      </div>
    </Modal>
  );
}
window.Inventory = Inventory;
window.StockMove  = StockMove;
