// ============ POS Analytics (4B) ============
// วิเคราะห์ช่องทางขาย · ยอดรายวัน · Average Basket · Peak Days

function POSAnalyticsPage({ go }) {
  const { fdb: db, settings } = useData();
  const [period, setPeriod] = React.useState('3m'); // '1m' '3m' '6m' 'all'

  const allMonths = React.useMemo(() => aggregateByMonth(db), [db]);

  const filteredMonths = React.useMemo(() => {
    const n = period === '1m' ? 1 : period === '3m' ? 3 : period === '6m' ? 6 : allMonths.length;
    return allMonths.slice(-n);
  }, [allMonths, period]);

  const filteredDays = React.useMemo(() => {
    if (!filteredMonths.length) return [];
    const from = filteredMonths[0].key;
    return (db.dailySales || []).filter(d => d.date?.slice(0, 7) >= from);
  }, [db.dailySales, filteredMonths]);

  // ---- Channel Mix ----
  const channelTotals = React.useMemo(() => {
    return filteredMonths.reduce((acc, m) => ({
      store: acc.store + (m.store || 0),
      line: acc.line + (m.line || 0),
      other: acc.other + (m.other || 0),
      total: acc.total + m.total,
    }), { store: 0, line: 0, other: 0, total: 0 });
  }, [filteredMonths]);

  // ---- Monthly Revenue by Channel ----
  const channelSeries = React.useMemo(() => filteredMonths.map(m => ({
    label: THAI_MONTHS_SHORT[m.monthIdx] || m.key.slice(5),
    store: m.store || 0,
    line: m.line || 0,
    other: m.other || 0,
    total: m.total,
  })), [filteredMonths]);

  // ---- Average Basket ----
  const basketData = React.useMemo(() => {
    return filteredMonths.map(m => {
      const days = (db.dailySales || []).filter(d => d.date?.slice(0, 7) === m.key);
      const bills = days.reduce((s, d) => s + (d.bills || 0), 0);
      return { label: THAI_MONTHS_SHORT[m.monthIdx] || m.key.slice(5), basket: bills > 0 ? m.total / bills : 0, bills };
    });
  }, [filteredMonths, db.dailySales]);

  // ---- Peak Day of Week ----
  const dowData = React.useMemo(() => {
    const DAYS = ['อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.'];
    const counts = Array(7).fill(0);
    const totals = Array(7).fill(0);
    filteredDays.forEach(d => {
      if (!d.date) return;
      const dow = new Date(d.date + 'T00:00:00Z').getUTCDay();
      counts[dow]++;
      totals[dow] += dailyTotal(d);
    });
    return DAYS.map((label, i) => ({ label, avg: counts[i] > 0 ? totals[i] / counts[i] : 0, count: counts[i] }));
  }, [filteredDays]);

  // ---- Growth Rate ----
  const growth = React.useMemo(() => {
    if (filteredMonths.length < 2) return null;
    const last = filteredMonths[filteredMonths.length - 1].total;
    const prev = filteredMonths[filteredMonths.length - 2].total;
    return prev > 0 ? (last - prev) / prev : null;
  }, [filteredMonths]);

  // ---- Revenue per Day of Month ----
  const dailySeries = React.useMemo(() => {
    const cur = filteredMonths[filteredMonths.length - 1];
    if (!cur) return [];
    return (db.dailySales || [])
      .filter(d => d.date?.slice(0, 7) === cur.key)
      .map(d => ({ x: d.date, y: dailyTotal(d) }))
      .sort((a, b) => a.x.localeCompare(b.x));
  }, [filteredMonths, db.dailySales]);

  if (!allMonths.length) {
    return <Empty icon="chart" title="ยังไม่มีข้อมูลยอดขาย"
      sub="บันทึกยอดขายก่อน แล้ว POS Analytics จะแสดงผลอัตโนมัติ"
      action={<Button icon="plus" onClick={() => go('sales')}>บันทึกยอดขาย</Button>} />;
  }

  const pct = v => v === null ? '–' : (v * 100).toFixed(1) + '%';
  const baht = v => '฿' + Math.round(v || 0).toLocaleString('th-TH');
  const maxDow = Math.max(...dowData.map(d => d.avg));

  return (
    <div style={{ maxWidth: 900, margin: '0 auto', paddingBottom: 80, display: 'flex', flexDirection: 'column', gap: 18 }}>

      {/* Period Selector */}
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Segmented value={period} onChange={setPeriod} options={[
          { value: '1m', label: '1 เดือน' },
          { value: '3m', label: '3 เดือน' },
          { value: '6m', label: '6 เดือน' },
          { value: 'all', label: 'ทั้งหมด' },
        ]} />
      </div>

      {/* KPI Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12 }}>
        {[
          { label: 'รายได้รวม', value: baht(channelTotals.total), color: 'var(--accent)' },
          { label: 'หน้าร้าน', value: pct(channelTotals.total ? channelTotals.store / channelTotals.total : 0), color: '#0071e3' },
          { label: 'LINE MAN', value: pct(channelTotals.total ? channelTotals.line / channelTotals.total : 0), color: '#30a46c' },
          { label: 'การเติบโต MoM', value: growth !== null ? (growth >= 0 ? '+' : '') + pct(growth) : '–', color: growth === null ? 'var(--ink-3)' : growth >= 0 ? 'var(--green)' : 'var(--red)' },
        ].map(c => (
          <div key={c.label} style={{ background: 'var(--surface)', borderRadius: 14, padding: '14px 12px', textAlign: 'center', boxShadow: 'var(--shadow)' }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: c.color }}>{c.value}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{c.label}</div>
          </div>
        ))}
      </div>

      {/* Revenue by Channel + Daily Trend */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Card>
          <SectionTitle sub="ยอดขายแยกช่องทางรายเดือน">ช่องทางการขาย</SectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {channelSeries.map((m, i) => (
              <div key={i}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 3 }}>
                  <span style={{ color: 'var(--ink-2)' }}>{m.label}</span>
                  <span style={{ fontWeight: 600 }}>{baht(m.total)}</span>
                </div>
                <div style={{ display: 'flex', height: 8, borderRadius: 4, overflow: 'hidden', background: 'var(--chip)' }}>
                  {m.total > 0 && <>
                    <div style={{ width: `${(m.store / m.total) * 100}%`, background: '#0071e3' }} />
                    <div style={{ width: `${(m.line / m.total) * 100}%`, background: '#30a46c' }} />
                    <div style={{ width: `${(m.other / m.total) * 100}%`, background: '#d97a16' }} />
                  </>}
                </div>
              </div>
            ))}
            <div style={{ display: 'flex', gap: 14, marginTop: 4 }}>
              {[{ color: '#0071e3', label: 'หน้าร้าน' }, { color: '#30a46c', label: 'LINE MAN' }, { color: '#d97a16', label: 'อื่นๆ' }].map(c => (
                <div key={c.label} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--ink-2)' }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: c.color, display: 'inline-block' }} />{c.label}
                </div>
              ))}
            </div>
          </div>
        </Card>

        <Card>
          <SectionTitle sub={`ยอดขายรายวัน — เดือนล่าสุด`}>แนวโน้มรายวัน</SectionTitle>
          {dailySeries.length > 0
            ? <LineChart data={dailySeries} height={180} color={settings.accent}
                xlabels={(i) => (i % 5 === 0 || i === dailySeries.length - 1) ? parseInt(dailySeries[i].x.slice(8)) : null} />
            : <div style={{ color: 'var(--ink-3)', fontSize: 13, textAlign: 'center', padding: 40 }}>ไม่มีข้อมูล</div>
          }
        </Card>
      </div>

      {/* Average Basket + Peak DOW */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Card>
          <SectionTitle sub="ยอดเฉลี่ยต่อบิลรายเดือน">Average Basket Size</SectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {basketData.filter(d => d.bills > 0).length === 0
              ? <div style={{ fontSize: 13, color: 'var(--ink-3)', textAlign: 'center', padding: 20 }}>ยังไม่ได้บันทึกจำนวนบิล</div>
              : basketData.map((m, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ fontSize: 13, color: 'var(--ink-2)', width: 36, flexShrink: 0 }}>{m.label}</span>
                  <div style={{ flex: 1, height: 8, borderRadius: 4, background: 'var(--chip)', overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${m.basket > 0 ? Math.min(100, (m.basket / 500) * 100) : 0}%`, background: 'var(--accent)', borderRadius: 4 }} />
                  </div>
                  <span style={{ fontSize: 13, fontWeight: 600, width: 70, textAlign: 'right' }}>{m.basket > 0 ? baht(m.basket) : '–'}</span>
                </div>
              ))
            }
          </div>
        </Card>

        <Card>
          <SectionTitle sub="ยอดขายเฉลี่ยแยกตามวันในสัปดาห์">วันขายดีสุด</SectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {dowData.map((d, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 13, color: 'var(--ink-2)', width: 30, flexShrink: 0 }}>{d.label}</span>
                <div style={{ flex: 1, height: 8, borderRadius: 4, background: 'var(--chip)', overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${maxDow > 0 ? (d.avg / maxDow) * 100 : 0}%`, background: d.avg === maxDow ? 'var(--green)' : 'var(--accent)', borderRadius: 4 }} />
                </div>
                <span style={{ fontSize: 12, color: 'var(--ink-2)', width: 70, textAlign: 'right' }}>{d.avg > 0 ? baht(d.avg) : '–'}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Monthly Summary Table */}
      <Card>
        <SectionTitle sub="สรุปรายเดือน">ตารางสรุป</SectionTitle>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: '2px solid var(--line-2)', color: 'var(--ink-3)', textAlign: 'right' }}>
                <th style={{ textAlign: 'left', padding: '8px 0', fontWeight: 600 }}>เดือน</th>
                <th style={{ padding: '8px 8px', fontWeight: 600 }}>รายได้รวม</th>
                <th style={{ padding: '8px 8px', fontWeight: 600 }}>หน้าร้าน</th>
                <th style={{ padding: '8px 8px', fontWeight: 600 }}>LINE MAN</th>
                <th style={{ padding: '8px 8px', fontWeight: 600 }}>วันบันทึก</th>
                <th style={{ padding: '8px 8px', fontWeight: 600 }}>เฉลี่ย/วัน</th>
                <th style={{ padding: '8px 8px', fontWeight: 600 }}>MoM</th>
              </tr>
            </thead>
            <tbody>
              {channelSeries.map((m, i) => {
                const prev = channelSeries[i - 1];
                const mom = prev && prev.total > 0 ? (m.total - prev.total) / prev.total : null;
                const monthData = filteredMonths[i];
                return (
                  <tr key={i} style={{ borderBottom: '1px solid var(--line-2)' }}>
                    <td style={{ padding: '9px 0', fontWeight: 500 }}>{m.label} {parseInt(filteredMonths[i]?.year || 0) + 543}</td>
                    <td style={{ padding: '9px 8px', textAlign: 'right', fontWeight: 600 }}>{baht(m.total)}</td>
                    <td style={{ padding: '9px 8px', textAlign: 'right', color: '#0071e3' }}>{baht(m.store)}</td>
                    <td style={{ padding: '9px 8px', textAlign: 'right', color: '#30a46c' }}>{baht(m.line)}</td>
                    <td style={{ padding: '9px 8px', textAlign: 'right', color: 'var(--ink-3)' }}>{monthData?.days || 0} วัน</td>
                    <td style={{ padding: '9px 8px', textAlign: 'right' }}>{monthData?.days ? baht(m.total / monthData.days) : '–'}</td>
                    <td style={{ padding: '9px 8px', textAlign: 'right', color: mom === null ? 'var(--ink-3)' : mom >= 0 ? 'var(--green)' : 'var(--red)', fontWeight: 600 }}>
                      {mom === null ? '–' : (mom >= 0 ? '+' : '') + pct(mom)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { POSAnalyticsPage });
