/* screens-customer-list.jsx — Customer list (simplified) for
   /planner/forecast/customer · just filter + list. Click row → detail. */

function CustomerListPage({ onSelect, navigate }) {
  const [sortKey, setSortKey] = React.useState('avg');
  const [tierFilter, setTierFilter] = React.useState('all');
  const [submitFilter, setSubmitFilter] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const { isMobile } = useViewport();

  const all = WFP.CUSTOMERS_EXT;
  let visible = all.filter(c => {
    if (tierFilter !== 'all' && c.tier !== tierFilter) return false;
    if (submitFilter !== 'all' && c.submitStatus !== submitFilter) return false;
    if (search) {
      const q = search.toLowerCase();
      if (!(c.name + ' ' + c.code + ' ' + c.segment).toLowerCase().includes(q)) return false;
    }
    return true;
  });
  visible = [...visible].sort((a, b) => {
    if (sortKey === 'avg')     return b.avgDaily - a.avgDaily;
    if (sortKey === 'mom')     return Math.abs(b.momPct) - Math.abs(a.momPct);
    if (sortKey === 'vol')     return b.volatility - a.volatility;
    if (sortKey === 'pending') return b.pendingApprovals - a.pendingApprovals;
    return 0;
  });
  const overdueCount = all.filter(c => c.submitStatus === 'OVERDUE').length;
  const pendingTotal = all.reduce((s, c) => s + c.pendingApprovals, 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <PageHeader
        breadcrumb={['Dự báo', 'Khách hàng']}
        title="Khách hàng"
        subtitle={
          all.length + ' khách hàng' +
          (overdueCount > 0 ? ' · ' + overdueCount + ' trễ hạn' : '') +
          (pendingTotal > 0 ? ' · ' + pendingTotal + ' yêu cầu chờ duyệt' : '')
        }
        actions={
          <>
            <Button variant="outline" icon="forecast" onClick={() => navigate('/planner/forecast')}>
              {isMobile ? 'Tổng quan' : 'Tổng quan'}
            </Button>
            <Button variant="primary" icon="upload" onClick={() => navigate('/planner/override-import')}>
              {isMobile ? 'Gửi' : 'Gửi điều chỉnh'}
            </Button>
          </>
        }
      />
      <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? 14 : 20, display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* Filter bar */}
        <Card padding={0}>
          <div style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>Tier</div>
            <Tabs value={tierFilter} onChange={setTierFilter} dense tabs={[
              { id: 'all',      label: 'Tất cả',   count: all.length },
              { id: 'KEY',      label: 'Key',      count: all.filter(c => c.tier === 'KEY').length },
              { id: 'MAJOR',    label: 'Major',    count: all.filter(c => c.tier === 'MAJOR').length },
              { id: 'STANDARD', label: 'Standard', count: all.filter(c => c.tier === 'STANDARD').length },
            ]}/>
            <div style={{ width: 1, height: 22, background: 'var(--bx-border-muted)' }}/>
            <div style={{ width: 240 }}>
              <Input size="sm" placeholder="Tìm theo tên / mã / ngành" icon="search"
                value={search} onChange={e => setSearch(e.target.value)}/>
            </div>
            <div style={{ width: 160 }}>
              <Select size="sm" value={submitFilter} onChange={e => setSubmitFilter(e.target.value)} options={[
                { value: 'all',       label: 'Mọi trạng thái' },
                { value: 'SUBMITTED', label: 'Đã gửi' },
                { value: 'PENDING',   label: 'Chờ duyệt' },
                { value: 'OVERDUE',   label: 'Trễ hạn' },
                { value: 'NONE',      label: 'Chưa gửi' },
              ]}/>
            </div>
            <div style={{ flex: 1 }}/>
            <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700 }}>Sắp xếp</div>
            <Tabs value={sortKey} onChange={setSortKey} dense tabs={[
              { id: 'avg',     label: 'Sản lượng' },
              { id: 'mom',     label: 'MoM' },
              { id: 'vol',     label: 'Biến động' },
              { id: 'pending', label: 'Chờ duyệt' },
            ]}/>
          </div>
        </Card>

        {/* List */}
        <Card title="Danh sách khách hàng"
          subtitle={visible.length === all.length
            ? all.length + ' khách hàng · bấm vào dòng để mở chi tiết'
            : visible.length + ' / ' + all.length + ' khách hàng'}
          padding={0}
          actions={!isMobile && <Button variant="ghost" size="sm" icon="download">CSV</Button>}>
          {visible.length === 0 ? (
            <Empty icon="users" title="Không có khách hàng phù hợp"
              subtitle="Thử thay đổi bộ lọc hoặc xóa từ khóa tìm kiếm."
              action={<Button variant="outline" size="sm" onClick={() => { setSearch(''); setTierFilter('all'); setSubmitFilter('all'); }}>Xóa bộ lọc</Button>}/>
          ) : (
            <Table dense stickyHeader onRowClick={r => onSelect(r.id)}
              columns={[
                { header: 'Khách hàng', render: r => (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <Avatar name={r.name} size={28}/>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontWeight: 600, color: 'var(--bx-text-dark)', fontSize: 13 }}>{r.name}</div>
                      <div style={{ fontSize: 10.5, color: 'var(--bx-text-muted)' }}>{r.segment} · {r.code}</div>
                    </div>
                  </div>
                )},
                { header: 'Tier', priority: 2, render: r => (
                  <Badge kind={r.tier === 'KEY' ? 'APPROVED' : r.tier === 'MAJOR' ? 'INFO' : 'INACTIVE'} size="sm">
                    {r.tier}
                  </Badge>
                )},
                { header: 'Sản lượng / ngày', mono: true, align: 'right', render: r => fmt.int(r.avgDaily) },
                { header: '30 ngày', priority: 2, render: r => (
                  <Sparkline data={r.series} color={r.tier === 'KEY' ? '#0b43ea' : '#4f7dff'} width={88} height={22}/>
                )},
                { header: 'MoM', mono: true, align: 'right', render: r => (
                  <span style={{
                    fontWeight: 600,
                    color: r.momPct > 0 ? 'var(--bx-success)' : r.momPct < 0 ? 'var(--bx-error)' : 'var(--bx-text-muted)',
                  }}>{r.momPct > 0 ? '+' : ''}{r.momPct}%</span>
                )},
                { header: 'YoY', priority: 2, mono: true, align: 'right', render: r => (
                  <span style={{ color: r.yoyPct > 0 ? 'var(--bx-success)' : 'var(--bx-error)', fontWeight: 600 }}>
                    {r.yoyPct > 0 ? '+' : ''}{r.yoyPct}%
                  </span>
                )},
                { header: 'Biến động', priority: 3, render: r => <VolatilityBar v={r.volatility}/> },
                { header: 'Trạng thái', render: r => (
                  <Badge kind={
                    r.submitStatus === 'SUBMITTED' ? 'APPROVED'
                    : r.submitStatus === 'PENDING' ? 'WARNING'
                    : r.submitStatus === 'OVERDUE' ? 'CRITICAL'
                    : 'INACTIVE'
                  } size="sm">{r.submitStatus}</Badge>
                )},
                { header: 'Chờ duyệt', priority: 2, align: 'right', render: r => r.pendingApprovals > 0 ? (
                  <Badge kind="WARNING" size="sm">{r.pendingApprovals} y/c</Badge>
                ) : <span style={{ color: 'var(--bx-text-muted)', fontSize: 11 }}>—</span> },
                { header: '', width: 40, render: () => (
                  <Icon name="chevron-right" size={11} style={{ color: 'var(--bx-text-muted)' }}/>
                )},
              ]}
              rows={visible} getRowKey={r => r.id}/>
          )}
        </Card>
      </div>
    </div>
  );
}

// ---------- Volatility bar (reused) ----------
function VolatilityBar({ v }) {
  const pct = Math.min(100, v * 100 * 2);
  const tone = v >= 0.30 ? 'var(--bx-error)' : v >= 0.18 ? 'var(--bx-warning)' : 'var(--bx-success)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 100 }}>
      <div style={{ flex: 1, height: 5, background: 'var(--bx-surface-2)', borderRadius: 6, overflow: 'hidden' }}>
        <div style={{ width: pct + '%', height: '100%', background: tone }}/>
      </div>
      <span style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 11, fontWeight: 600, color: 'var(--bx-text-body)', minWidth: 32, textAlign: 'right' }}>
        {(v * 100).toFixed(0)}%
      </span>
    </div>
  );
}

Object.assign(window, { CustomerListPage, VolatilityBar });
