/* screens-forecast-overview.jsx — /planner/forecast
   Audience: BOD / Manager — exec view of daily orders + period comparisons. */

function ForecastOverviewScreen({ country, warehouseId, navigate }) {
  const [whScope, setWhScope] = React.useState('all');   // 'all' or wh-id
  const [range, setRange] = React.useState('14d');       // '7d' | '14d' | '30d'
  const [metric, setMetric] = React.useState('qty');     // 'qty' or 'wlu'
  const [compareMode, setCompareMode] = React.useState('lastSale'); // 'lastSale' | 'lastYear' | 'none'
  const { isMobile, isTablet, vw } = useViewport();

  // Filter active warehouses by country
  const countryWhs = WFP.WAREHOUSES.filter(w => w.countryCode === country);

  // Reset warehouse scope if country changes invalidly
  React.useEffect(() => {
    if (whScope !== 'all' && !countryWhs.find(w => w.id === whScope)) setWhScope('all');
  }, [country]);

  const days = range === '7d' ? 7 : range === '14d' ? 14 : 30;

  // Filter daily rows
  function filterDaily(rows) {
    return rows.filter(r => {
      if (whScope === 'all') return countryWhs.some(w => w.id === r.warehouseId);
      return r.warehouseId === whScope;
    });
  }

  const allDaily = filterDaily(WFP.DAILY_ORDERS);
  // Slice to last (days/2) past + (days/2) future centered on today
  const past = Math.floor(days * 0.45);
  const future = days - past;
  const sliced = allDaily.filter(r => {
    const off = Math.round((new Date(r.date) - new Date('2026-05-18T00:00:00Z')) / 86400000);
    return off >= -past && off < future;
  });

  // Aggregate by date
  const byDate = {};
  sliced.forEach(r => {
    if (!byDate[r.date]) byDate[r.date] = { date: r.date, label: r.date.slice(5), qty: 0, wlu: 0, capacity: 0, dayType: r.dayType, isFuture: r.isFuture };
    byDate[r.date].qty += r.qty;
    byDate[r.date].wlu += r.wlu;
    byDate[r.date].capacity += r.capacity;
  });
  const tsRows = Object.values(byDate).sort((a, b) => a.date.localeCompare(b.date));

  // KPIs (past 7 days + next 14 days)
  function rangeSum(rows, off0, off1, key) {
    return rows.reduce((s, r) => {
      const off = Math.round((new Date(r.date) - new Date('2026-05-18T00:00:00Z')) / 86400000);
      return (off >= off0 && off <= off1) ? s + (r[key] || 0) : s;
    }, 0);
  }
  const last7 = rangeSum(allDaily, -7, -1, metric);
  const prev7 = rangeSum(allDaily, -14, -8, metric);
  const next14 = rangeSum(allDaily, 0, 13, metric);
  const next14Cap = rangeSum(allDaily, 0, 13, 'capacity');
  const next14WoW = ((next14 - last7) / last7) * 100;
  const last7WoW = ((last7 - prev7) / prev7) * 100;
  const utilNext = (next14 / next14Cap) * 100;

  // Comparison series
  function withCompare(rows) {
    return rows.map(r => {
      // For aggregate, get compare values per-warehouse and sum
      const sources = whScope === 'all' ? countryWhs.map(w => w.id) : [whScope];
      let lastSaleQty = 0, lastYearQty = 0;
      sources.forEach(whId => {
        const c = WFP.DAILY_COMPARE[whId]?.[r.date];
        if (c) {
          lastSaleQty += c.lastSale.qty;
          lastYearQty += c.lastYear.qty;
        }
      });
      return { ...r, lastSaleQty, lastYearQty };
    });
  }
  const comparable = withCompare(tsRows);

  // Per-warehouse trend cards
  const trends = WFP.WAREHOUSE_TRENDS.filter(t => countryWhs.find(w => w.id === t.warehouseId));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <PageHeader
        breadcrumb={['Forecast', 'Overview']}
        title="Forecast overview"
        subtitle={'Executive view · ' + country + ' · ' + (whScope === 'all' ? countryWhs.length + ' warehouses' : WFP.WAREHOUSES.find(w => w.id === whScope)?.code) + ' · ' + range + ' horizon'}
        actions={
          <>
            {!isMobile && <Button variant="outline" icon="download">Export</Button>}
            <Button variant="outline" icon="diff" onClick={() => navigate('/planner/forecast/customer')}>
              {isMobile ? 'Customers' : 'Drill to customers'}
            </Button>
            <Button variant="primary" icon="warehouse" onClick={() => navigate('/planner/forecast/warehouse')}>
              {isMobile ? 'Warehouse' : 'Drill to warehouse'}
            </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, marginRight: 4 }}>Scope</div>
            <Tabs value={whScope} onChange={setWhScope} dense tabs={[
              { id: 'all', label: 'All ' + country, icon: 'globe' },
              ...countryWhs.map(w => ({ id: w.id, label: w.code })),
            ]}/>
            <div style={{ flex: 1, minWidth: 20 }}/>
            <Tabs value={range} onChange={setRange} dense tabs={[
              { id: '7d', label: '7 days' },
              { id: '14d', label: '14 days' },
              { id: '30d', label: '30 days' },
            ]}/>
            <div style={{ width: 1, height: 22, background: 'var(--bx-border-muted)' }}/>
            <Tabs value={metric} onChange={setMetric} dense tabs={[
              { id: 'qty', label: 'Volume', icon: 'cube' },
              { id: 'wlu', label: 'Workload', icon: 'spark' },
            ]}/>
          </div>
        </Card>

        {/* KPI row */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: vw < 560 ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)',
          gap: 12,
        }}>
          <Metric icon="history" label={'Last 7 days · ' + (metric === 'qty' ? 'volume' : 'workload')}
            value={fmt.int(last7)}
            sublabel={'WoW ' + (last7WoW > 0 ? '+' : '') + last7WoW.toFixed(1) + '%'}
            deltaTone={last7WoW >= 0 ? 'up' : 'down'} delta={fmt.signed(Math.round(last7 - prev7))}/>
          <Metric icon="forecast" label="Next 14 days · forecast"
            value={fmt.int(next14)}
            sublabel={'vs trailing-7 ' + (next14WoW > 0 ? '+' : '') + next14WoW.toFixed(0) + '%'}
            deltaTone={next14WoW >= 0 ? 'up' : 'down'} delta={fmt.signed(Math.round(next14 - last7))}/>
          <Metric icon="plan" label="Capacity utilization"
            value={utilNext.toFixed(0) + '%'}
            sublabel={'of ' + fmt.int(next14Cap) + ' max workload'}
            deltaTone={utilNext > 90 ? 'down' : utilNext > 75 ? 'flat' : 'up'}
            delta={utilNext > 90 ? 'over-90%' : utilNext > 75 ? 'tight' : 'healthy'}/>
          <Metric icon="warning" label="Peak day · next 14"
            value={(function () {
              const peak = tsRows.filter(r => r.isFuture).reduce((m, r) => r.qty > m.qty ? r : m, { qty: 0, date: '—', dayType: '—' });
              return peak.date === '—' ? '—' : fmt.shortDate(peak.date);
            })()}
            sublabel={(function () {
              const peak = tsRows.filter(r => r.isFuture).reduce((m, r) => r.qty > m.qty ? r : m, { qty: 0, date: '—', dayType: '—' });
              return peak.dayType + ' · ' + fmt.int(peak.qty) + ' units';
            })()}/>
        </div>

        {/* Main chart: orders vs comparison */}
        <Card title="Daily orders" subtitle={range + ' window centered on today · ' + (metric === 'qty' ? 'units' : 'workload units')}
          actions={
            <Tabs value={compareMode} onChange={setCompareMode} dense tabs={[
              { id: 'lastSale', label: 'vs last sale period' },
              { id: 'lastYear', label: 'vs same period LY' },
              { id: 'none',     label: 'No compare' },
            ]}/>
          }>
          <ChartLegend items={[
            { color: '#0b43ea', label: metric === 'qty' ? 'Forecast / actual volume' : 'Workload unit (forecast)' },
            ...(compareMode === 'lastSale' ? [{ color: '#ff6467', label: 'Same period · last sale event', dashed: true }] : []),
            ...(compareMode === 'lastYear' ? [{ color: '#00af4e', label: 'Same period · last year',       dashed: true }] : []),
            { color: '#99a1af', label: 'Capacity ceiling', dashed: true },
          ]} style={{ marginBottom: 10 }}/>
          <LineChart
            data={comparable}
            height={260}
            xKey="label"
            lines={[
              ...(compareMode === 'lastYear' ? [{ key: 'lastYearQty', label: 'Same period LY',   color: '#00af4e', width: 1.5, dashed: true }] : []),
              ...(compareMode === 'lastSale' ? [{ key: 'lastSaleQty', label: 'Same period last sale', color: '#ff6467', width: 1.5, dashed: true }] : []),
              { key: 'capacity',     label: 'Capacity',   color: '#99a1af', width: 1,   dashed: true },
              { key: metric,         label: metric === 'qty' ? 'Volume' : 'Workload', color: '#0b43ea', width: 2.5 },
            ]}
          />
          <div style={{ display: 'flex', gap: 14, marginTop: 8, fontSize: 11, color: 'var(--bx-text-muted)', flexWrap: 'wrap' }}>
            <span><Icon name="info" size={10}/> Dotted vertical at today · dates ahead are forecast, behind are actuals.</span>
          </div>
        </Card>

        {/* Volume vs workload dual-axis */}
        <Card title="Volume vs workload unit" subtitle="Complexity-weighted demand on top of raw order count. Workload spikes precede headcount strain on Mega-sale days.">
          <ChartLegend items={[
            { color: '#0b43ea', label: 'Volume (orders)' },
            { color: '#ff6467', label: 'Workload unit (WLU)' },
            { color: '#ff6467', label: 'Mega-sale marker' },
          ]} style={{ marginBottom: 8 }}/>
          <DualAxisChart data={tsRows} height={260}
            barKey="qty" lineKey="wlu"
            barLabel="Volume" lineLabel="Workload"
            xKey="label"/>
        </Card>

        {/* Per-warehouse trend grid */}
        <Card title="Trend per warehouse" subtitle="30-day moving series · 7d vs prev 7d delta · utilization snapshot"
          padding={0}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: vw < 720 ? '1fr' : vw < 1100 ? 'repeat(2,1fr)' : 'repeat(' + Math.min(trends.length, 3) + ',1fr)',
            gap: 0,
          }}>
            {trends.map((t, i) => (
              <WarehouseTrendCell key={t.warehouseId} t={t} metric={metric}
                style={{
                  borderRight: (i + 1) % (vw < 720 ? 1 : vw < 1100 ? 2 : 3) === 0 ? 'none' : '1px solid var(--bx-border-muted)',
                  borderBottom: Math.floor(i / (vw < 720 ? 1 : vw < 1100 ? 2 : 3)) < Math.floor((trends.length - 1) / (vw < 720 ? 1 : vw < 1100 ? 2 : 3)) ? '1px solid var(--bx-border-muted)' : 'none',
                }}/>
            ))}
          </div>
        </Card>

        {/* Detail table */}
        <Card title="Daily detail" subtitle="Forecast and actuals by date — all warehouses in scope"
          padding={0}
          actions={!isMobile && <Button variant="ghost" size="sm" icon="excel">Export rows</Button>}>
          <Table dense stickyHeader
            columns={[
              { header: 'Date', mono: true, render: r => (
                <div>
                  <div style={{ fontWeight: 600, color: 'var(--bx-text-dark)' }}>{fmt.shortDate(r.date)}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--bx-text-muted)' }}>
                    {new Date(r.date).toLocaleDateString('en-US', { weekday: 'short' })}
                    {r.isFuture ? ' · forecast' : ''}
                  </div>
                </div>
              )},
              { header: 'Day type', priority: 2, render: r => <Badge kind={r.dayType === 'MEGA_SALE' ? 'CRITICAL' : r.dayType === 'MINI_SPIKE' ? 'WARNING' : r.dayType === 'PAYDAY' ? 'INFO' : 'INACTIVE'} size="sm">{r.dayType}</Badge> },
              { header: 'Volume',   mono: true, align: 'right', render: r => fmt.int(r.qty) },
              { header: 'Workload', mono: true, align: 'right', render: r => <span style={{ color: 'var(--bx-text-body)' }}>{fmt.int(r.wlu)}</span> },
              { header: 'vs last sale', priority: 2, render: r => {
                const c = comparable.find(c => c.date === r.date);
                if (!c || !c.lastSaleQty) return <span style={{ color: 'var(--bx-text-muted)' }}>—</span>;
                const d = r.qty - c.lastSaleQty;
                const pct = (d / c.lastSaleQty) * 100;
                return <span style={{ fontFamily: 'var(--bx-font-mono)', fontVariantNumeric: 'tabular-nums', fontWeight: 600,
                  color: d > 0 ? 'var(--bx-success)' : d < 0 ? 'var(--bx-error)' : 'var(--bx-text-muted)' }}>
                  {d > 0 ? '+' : ''}{pct.toFixed(0)}%
                </span>;
              }},
              { header: 'vs LY',       priority: 3, render: r => {
                const c = comparable.find(c => c.date === r.date);
                if (!c || !c.lastYearQty) return <span style={{ color: 'var(--bx-text-muted)' }}>—</span>;
                const d = r.qty - c.lastYearQty;
                const pct = (d / c.lastYearQty) * 100;
                return <span style={{ fontFamily: 'var(--bx-font-mono)', fontVariantNumeric: 'tabular-nums', fontWeight: 600,
                  color: d > 0 ? 'var(--bx-success)' : 'var(--bx-error)' }}>
                  {d > 0 ? '+' : ''}{pct.toFixed(0)}%
                </span>;
              }},
              { header: 'Util',        priority: 2, render: r => {
                const u = (r.wlu / r.capacity) * 100;
                return (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 120 }}>
                    <div style={{ flex: 1, height: 6, background: 'var(--bx-surface-2)', borderRadius: 6, overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: Math.min(100, u) + '%',
                        background: u > 95 ? 'var(--bx-error)' : u > 80 ? 'var(--bx-warning)' : 'var(--bx-primary)' }}/>
                    </div>
                    <span style={{ fontFamily: 'var(--bx-font-mono)', fontVariantNumeric: 'tabular-nums', fontSize: 11.5, color: 'var(--bx-text-muted)' }}>{u.toFixed(0)}%</span>
                  </div>
                );
              }},
            ]}
            rows={tsRows} getRowKey={r => r.date}/>
        </Card>
      </div>
    </div>
  );
}

function WarehouseTrendCell({ t, metric, style }) {
  const change = metric === 'qty' ? t.change7dPct : t.change7dPct;
  const series = metric === 'qty' ? t.series : t.wluSeries;
  const max = Math.max(...series), min = Math.min(...series);
  const range = max - min || 1;
  return (
    <div style={{ padding: 14, ...style }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
        <span style={{ width: 9, height: 9, borderRadius: 2, background: t.color }}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, color: 'var(--bx-text-dark)', fontSize: 13, fontFamily: 'var(--bx-font-mono)' }}>{t.warehouseCode}</div>
          <div style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>{t.warehouseName}</div>
        </div>
        <Badge kind={change > 0 ? 'APPROVED' : 'CRITICAL'} size="sm">
          {change > 0 ? '+' : ''}{change.toFixed(0)}%
        </Badge>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 8 }}>
        <span style={{ fontFamily: 'var(--bx-font-mono)', fontSize: 18, fontWeight: 600, color: 'var(--bx-text-heading)' }}>{fmt.int(t.dailyAvg)}</span>
        <span style={{ fontSize: 11, color: 'var(--bx-text-muted)' }}>avg / day</span>
      </div>
      {/* tiny inline bars sparkline */}
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 1, height: 32, marginTop: 8 }}>
        {series.map((v, i) => {
          const h = ((v - min) / range) * 28 + 3;
          return <div key={i} style={{ flex: 1, height: h, background: i >= series.length - 7 ? t.color : 'color-mix(in oklab, ' + t.color + ' 32%, #ffffff)', borderRadius: 1 }}/>;
        })}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--bx-text-muted)', marginTop: 4, fontFamily: 'var(--bx-font-mono)' }}>
        <span>30d ago</span>
        <span>util {(t.utilization7d * 100).toFixed(0)}%</span>
        <span>today</span>
      </div>
    </div>
  );
}

Object.assign(window, { ForecastOverviewScreen });
