// Order list view — default landing
// Tweaks-aware: layout (sidebar/topnav), listView (table/card/kanban)

const OrderListView = ({ tweaks, onOpen, onNew }) => {
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [productFilter, setProductFilter] = useState('all');
  const [view, setView] = useState(tweaks.listView || 'table');
  const [sortCol, setSortCol] = useState('created');
  const [sortDir, setSortDir] = useState('desc');
  const [orders, setOrders] = useState(window.ORDERS || ORDERS || []);
  const [loading, setLoading] = useState(false);
  const [page, setPage]     = useState(1);
  const [perPage, setPerPage] = useState(10);

  useEffect(() => { setView(tweaks.listView || 'table'); }, [tweaks.listView]);

  // Fetch orders from DB on mount
  useEffect(() => {
    setLoading(true);
    window.apiFetch('/api/init')
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (data?.orders) {
          window.ORDERS = data.orders;
          if (data.products)          window.PRODUCTS            = data.products;
          if (data.companies)         window.COMPANIES           = data.companies;
          if (data.contacts)          window.CONTACTS            = data.contacts;
          if (data.users)             window.USERS               = data.users;
          if (data.roles)             window.ROLES               = data.roles;
          if (data.workflows)         window.DEFAULT_WORKFLOWS   = data.workflows;
          if (data.conditions)        window.CONDITIONS_DATA     = data.conditions;
          setOrders(data.orders);
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleSort = (col) => {
    setPage(1);
    if (sortCol === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortCol(col); setSortDir('asc'); }
  };

  // Reset to page 1 when filters change
  useEffect(() => { setPage(1); }, [search, statusFilter, productFilter]);

  // Permissions
  const { perms = {}, currentUser = {} } = React.useContext(window.PermCtx);
  const viewScope = perms['View orders'] !== undefined ? perms['View orders'] : 'all';
  const canCreate  = perms['Create orders'] !== false;

  // Helper: match an order's owner field (which may be user ID or abbreviated name) to a user
  const _findOwnerUser = (ownerField) => {
    const users = window.USERS || [];
    return users.find(u => {
      if (u.id === ownerField) return true;
      const sn = u.name.split(' ').map((p, i) => i === 0 ? p : (p[0] || '') + '.').join(' ');
      return sn === ownerField;
    });
  };

  // Scope base list by View orders permission
  const scopedOrders = useMemo(() => {
    if (viewScope === false) return [];
    if (viewScope === 'active') return orders.filter(o => o.status?.id === 'active');
    if (viewScope === 'assigned') {
      return orders.filter(o => o.owner === currentUser.id || o.owner === currentUser.ownerKey);
    }
    if (viewScope === 'own + team') {
      const myTeam = currentUser.team || '';
      return orders.filter(o => {
        if (o.owner === currentUser.id || o.owner === currentUser.ownerKey) return true;
        if (!myTeam) return false;
        const ownerUser = _findOwnerUser(o.owner);
        return ownerUser?.team === myTeam;
      });
    }
    return orders;
  }, [viewScope, currentUser, orders]);

  const filtered = useMemo(() => {
    const prods = window.PRODUCTS || PRODUCTS || [];
    const base = scopedOrders.filter(o => {
      if (statusFilter !== 'all' && o.status?.id !== statusFilter) return false;
      if (productFilter !== 'all' && !o.items.some(it => it.productId === productFilter)) return false;
      if (search) {
        const s = search.toLowerCase();
        if (!o.id.toLowerCase().includes(s) &&
            !(o.company?.name || '').toLowerCase().includes(s) &&
            !o.items.some(it => (prods.find(p => p.id === it.productId)?.name || '').toLowerCase().includes(s))) {
          return false;
        }
      }
      return true;
    });

    // Sort
    return [...base].sort((a, b) => {
      let va, vb;
      if (sortCol === 'id')       { va = a.id; vb = b.id; }
      else if (sortCol === 'company') { va = a.company?.name || ''; vb = b.company?.name || ''; }
      else if (sortCol === 'status')  { va = a.status?.stage ?? 0; vb = b.status?.stage ?? 0; }
      else if (sortCol === 'monthly') { va = a.monthly || 0; vb = b.monthly || 0; }
      else if (sortCol === 'created') { va = new Date(a.createdAt || 0); vb = new Date(b.createdAt || 0); }
      else if (sortCol === 'start')   { va = new Date(a.estimatedStart || 0); vb = new Date(b.estimatedStart || 0); }
      else if (sortCol === 'owner')   { va = a.owner || ''; vb = b.owner || ''; }
      else return 0;
      if (va < vb) return sortDir === 'asc' ? -1 : 1;
      if (va > vb) return sortDir === 'asc' ? 1 : -1;
      return 0;
    });
  }, [scopedOrders, search, statusFilter, productFilter, sortCol, sortDir]);

  // KPIs (scoped to what user can see)
  const kpis = useMemo(() => {
    const all = scopedOrders;
    const inProgress = all.filter(o => ['submitted','pending_apv','approved','provisioning'].includes(o.status.id));
    const active = all.filter(o => o.status.id === 'active');
    const pendingApv = all.filter(o => o.status.id === 'pending_apv');
    const mrr = active.reduce((sum, o) => sum + o.monthly, 0);
    return {
      total: all.length,
      inProgress: inProgress.length,
      pendingApv: pendingApv.length,
      mrr,
    };
  }, [scopedOrders]);

  return (
    <>
      {/* Page header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 20 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 6 }}>Solutions · Order Management</div>
          <h1 style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.01em', margin: 0 }}>คำสั่งซื้อบริการ Solutions</h1>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>
            จัดการคำสั่งซื้อสำหรับลูกค้ากลุ่มธุรกิจ — Cloud PBX, Cloud Contact Center, One Call, Google Workspace, Microsoft 365
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button variant="ghost" icon="download" onClick={() => showToast('Exported ' + filtered.length + ' orders to CSV', { variant: 'success', detail: `solution-orders-${new Date().toISOString().slice(0,10)}.csv` })}>Export CSV</Button>
          {canCreate && <Button variant="primary" icon="plus" onClick={() => onNew()}>New order</Button>}
        </div>
      </div>

      {/* Permission scope indicator */}
      {viewScope !== 'all' && viewScope !== false && (
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '5px 10px', marginBottom: 14,
          background: 'var(--bg-2)', border: '1px solid var(--line)',
          borderRadius: 3, fontSize: 11.5, color: 'var(--ink-3)',
        }}>
          <Icon name="shield" size={12}/>
          <span>
            แสดงเฉพาะ:{' '}
            <strong style={{ color: 'var(--ink-2)' }}>
              {viewScope === 'active' ? 'Active orders เท่านั้น'
               : viewScope === 'assigned' ? 'Order ที่ได้รับมอบหมาย'
               : 'Orders ของทีมฉัน'}
            </strong>
            {' '}· {scopedOrders.length} of {orders.length} orders
          </span>
        </div>
      )}

      {/* Access denied */}
      {viewScope === false ? (
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4, padding: '60px 40px', textAlign: 'center' }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>🔒</div>
          <h3 style={{ fontSize: 16, fontWeight: 600, margin: '0 0 6px' }}>ไม่มีสิทธิ์ดู Orders</h3>
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>Role ของคุณไม่มีสิทธิ์ View orders — ติดต่อ System Admin</div>
        </div>
      ) : (<>

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 20 }}>
        <SummaryStat label="TOTAL ORDERS · YTD" value={kpis.total} sublabel="2026 พฤษภาคม"/>
        <SummaryStat label="IN PROGRESS"        value={kpis.inProgress} sublabel="กำลังดำเนินการ" accent="#d97b2e"/>
        <SummaryStat label="PENDING APPROVAL"   value={kpis.pendingApv}  sublabel="รออนุมัติ" accent="#b8492f"/>
        <SummaryStat label="ACTIVE MRR"         value={fmtBaht(kpis.mrr, { compact: true })} sublabel="รายได้รวมต่อเดือน" accent="#1f7a4d"/>
      </div>

      {/* Filter bar */}
      <div style={{
        background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4,
        padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 12,
      }}>
        <div style={{ position: 'relative', flex: '1 1 260px', maxWidth: 360 }}>
          <span style={{ position: 'absolute', left: 9, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-3)' }}>
            <Icon name="search" size={13}/>
          </span>
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="พิมพ์เพื่อค้นหา Order ID, บริษัท หรือ Product…"
            style={{ ...inputStyle, paddingLeft: 30, fontSize: 12.5 }}/>
        </div>

        <Select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} style={{ width: 'auto', fontSize: 12, padding: '7px 24px 7px 10px' }}>
          <option value="all">All status</option>
          {ORDER_STATUSES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
        </Select>

        <Select value={productFilter} onChange={e => setProductFilter(e.target.value)} style={{ width: 'auto', fontSize: 12, padding: '7px 24px 7px 10px' }}>
          <option value="all">All products</option>
          {(window.PRODUCTS || PRODUCTS)
            .filter(p => p.status === 'live' && !tweaks.hiddenProducts?.includes(p.id))
            .map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
        </Select>

        <Button variant="ghost" size="sm" icon="filter">More filters</Button>

        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>
            <span className="num" style={{ color: 'var(--ink-2)', fontWeight: 500 }}>{filtered.length}</span>
            {' '}of <span className="num">{scopedOrders.length}</span> orders
          </span>
          <Segmented
            options={[
              { value: 'table',  label: 'Table',  icon: 'list' },
              { value: 'card',   label: 'Cards',  icon: 'grid3' },
              { value: 'kanban', label: 'Kanban', icon: 'kanban' },
            ]}
            value={view} onChange={setView} dense/>
        </div>
      </div>

      {/* View */}
      {(() => {
        const totalPages = Math.max(1, Math.ceil(filtered.length / perPage));
        const safePage   = Math.min(page, totalPages);
        const paged      = filtered.slice((safePage - 1) * perPage, safePage * perPage);
        return (<>
          {view === 'table'  && <OrderTable orders={paged} onOpen={onOpen} sortCol={sortCol} sortDir={sortDir} onSort={handleSort} loading={loading}/>}
          {view === 'card'   && <OrderCards orders={filtered} onOpen={onOpen}/>}
          {view === 'kanban' && <OrderKanban orders={filtered} onOpen={onOpen}/>}

          {/* Pagination bar — table view only */}
          {view === 'table' && filtered.length > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14, padding: '0 2px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>แสดง</span>
                {[10, 20, 50].map(n => (
                  <button key={n} onClick={() => { setPerPage(n); setPage(1); }} style={{
                    padding: '3px 10px', fontSize: 11.5, borderRadius: 3, cursor: 'pointer',
                    border: '1px solid var(--line)',
                    background: perPage === n ? 'var(--ink)' : 'var(--panel)',
                    color: perPage === n ? '#fff' : 'var(--ink-2)',
                    fontFamily: 'IBM Plex Mono, monospace',
                    fontWeight: perPage === n ? 600 : 400,
                  }}>{n}</button>
                ))}
                <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>
                  รายการ &nbsp;·&nbsp; <span className="num">{(safePage - 1) * perPage + 1}</span>–<span className="num">{Math.min(safePage * perPage, filtered.length)}</span> จาก <span className="num">{filtered.length}</span>
                </span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={safePage === 1} style={{
                  width: 28, height: 28, borderRadius: 3, border: '1px solid var(--line)',
                  background: 'var(--panel)', cursor: safePage === 1 ? 'default' : 'pointer',
                  opacity: safePage === 1 ? 0.35 : 1, display: 'grid', placeItems: 'center',
                }}><Icon name="chevron" size={11} style={{ transform: 'rotate(180deg)' }}/></button>
                {(() => {
                  const pages = [];
                  const delta = 1;
                  for (let p = 1; p <= totalPages; p++) {
                    if (p === 1 || p === totalPages || (p >= safePage - delta && p <= safePage + delta)) {
                      pages.push(p);
                    } else if (pages[pages.length - 1] !== '…') {
                      pages.push('…');
                    }
                  }
                  return pages.map((p, i) => p === '…' ? (
                    <span key={'e' + i} style={{ width: 28, textAlign: 'center', fontSize: 12, color: 'var(--ink-4)' }}>…</span>
                  ) : (
                    <button key={p} onClick={() => setPage(p)} style={{
                      width: 28, height: 28, borderRadius: 3, border: '1px solid var(--line)',
                      background: safePage === p ? 'var(--ink)' : 'var(--panel)',
                      color: safePage === p ? '#fff' : 'var(--ink-2)',
                      cursor: 'pointer', fontSize: 12, fontFamily: 'IBM Plex Mono, monospace',
                      fontWeight: safePage === p ? 600 : 400,
                    }}>{p}</button>
                  ));
                })()}
                <button onClick={() => setPage(p => Math.min(totalPages, p + 1))} disabled={safePage === totalPages} style={{
                  width: 28, height: 28, borderRadius: 3, border: '1px solid var(--line)',
                  background: 'var(--panel)', cursor: safePage === totalPages ? 'default' : 'pointer',
                  opacity: safePage === totalPages ? 0.35 : 1, display: 'grid', placeItems: 'center',
                }}><Icon name="chevron" size={11}/></button>
              </div>
            </div>
          )}
        </>);
      })()}
      </>)}{/* end viewScope !== false */}
    </>
  );
};

const SummaryStat = ({ label, value, sublabel, accent }) => (
  <div style={{
    background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4,
    padding: '14px 16px', position: 'relative', overflow: 'hidden',
  }}>
    {accent && <div style={{ position: 'absolute', top: 0, left: 0, width: 3, height: '100%', background: accent }}/>}
    <div className="eyebrow">{label}</div>
    <div className="num" style={{ fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 6 }}>{value}</div>
    <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{sublabel}</div>
  </div>
);

// ---------- Table view ----------
const SortIcon = ({ col, sortCol, sortDir }) => {
  if (col !== sortCol) return <span style={{ opacity: 0.25, marginLeft: 3, fontSize: 9 }}>↕</span>;
  return <span style={{ marginLeft: 3, fontSize: 9, color: 'var(--ink)' }}>{sortDir === 'asc' ? '↑' : '↓'}</span>;
};

const OrderTable = ({ orders, onOpen, sortCol, sortDir, onSort, loading }) => (
  <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4, overflow: 'hidden' }}>
    {loading && (
      <div style={{ padding: '6px 12px', background: 'var(--bg-2)', borderBottom: '1px solid var(--line)', fontSize: 11, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name="clock" size={11}/> กำลังโหลดข้อมูลจากฐานข้อมูล…
      </div>
    )}
    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
      <thead>
        <tr style={{ background: 'var(--bg-2)' }}>
          {[
            ['Order ID', 'left', 130, 'id'],
            ['Company', 'left', null, 'company'],
            ['Products', 'left', null, null],
            ['Status', 'left', 140, 'status'],
            ['Monthly', 'right', 100, 'monthly'],
            ['Created', 'right', 90, 'created'],
            ['Est. start', 'right', 100, 'start'],
            ['Owner', 'left', 110, 'owner'],
            ['', 'right', 36, null],
          ].map(([lbl, align, w, col], i) => (
            <th key={i} className="eyebrow" onClick={col ? () => onSort(col) : undefined} style={{
              padding: '10px 10px', textAlign: align, fontWeight: 500,
              borderBottom: '1px solid var(--line)', width: w || undefined,
              cursor: col ? 'pointer' : 'default',
              userSelect: 'none',
              whiteSpace: 'nowrap',
            }}>
              {lbl}{col && <SortIcon col={col} sortCol={sortCol} sortDir={sortDir}/>}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {orders.length === 0 && (
          <tr>
            <td colSpan={9}><Empty icon="file" title="ไม่พบคำสั่งซื้อ" hint="ลองปรับเงื่อนไขการค้นหาหรือ filter"/></td>
          </tr>
        )}
        {orders.map((o, i) => {
          const prods = window.PRODUCTS || PRODUCTS || [];
          const products = o.items.map(it => prods.find(p => p.id === it.productId)).filter(Boolean);
          return (
            <tr key={o.id} onClick={() => onOpen(o.id)} style={{
              borderBottom: i === orders.length - 1 ? 'none' : '1px solid var(--line-2)',
              cursor: 'pointer', transition: 'background 120ms',
            }} onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
               onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <td className="num" style={{ padding: '12px 10px', fontWeight: 500, color: 'var(--ink)' }}>{o.id}</td>
              <td style={{ padding: '12px 10px' }}>
                <div style={{ fontWeight: 500 }}>{o.company.name}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{o.company.sector} · {o.company.province}</div>
              </td>
              <td style={{ padding: '12px 10px' }}>
                <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
                  {products.slice(0, 3).map((p, j) => (
                    <span key={j} style={{
                      display: 'inline-flex', alignItems: 'center', gap: 5,
                      padding: '2px 7px 2px 6px', background: p.color + '12', color: p.color,
                      borderRadius: 2, fontSize: 11, fontWeight: 500,
                    }}>
                      <span style={{ width: 5, height: 5, borderRadius: '50%', background: p.color }}/>
                      {p.name}
                    </span>
                  ))}
                  {products.length > 3 && <span style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>+{products.length - 3}</span>}
                </div>
              </td>
              <td style={{ padding: '12px 10px' }}><StatusChip status={o.status}/></td>
              <td className="num" style={{ padding: '12px 10px', textAlign: 'right', fontWeight: 500 }}>{fmtBaht(o.monthly)}</td>
              <td className="num" style={{ padding: '12px 10px', textAlign: 'right', color: 'var(--ink-2)', fontSize: 11 }}>
                {relTime(o.createdAt)}
              </td>
              <td className="num" style={{ padding: '12px 10px', textAlign: 'right', color: 'var(--ink-2)', fontSize: 11 }}>
                {fmtDateShort(o.estimatedStart)}
              </td>
              <td style={{ padding: '12px 10px' }}>
                {(() => {
                  const ownerUser = (window.USERS || USERS || []).find(u => u.id === o.owner);
                  const name = ownerUser?.name || o.owner || '—';
                  return (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <Avatar name={name} size={20}/>
                      <span style={{ fontSize: 11.5, color: 'var(--ink-2)' }}>{name}</span>
                    </div>
                  );
                })()}
              </td>
              <td style={{ padding: '12px 10px', textAlign: 'right', color: 'var(--ink-3)' }}>
                <Icon name="chevron" size={12}/>
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </div>
);

// ---------- Card view ----------
const OrderCards = ({ orders, onOpen }) => (
  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 12 }}>
    {orders.length === 0 && (
      <div style={{ gridColumn: '1 / -1', background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4 }}>
        <Empty icon="file" title="ไม่พบคำสั่งซื้อ"/>
      </div>
    )}
    {orders.map(o => {
      const _prods = window.PRODUCTS || PRODUCTS;
      const products = o.items.map(it => _prods.find(p => p.id === it.productId)).filter(Boolean);
      const totalSeats = o.items.reduce((s, it) => s + it.qty, 0);
      return (
        <div key={o.id} onClick={() => onOpen(o.id)} style={{
          background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4,
          padding: 16, cursor: 'pointer', transition: 'all 160ms', position: 'relative',
        }} onMouseEnter={e => {
          e.currentTarget.style.transform = 'translateY(-1px)';
          e.currentTarget.style.borderColor = 'var(--ink)';
          e.currentTarget.style.boxShadow = 'var(--shadow-lift)';
        }} onMouseLeave={e => {
          e.currentTarget.style.transform = 'none';
          e.currentTarget.style.borderColor = 'var(--line)';
          e.currentTarget.style.boxShadow = 'none';
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
            <div className="num" style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500 }}>{o.id}</div>
            <StatusChip status={o.status} dense/>
          </div>
          <div style={{ fontWeight: 500, fontSize: 14, marginBottom: 2 }}>{o.company.name}</div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 12 }}>{o.company.sector} · {o.company.province}</div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
            {o.items.map((it, j) => {
              const prod = _prods.find(p => p.id === it.productId);
              if (!prod) return null;
              const pkg = (prod.packages || []).find(p => p.id === it.packageId);
              return (
                <div key={j} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
                  <ProductGlyph productId={it.productId} size={22}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 500, fontSize: 12 }}>{prod.name}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{pkg?.name || '—'} · <span className="num">{it.qty}</span> {prod.unit}{it.qty > 1 ? 's' : ''}</div>
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', borderTop: '1px solid var(--line-2)', paddingTop: 10 }}>
            <div>
              <div className="eyebrow" style={{ fontSize: 9.5 }}>MONTHLY · MRR</div>
              <div className="num" style={{ fontSize: 17, fontWeight: 500, letterSpacing: '-0.02em' }}>{fmtBaht(o.monthly)}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{totalSeats} units · {relTime(o.createdAt)}</div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 4 }}>
                <Avatar name={o.owner} size={16}/>
                <span style={{ fontSize: 10.5, color: 'var(--ink-2)' }}>{o.owner}</span>
              </div>
            </div>
          </div>
        </div>
      );
    })}
  </div>
);

// ---------- Kanban view ----------
const KANBAN_COLS = ['draft','submitted','pending_apv','approved','provisioning','active'];
const OrderKanban = ({ orders, onOpen }) => (
  <div style={{ display: 'grid', gridTemplateColumns: `repeat(${KANBAN_COLS.length}, minmax(220px, 1fr))`, gap: 10, overflowX: 'auto' }}>
    {KANBAN_COLS.map(colId => {
      const status = ORDER_STATUSES.find(s => s.id === colId);
      const cards = orders.filter(o => o.status.id === colId);
      return (
        <div key={colId} style={{ background: 'var(--bg-2)', borderRadius: 4, padding: 8, minHeight: 200 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 6px 8px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: status.color }}/>
              <span style={{ fontSize: 11.5, fontWeight: 500 }}>{status.label}</span>
            </div>
            <span className="num" style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500 }}>{cards.length}</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {cards.map(o => {
              const _prods = window.PRODUCTS || PRODUCTS;
              const products = o.items.map(it => _prods.find(p => p.id === it.productId)).filter(Boolean);
              return (
                <div key={o.id} onClick={() => onOpen(o.id)} style={{
                  background: 'var(--panel)', borderRadius: 3, padding: 10,
                  border: '1px solid var(--line)', cursor: 'pointer', transition: 'all 120ms',
                }} onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--ink)'}
                   onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--line)'}>
                  <div className="num" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{o.id}</div>
                  <div style={{ fontSize: 12, fontWeight: 500, marginTop: 2, lineHeight: 1.3 }}>{o.company.name}</div>
                  <div style={{ display: 'flex', gap: 3, marginTop: 6, flexWrap: 'wrap' }}>
                    {products.map((p, j) => (
                      <span key={j} title={p.name} style={{ width: 6, height: 6, borderRadius: '50%', background: p.color }}/>
                    ))}
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8, borderTop: '1px solid var(--line-2)', paddingTop: 6 }}>
                    <span className="num" style={{ fontSize: 11.5, fontWeight: 500 }}>{fmtBaht(o.monthly, { compact: true })}</span>
                    <Avatar name={o.owner} size={16}/>
                  </div>
                </div>
              );
            })}
            {cards.length === 0 && (
              <div style={{ padding: '24px 8px', textAlign: 'center', color: 'var(--ink-4)', fontSize: 11 }}>—</div>
            )}
          </div>
        </div>
      );
    })}
  </div>
);

Object.assign(window, { OrderListView });
