/* screens-forecast-warehouse.jsx — /planner/forecast/warehouse
   Báo cáo theo kho — sản lượng + WLU theo Kênh, Nhóm sản phẩm,
   Hãng vận chuyển, Loại Picking list. */

// ---------- Breakdown dimensions ----------
const WH_CHANNELS = [
  { id: 'SPE', label: 'Unilever',      color: '#ee4d2d', share: 0.36 },
  { id: 'TTS', label: 'TikTok Shop', color: '#111827', share: 0.24 },
  { id: 'LZD', label: 'L’Oréal',      color: '#0f146d', share: 0.28 },
  { id: 'ETC', label: 'Khác',        color: '#9ca3af', share: 0.12 },
];
const WH_CATEGORIES = [
  { id: 'COSM', label: 'Mỹ phẩm',     color: '#ec4899', share: 0.28, wluFactor: 0.9 },
  { id: 'ELEC', label: 'Điện tử',     color: '#0b43ea', share: 0.22, wluFactor: 1.1 },
  { id: 'FOOD', label: 'Thực phẩm',   color: '#15803d', share: 0.18, wluFactor: 1.0 },
  { id: 'HOME', label: 'Gia dụng',    color: '#f59e0b', share: 0.14, wluFactor: 1.2 },
  { id: 'FASH', label: 'Thời trang',  color: '#a855f7', share: 0.12, wluFactor: 0.85 },
  { id: 'ETC',  label: 'Khác',        color: '#9ca3af', share: 0.06, wluFactor: 1.0 },
];
const WH_CARRIERS = [
  { id: 'GHN',  label: 'GHN',          color: '#0b43ea', share: 0.30 },
  { id: 'GHTK', label: 'GHTK',         color: '#15803d', share: 0.22 },
  { id: 'JNT',  label: 'J&T Express',  color: '#dc2626', share: 0.18 },
  { id: 'VTP',  label: 'Viettel Post', color: '#f59e0b', share: 0.14 },
  { id: 'BEST', label: 'BEST Express', color: '#a855f7', share: 0.10 },
  { id: 'ETC',  label: 'Khác',         color: '#9ca3af', share: 0.06 },
];

function splitBy(qty, wlu, items) {
  const totalShare = items.reduce((s, i) => s + i.share, 0) || 1;
  let totalWluRaw = items.reduce((s, i) => s + i.share * (i.wluFactor ?? 1), 0) || 1;
  return items.map(i => {
    const myShare = i.share / totalShare;
    const myQty   = Math.round(qty * myShare);
    const myWlu   = Math.round(wlu * (i.share * (i.wluFactor ?? 1)) / totalWluRaw);
    return { ...i, qty: myQty, wlu: myWlu, share: myShare };
  });
}

// ============================================================
// Page
// ============================================================
function ForecastWarehouseScreen({ warehouseId, navigate }) {
  const [dateOffset, setDateOffset] = React.useState(0);
  const [shiftFilter, setShiftFilter] = React.useState('all');
  const [channelFilter, setChannelFilter] = React.useState('all');
  const [categoryFilter, setCategoryFilter] = React.useState('all');
  const { isMobile, vw } = useViewport();
  const stacked = vw < 1200;

  const wh = WFP.WAREHOUSES.find(w => w.id === warehouseId);
  const baseMeta = WFP.WH_BASE[warehouseId];
  if (!wh || !baseMeta) return <Empty icon="warehouse" title="Kho không khả dụng" subtitle="Chọn kho đang hoạt động ở thanh trên."/>;

  // Selected day
  const TODAY = new Date('2026-05-18T00:00:00Z');
  const selDate = new Date(TODAY.getTime() + dateOffset * 86400000);
  const selISO = selDate.toISOString().slice(0, 10);
  const selRow = WFP.DAILY_ORDERS.find(r => r.warehouseId === warehouseId && r.date === selISO);

  // Per-shift breakdown
  const shiftRows = WFP.SHIFTS_DEF.map(s => {
    const split = { CA_SANG: 0.45, CA_CHIEU: 0.42, CA_DEM: 0.13 }[s.code];
    return { ...s, qty: Math.round((selRow?.qty || 0) * split), wlu: Math.round((selRow?.wlu || 0) * split) };
  });

  // Breakdowns (sản lượng + WLU)
  const channelRows  = splitBy(selRow?.qty || 0, selRow?.wlu || 0, WH_CHANNELS);
  const categoryRows = splitBy(selRow?.qty || 0, selRow?.wlu || 0, WH_CATEGORIES);
  const carrierRows  = splitBy(selRow?.qty || 0, selRow?.wlu || 0, WH_CARRIERS);
  const pickingRows  = splitBy(selRow?.qty || 0, selRow?.wlu || 0, WFP.PRODUCT_GROUPS.map(g => ({
    id: g.id, label: vnPickingLabel(g.id), color: g.color, share: g.share,
    wluFactor: g.id === 'HEAVY' ? 1.6 : g.id === 'BUNDLE' ? 1.2 : g.id === 'FRAGILE' ? 1.15 : 1.0,
  })));

  // Date strip
  const dateStrip = [];
  for (let i = -7; i <= 7; i++) {
    const d = new Date(TODAY.getTime() + i * 86400000);
    const iso = d.toISOString().slice(0, 10);
    const row = WFP.DAILY_ORDERS.find(r => r.warehouseId === warehouseId && r.date === iso);
    dateStrip.push({ offset: i, iso, qty: row?.qty || 0, dayType: row?.dayType || 'NORMAL', isFuture: i > 0, isToday: i === 0 });
  }
  const stripMax = Math.max(...dateStrip.map(d => d.qty), 1);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <PageHeader
        breadcrumb={['Dự báo', 'Theo kho', wh.code]}
        title={'Dự báo · ' + wh.name}
        subtitle={
          vnDayType(selRow?.dayType || 'NORMAL') + ' · ' +
          fmt.int(selRow?.qty || 0) + ' đơn · ' +
          fmt.int(selRow?.wlu || 0) + ' WLU · năng lực ' + fmt.int(baseMeta.cap)
        }
        status={<Badge kind={selRow?.isFuture ? 'INFO' : 'APPROVED'} size="sm">{selRow?.isFuture ? 'DỰ BÁO' : 'THỰC TẾ'}</Badge>}
        actions={
          <>
            <Button variant="outline" icon="forecast" onClick={() => navigate('/planner/forecast')}>{isMobile ? 'Tổng quan' : 'Tổng quan'}</Button>
            <Button variant="outline" icon="users" onClick={() => navigate('/planner/forecast/customer')}>{isMobile ? 'Khách hàng' : 'Khách hàng'}</Button>
            <Button variant="primary" icon="plan" onClick={() => navigate('/planner/shift-plan')}>{isMobile ? 'Kế hoạch ca' : 'Sang kế hoạch ca'}</Button>
          </>
        }
      />

      {/* Date strip */}
      <div style={{ padding: '12px 16px', background: '#fff', borderBottom: '1px solid var(--bx-border-muted)',
        display: 'flex', alignItems: 'center', gap: 6, overflowX: 'auto' }}>
        <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginRight: 4, flexShrink: 0 }}>
          15 ngày
        </div>
        {dateStrip.map(d => {
          const active = d.offset === dateOffset;
          const dayBg = d.dayType === 'MEGA_SALE' ? '#fef2f2' : d.dayType === 'MINI_SPIKE' ? '#fefce8' : d.dayType === 'PAYDAY' ? '#eff6ff' : 'transparent';
          return (
            <button key={d.iso} onClick={() => setDateOffset(d.offset)} style={{
              flexShrink: 0, padding: '6px 10px', minWidth: 64,
              background: active ? 'var(--bx-primary)' : dayBg,
              color: active ? '#fff' : 'var(--bx-text-dark)',
              border: '1px solid ' + (active ? 'var(--bx-primary)' : 'var(--bx-border-muted)'),
              borderRadius: 8, cursor: 'pointer',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
              opacity: d.isFuture ? (active ? 1 : 0.9) : 1,
              fontFamily: 'var(--bx-font-sans)',
            }}>
              <span style={{ fontSize: 10, fontWeight: 600, opacity: 0.75, letterSpacing: '0.04em' }}>
                {d.isToday ? 'HÔM NAY' : vnWeekdayShort(d.iso).toUpperCase()}
              </span>
              <span style={{ fontSize: 13, fontWeight: 700, fontFamily: 'var(--bx-font-mono)' }}>
                {new Date(d.iso).toLocaleDateString('en-US', { day: '2-digit' })}
              </span>
              <div style={{ width: 32, height: 3, background: active ? '#fff' : 'var(--bx-border)', borderRadius: 2, overflow: 'hidden', opacity: 0.4 }}>
                <div style={{ width: (d.qty / stripMax * 100) + '%', height: '100%', background: active ? '#fff' : (d.dayType === 'MEGA_SALE' ? 'var(--bx-error)' : d.dayType === 'MINI_SPIKE' ? '#d97706' : 'var(--bx-primary)'), opacity: 1 }}/>
              </div>
            </button>
          );
        })}
      </div>

      {/* Filter row */}
      <div style={{ padding: '10px 16px', background: 'var(--bx-surface-2)', borderBottom: '1px solid var(--bx-border-muted)',
        display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
        <div style={{ fontSize: 11, color: 'var(--bx-text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700, marginRight: 2 }}>Lọc</div>
        <div style={{ width: 140 }}>
          <Select size="sm" value={shiftFilter} onChange={e => setShiftFilter(e.target.value)} options={[
            { value: 'all', label: 'Tất cả ca' },
            ...WFP.SHIFTS_DEF.map(s => ({ value: s.code, label: s.code + ' · ' + vnShiftLabel(s.code) })),
          ]}/>
        </div>
        <div style={{ width: 140 }}>
          <Select size="sm" value={channelFilter} onChange={e => setChannelFilter(e.target.value)} options={[
            { value: 'all', label: 'Tất cả kênh' },
            ...WH_CHANNELS.map(c => ({ value: c.id, label: c.label })),
          ]}/>
        </div>
        <div style={{ width: 170 }}>
          <Select size="sm" value={categoryFilter} onChange={e => setCategoryFilter(e.target.value)} options={[
            { value: 'all', label: 'Tất cả nhóm hàng' },
            ...WH_CATEGORIES.map(c => ({ value: c.id, label: c.label })),
          ]}/>
        </div>
        <div style={{ flex: 1 }}/>
        <Button size="sm" variant="ghost" icon="x" onClick={() => { setShiftFilter('all'); setChannelFilter('all'); setCategoryFilter('all'); }}>Đặt lại</Button>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? 14 : 20, display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* KPI row */}
        <div style={{ display: 'grid', gridTemplateColumns: vw < 560 ? 'repeat(2,1fr)' : 'repeat(4,1fr)', gap: 12 }}>
          <Metric icon="cube" label="Sản lượng" value={fmt.int(selRow?.qty || 0)} sublabel="đơn dự báo"/>
          <Metric icon="spark" label="WLU" value={fmt.int(selRow?.wlu || 0)}
            sublabel={'×' + ((selRow?.wlu || 0) / (selRow?.qty || 1)).toFixed(2) + ' hệ số độ phức tạp'}/>
          <Metric icon="plan" label="Tỷ lệ dùng năng lực"
            value={Math.round((selRow?.wlu || 0) / baseMeta.cap * 100) + '%'}
            sublabel={'trần ' + fmt.int(baseMeta.cap) + ' WLU'}
            deltaTone={(selRow?.wlu || 0) / baseMeta.cap > 0.95 ? 'down' : (selRow?.wlu || 0) / baseMeta.cap > 0.85 ? 'flat' : 'up'}/>
          <Metric icon="users" label="Số khách" value={WFP.customerSplitForWh(warehouseId).length}
            sublabel="khách trong kho · ngày này"/>
        </div>

        {/* Volume + shift */}
        <div style={{ display: 'grid', gridTemplateColumns: stacked ? '1fr' : '1.4fr 1fr', gap: 16 }}>
          <Card title="Sản lượng vs WLU" subtitle="30 ngày qua + 14 ngày dự báo">
            <DualAxisChart data={[
              ...WFP.DAILY_ORDERS.filter(r => r.warehouseId === warehouseId).slice(30, 60),
              ...WFP.DAILY_ORDERS.filter(r => r.warehouseId === warehouseId).slice(60),
            ].map(r => ({ ...r, label: r.date.slice(5) }))}
              barKey="qty" lineKey="wlu" height={260}/>
          </Card>

          <Card title="Phân bổ theo ca" subtitle={'Ngày ' + fmt.date(selISO)} padding={16}>
            <ChartLegend items={WFP.SHIFTS_DEF.map(s => ({ color: s.color, label: s.code + ' · ' + s.start + '–' + s.end }))} style={{ marginBottom: 12 }}/>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 8 }}>
              <Donut items={shiftRows.map(s => ({ value: s.qty, color: s.color }))} size={120} thickness={20}
                centerLabel={fmt.int(shiftRows.reduce((s, r) => s + r.qty, 0))}
                centerSub="đơn"/>
              <div style={{ flex: 1 }}>
                <HBar items={shiftRows.map(s => ({
                  label: vnShiftLabel(s.code), sub: s.start + '–' + s.end,
                  value: s.qty, color: s.color,
                }))} labelWidth={88} valueWidth={64} height={12}/>
              </div>
            </div>
          </Card>
        </div>

        {/* 4 Breakdowns */}
        <div style={{ display: 'grid', gridTemplateColumns: stacked ? '1fr' : '1fr 1fr', gap: 16 }}>
          <BreakdownCard
            title="Theo kênh bán" subtitle="Unilever · TikTok Shop · L’Oréal · Khác"
            rows={channelRows} dimLabel="Kênh"/>

          <BreakdownCard
            title="Theo nhóm sản phẩm" subtitle="Phân loại hàng — ảnh hưởng độ phức tạp"
            rows={categoryRows} dimLabel="Nhóm"/>

          <BreakdownCard
            title="Theo hãng vận chuyển" subtitle="Phân chia đơn cho các đối tác giao hàng"
            rows={carrierRows} dimLabel="Hãng"/>

          <BreakdownCard
            title="Theo loại Picking list" subtitle="Single · Mix · Bundle · Heavy · Fragile"
            rows={pickingRows} dimLabel="Loại"/>
        </div>
      </div>
    </div>
  );
}

// ---------- Breakdown card (table with bar) ----------
function BreakdownCard({ title, subtitle, rows, dimLabel }) {
  const totalQty = rows.reduce((s, r) => s + r.qty, 0) || 1;
  const totalWlu = rows.reduce((s, r) => s + r.wlu, 0) || 1;
  const maxQty = Math.max(...rows.map(r => r.qty), 1);
  return (
    <Card title={title} subtitle={subtitle} padding={0}>
      <Table dense columns={[
        { header: dimLabel, render: r => (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: r.color, flexShrink: 0 }}/>
            <span style={{ fontWeight: 600 }}>{r.label}</span>
          </span>
        )},
        { header: 'Sản lượng', mono: true, align: 'right', render: r => fmt.int(r.qty) },
        { header: 'WLU',        mono: true, align: 'right', render: r => (
          <b style={{ color: r.id === 'HEAVY' ? 'var(--bx-error)' : 'var(--bx-text-dark)' }}>{fmt.int(r.wlu)}</b>
        )},
        { header: 'Tỷ trọng', render: r => (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 110 }}>
            <div style={{ flex: 1, height: 5, background: 'var(--bx-surface-2)', borderRadius: 5, overflow: 'hidden' }}>
              <div style={{ width: (r.qty / maxQty * 100) + '%', height: '100%', background: r.color }}/>
            </div>
            <span style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 11, fontWeight: 600, color: 'var(--bx-text-muted)', minWidth: 32, textAlign: 'right' }}>
              {Math.round(r.qty / totalQty * 100)}%
            </span>
          </div>
        )},
      ]} rows={rows} getRowKey={r => r.id}/>
      <div style={{ padding: '8px 12px', borderTop: '1px solid var(--bx-border-muted)', background: 'var(--bx-surface-2)',
        display: 'flex', alignItems: 'center', gap: 14, fontSize: 11, color: 'var(--bx-text-muted)' }}>
        <span>Tổng</span>
        <span style={{ flex: 1 }}/>
        <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700, color: 'var(--bx-text-dark)' }}>{fmt.int(totalQty)} đơn</span>
        <span style={{ fontFamily: 'var(--bx-font-mono)', fontWeight: 700, color: 'var(--bx-text-dark)' }}>{fmt.int(totalWlu)} WLU</span>
      </div>
    </Card>
  );
}

// ---------- Localization helpers ----------
function vnPickingLabel(id) {
  return { SINGLE: 'Single · 1 SKU/1 đơn', MIX: 'Mix · nhiều SKU/1 đơn', BUNDLE: 'Bundle · gói khuyến mại', HEAVY: 'Heavy · >5kg / cồng kềnh', FRAGILE: 'Fragile · dễ vỡ / chất lỏng' }[id] || id;
}
function vnShiftLabel(code) {
  return { CA_SANG: 'Ca sáng', CA_CHIEU: 'Ca chiều', CA_DEM: 'Ca đêm' }[code] || code;
}
function vnDayType(t) {
  return {
    MEGA_SALE:  'Mega Sale',
    MINI_SPIKE: 'Mini Spike',
    PAYDAY:     'Payday',
    MID_MONTH:  'Mid-Month',
    DOUBLE_DAY: 'Double Day',
    NORMAL:     'Ngày thường',
  }[t] || t;
}
function vnWeekdayShort(iso) {
  return ['CN','T2','T3','T4','T5','T6','T7'][new Date(iso).getDay()];
}

Object.assign(window, { ForecastWarehouseScreen });
