/* =============================================================
   KASDAP ONE — ORDERS + TRACKING
============================================================= */
const { useState: useStateOR } = React;

const STAGES = {
  order: ['Confirmed', 'Packed', 'Shipped', 'Delivered'],
  rfq: ['Requested', 'Quoted', 'Approved', 'Dispatched'],
};
const timeAgo = (t) => { const d = Math.floor((Date.now() - t) / 86400000); return d === 0 ? 'Today' : d === 1 ? 'Yesterday' : d + ' days ago'; };

function OrdersScreen() {
  const { orders, go, user, userModes } = useStore();
  const [filter, setFilter] = useStateOR('all');
  const own = orders.filter(o => o.uid ? o.uid === user.id : (o.customer && o.customer.name === user.name));
  const mine = own.filter(o => filter === 'all' ? true : filter === 'd2c' ? o.mode === 'd2c' : filter === 'b2b' ? o.mode === 'b2b' : o.kind === 'rfq');

  return React.createElement('div', { className: 'page-wrap' },
    React.createElement('div', { style: { display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 20 } },
      React.createElement('div', null,
        React.createElement('h1', { style: { fontSize: '1.9rem' } }, 'Orders & quotes'),
        React.createElement('p', { className: 'muted', style: { marginTop: 4 } }, 'Track every D2C order and B2B quote in one place')),
      React.createElement('div', { className: 'seg' },
        (() => { const m = userModes(user);
          let segs = [['all', 'All']];
          if (m.length > 1) { segs.push(['d2c', 'D2C'], ['b2b', 'B2B']); }
          if (m.includes('b2b')) segs.push(['rfq', 'Quotes']);
          return segs; })().map(([k, l]) =>
          React.createElement('button', { key: k, className: filter === k ? 'on' : '', onClick: () => setFilter(k) }, l)))
    ),
    mine.length === 0
      ? React.createElement('div', { style: { textAlign: 'center', padding: '60px 20px', color: 'var(--text-3)' } },
          React.createElement(Icon, { name: 'receipt', size: 34, style: { margin: '0 auto 14px' } }),
          React.createElement('div', { style: { fontWeight: 700, color: 'var(--text-2)' } }, 'No orders yet'),
          React.createElement('button', { className: 'btn btn-accent', style: { marginTop: 16 }, onClick: () => go('catalog') }, 'Start ordering'))
      : React.createElement('div', { className: 'ord-list' },
          mine.map(o => {
            const stages = STAGES[o.kind] || STAGES.order;
            return React.createElement('div', { key: o.id, className: 'ord-card', onClick: () => go('order', { id: o.id }) },
              React.createElement('div', { className: 'ord-kind ' + o.mode }, React.createElement(Icon, { name: o.kind === 'rfq' ? 'receipt' : (o.mode === 'b2b' ? 'building' : 'user'), size: 20 })),
              React.createElement('div', null,
                React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
                  React.createElement('span', { className: 'ord-id' }, o.id),
                  React.createElement('span', { className: 'pill ' + (o.status === 'delivered' || o.status === 'dispatched' ? 'ok' : o.status === 'quoted' ? 'warn' : o.status === 'cancelled' ? 'danger' : 'info') }, (stages[(o.stage || 1) - 1] || o.status))),
                React.createElement('div', { className: 'ord-meta' }, timeAgo(o.createdAt) + ' · ' + o.lines.length + ' items · ' + (o.kind === 'rfq' ? 'B2B quote' : (o.mode === 'b2b' ? 'B2B order' : 'D2C order')) + (o.customer && user && user.role === 'admin' ? ' · ' + o.customer.name : ''))),
              React.createElement('div', null,
                React.createElement('div', { className: 'ord-amt' }, fmt(o.total)),
                React.createElement('div', { style: { textAlign: 'right', fontSize: '.7rem', color: 'var(--accent)', marginTop: 3, fontWeight: 600 } }, 'View →')));
          })
        )
  );
}

function OrderDetailScreen({ id }) {
  const { orders, productById, go } = useStore();
  const o = orders.find(x => x.id === id);
  if (!o) return React.createElement('div', { className: 'page-wrap' }, 'Order not found');
  const stages = STAGES[o.kind] || STAGES.order;
  const cur = (o.stage || 1) - 1;

  return React.createElement('div', { className: 'page-wrap' },
    React.createElement('div', { className: 'crumb' },
      React.createElement('button', { onClick: () => go('orders') }, React.createElement(Icon, { name: 'back', size: 14 }), 'Orders'),
      React.createElement(Icon, { name: 'chevron', size: 13 }), React.createElement('span', { style: { color: 'var(--text-2)' } }, o.id)),
    React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap', marginBottom: 24 } },
      React.createElement('div', { className: 'ord-kind ' + o.mode, style: { width: 52, height: 52 } }, React.createElement(Icon, { name: o.kind === 'rfq' ? 'receipt' : 'box', size: 24 })),
      React.createElement('div', null,
        React.createElement('h1', { style: { fontSize: '1.5rem' } }, o.id),
        React.createElement('p', { className: 'muted', style: { fontSize: '.84rem' } }, timeAgo(o.createdAt) + ' · ' + (o.kind === 'rfq' ? 'B2B quote' : (o.mode === 'b2b' ? 'B2B order' : 'D2C order')))),
      React.createElement('span', { className: 'pill ' + (cur >= stages.length - 1 ? 'ok' : 'info'), style: { marginLeft: 'auto', fontSize: '.72rem', padding: '6px 12px' } }, stages[cur])),

    React.createElement('div', { className: 'card card-pad', style: { marginBottom: 18 } },
      React.createElement('div', { className: 'eyebrow', style: { marginBottom: 18 } }, o.kind === 'rfq' ? 'Quote progress' : 'Shipment tracking'),
      React.createElement('div', { className: 'track' },
        stages.map((s, i) => React.createElement('div', { key: s, className: 'track-step ' + (i < cur ? 'done' : i === cur ? 'cur' : '') },
          React.createElement('div', { className: 'track-dot' }, i < cur ? React.createElement(Icon, { name: 'check', size: 15 }) : React.createElement('span', { className: 'mono', style: { fontSize: '.7rem' } }, i + 1)),
          React.createElement('div', { className: 'track-lbl' }, s))))
    ),

    React.createElement('div', { className: 'co', style: { alignItems: 'start' } },
      React.createElement('div', { className: 'card card-pad' },
        React.createElement('div', { className: 'card-title', style: { marginBottom: 14 } }, 'Items (' + o.lines.length + ')'),
        React.createElement('div', { className: 'co-lines' },
          o.lines.map((l, i) => { const p = productById[l.handle]; return React.createElement('div', { className: 'co-line', key: i },
            p && React.createElement(ProductImage, { p, className: 'pimg' }),
            React.createElement('div', { className: 'cl-mid' }, React.createElement('div', { className: 'cl-name' }, l.name),
              React.createElement('div', { className: 'cl-meta' }, l.qty + ' × ' + fmt(l.unit) + ' / ' + l.unitLabel)),
            React.createElement('div', { className: 'cl-amt' }, fmt(l.unit * l.qty))); }))
      ),
      React.createElement('div', { className: 'co-aside' },
        React.createElement('div', { className: 'card card-pad' },
          React.createElement('div', { className: 'card-title', style: { marginBottom: 14 } }, o.kind === 'rfq' ? 'Quote total' : 'Payment'),
          o.customer && React.createElement('div', { style: { marginBottom: 14, fontSize: '.82rem' } },
            React.createElement('div', { className: 'faint', style: { fontSize: '.68rem', marginBottom: 3 } }, 'Customer'),
            React.createElement('div', { style: { fontWeight: 600 } }, o.customer.name), o.customer.org && React.createElement('div', { className: 'muted' }, o.customer.org + ' · ' + o.customer.city)),
          React.createElement('div', { className: 'sumrow tot', style: { borderTop: 'none', paddingTop: 0 } }, React.createElement('span', null, 'Total'), React.createElement('span', { className: 'v' }, fmt(o.total))),
          o.kind === 'rfq'
            ? React.createElement('button', { className: 'btn btn-accent btn-block', style: { marginTop: 14 }, onClick: () => go('catalog') }, 'Reorder items')
            : React.createElement('button', { className: 'btn btn-ghost btn-block', style: { marginTop: 14 }, onClick: () => go('catalog') }, React.createElement(Icon, { name: 'copy', size: 15 }), 'Reorder'))
      )
    )
  );
}
Object.assign(window, { OrdersScreen, OrderDetailScreen });
