// Reports screen
const { useState: rpState, useMemo: rpMemo } = React;

function Reports({ t, lang }) {
  const { state } = useStore();
  const [report, setReport] = rpState('movement');
  const toast = useToast();

  const reports = [
    { key: 'movement', label: t.rep_movement, icon: Icon.Move },
    { key: 'valuation', label: t.rep_valuation, icon: Icon.Chart },
    { key: 'slow', label: t.rep_slow, icon: Icon.Clock },
    { key: 'abc', label: t.rep_abc, icon: Icon.Layers }
  ];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>{t.rep_title}</h1>
          <div className="page-sub">{lang === 'th' ? 'รายงานสรุปและการวิเคราะห์สต๊อก' : 'Summary reports and stock analysis'}</div>
        </div>
        <div className="page-head-actions">
          <button className="btn" onClick={() => toast(lang === 'th' ? 'ส่งออกแล้ว' : 'Exported')}><Icon.Download className="icon icon-sm" /> {t.rep_export}</button>
          <button className="btn" onClick={() => window.print()}><Icon.Print className="icon icon-sm" /> {t.rep_print}</button>
        </div>
      </div>

      <div className="grid grid-4" style={{ marginBottom: 20 }}>
        {reports.map(r => (
          <button
            key={r.key}
            onClick={() => setReport(r.key)}
            className="card"
            style={{ padding: 18, cursor: 'pointer', textAlign: 'left', border: report === r.key ? '2px solid var(--accent)' : '1px solid var(--border)' }}
          >
            <div style={{ width: 36, height: 36, borderRadius: 10, background: report === r.key ? 'var(--accent)' : 'var(--accent-soft)', color: report === r.key ? 'var(--accent-ink)' : 'var(--accent)', display: 'grid', placeItems: 'center', marginBottom: 10 }}>
              <r.icon className="icon icon-sm" />
            </div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{r.label}</div>
          </button>
        ))}
      </div>

      {report === 'movement' && <MovementReport t={t} lang={lang} state={state} />}
      {report === 'valuation' && <ValuationReport t={t} lang={lang} state={state} />}
      {report === 'slow' && <SlowReport t={t} lang={lang} state={state} />}
      {report === 'abc' && <ABCReport t={t} lang={lang} state={state} />}
    </div>
  );
}

function MovementReport({ t, lang, state }) {
  const summary = rpMemo(() => {
    const map = {};
    for (const m of state.movements) {
      const d = m.date;
      if (!map[d]) map[d] = { in: 0, out: 0, adjust: 0 };
      map[d][m.type] += m.qty || 0;
    }
    return Object.entries(map).sort((a,b) => a[0].localeCompare(b[0]));
  }, [state.movements]);

  const totalIn = summary.reduce((s,x) => s + x[1].in, 0);
  const totalOut = summary.reduce((s,x) => s + x[1].out, 0);
  const totalAdj = summary.reduce((s,x) => s + x[1].adjust, 0);
  const max = Math.max(...summary.flatMap(([,v]) => [v.in, v.out]), 1);

  return (
    <div className="grid grid-3" style={{ marginBottom: 16 }}>
      <KpiTile label={t.move_type_in} value={fmtThousands(totalIn)} tone="ok" icon={<Icon.Receive className="icon icon-sm" />} />
      <KpiTile label={t.move_type_out} value={fmtThousands(totalOut)} tone="info" icon={<Icon.Issue className="icon icon-sm" />} />
      <KpiTile label={t.move_type_adjust} value={fmtThousands(totalAdj)} tone="warn" icon={<Icon.Adjust className="icon icon-sm" />} />
      <div className="card" style={{ gridColumn: 'span 3' }}>
        <div className="card-header"><h2>{lang === 'th' ? 'ปริมาณการเคลื่อนไหวรายวัน' : 'Daily movement volume'}</h2></div>
        <div className="card-body">
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: 200, padding: '0 6px' }}>
            {summary.slice(-30).map(([d, v]) => (
              <div key={d} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }} title={`${d}: in ${v.in}, out ${v.out}`}>
                <div style={{ display: 'flex', flexDirection: 'column-reverse', gap: 2, width: '100%', alignItems: 'center' }}>
                  <div style={{ width: '60%', height: Math.max(1, v.in/max*150), background: 'var(--ok)', borderRadius: '3px 3px 0 0' }}></div>
                  <div style={{ width: '60%', height: Math.max(1, v.out/max*150), background: 'var(--info)', opacity: 0.7, borderRadius: '3px 3px 0 0' }}></div>
                </div>
                <div style={{ fontSize: 10, color: 'var(--ink-3)', writingMode: 'horizontal-tb' }}>{d.slice(-5)}</div>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 16, marginTop: 12, justifyContent: 'center' }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12 }}><span style={{ width: 10, height: 10, background: 'var(--ok)', borderRadius: 2 }}></span> {t.move_type_in}</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12 }}><span style={{ width: 10, height: 10, background: 'var(--info)', borderRadius: 2 }}></span> {t.move_type_out}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function ValuationReport({ t, lang, state }) {
  const byCategory = rpMemo(() => {
    const map = {};
    for (const p of state.products) {
      const c = p.category;
      if (!map[c]) map[c] = { count: 0, value: 0, qty: 0 };
      map[c].count++;
      map[c].value += p.onHand * p.unitCost;
      map[c].qty += p.onHand;
    }
    return Object.entries(map).sort((a,b) => b[1].value - a[1].value);
  }, [state.products]);
  const totalValue = byCategory.reduce((s,x) => s + x[1].value, 0);
  const totalItems = byCategory.reduce((s,x) => s + x[1].count, 0);
  const colors = ['var(--accent)','var(--ok)','var(--warn)','var(--bad)','var(--info)','var(--purple)','var(--ink-3)'];

  const slices = byCategory.map(([cat, v], i) => ({
    label: catLabel(cat, t),
    value: v.value,
    count: v.count,
    color: colors[i % colors.length]
  }));

  const [hovered, setHovered] = rpState(null);
  const activeSlice = hovered != null ? slices[hovered] : null;
  const centerLabel = activeSlice
    ? { primary: fmtCurrency(activeSlice.value/1000) + 'k', secondary: activeSlice.label }
    : { primary: fmtCurrency(totalValue/1000) + 'k', secondary: lang === 'th' ? 'มูลค่ารวม' : 'Total value' };

  return (
    <div className="grid grid-2" style={{ marginBottom: 16 }}>
      <div className="card">
        <div className="card-header"><h2>{lang === 'th' ? 'มูลค่าตามหมวด' : 'Value by category'}</h2></div>
        <div className="card-body">
          <div style={{ display: 'flex', gap: 24, alignItems: 'center', marginBottom: 18 }}>
            <PieChart slices={slices} hovered={hovered} setHovered={setHovered} centerLabel={centerLabel} unit="THB" />
            <div style={{ flex: 1, display: 'grid', gap: 6 }}>
              {slices.map((s, i) => {
                const pct = s.value / totalValue * 100;
                const dim = hovered != null && hovered !== i;
                return (
                  <div
                    key={s.label}
                    onMouseEnter={() => setHovered(i)}
                    onMouseLeave={() => setHovered(null)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      padding: '8px 10px', borderRadius: 8,
                      background: hovered === i ? 'var(--surface-2)' : 'transparent',
                      opacity: dim ? 0.45 : 1, cursor: 'pointer',
                      transition: 'opacity .15s, background .15s'
                    }}
                  >
                    <span style={{ width: 12, height: 12, borderRadius: 3, background: s.color, flex: '0 0 12px' }}></span>
                    <span style={{ flex: 1, fontWeight: 600, fontSize: 13.5 }}>{s.label}</span>
                    <span className="t-muted num" style={{ fontSize: 11.5, minWidth: 50, textAlign: 'right' }}>{s.count} {t.items}</span>
                    <span className="num" style={{ fontWeight: 700, fontSize: 13.5, minWidth: 60, textAlign: 'right' }}>{pct.toFixed(1)}%</span>
                  </div>
                );
              })}
            </div>
          </div>
          <div style={{ display: 'flex', padding: '14px 4px 0', borderTop: '1px solid var(--border)', fontWeight: 700, fontSize: 14 }}>
            <span style={{ flex: 1 }}>{lang === 'th' ? `รวม ${totalItems} รายการ` : `${totalItems} items total`}</span>
            <span className="num">{fmtCurrency(totalValue)} THB</span>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-header"><h2>{lang === 'th' ? '10 อันดับสินค้ามูลค่าสูง' : 'Top 10 by value'}</h2></div>
        <div className="card-body" style={{ padding: 0 }}>
          {[...state.products].sort((a,b) => (b.onHand*b.unitCost) - (a.onHand*a.unitCost)).slice(0, 10).map((p, i) => (
            <div key={p.sku} className="movement-row">
              <div style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--accent-soft)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12 }}>{i+1}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 13.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{(lang === 'th' ? p.nameTh : p.nameEn) || p.nameEn || p.sku}</div>
                <div className="t-muted mono" style={{ fontSize: 11 }}>{p.sku} · {p.onHand} {p.unit}</div>
              </div>
              <div className="num t-strong">{fmtCurrency(p.onHand * p.unitCost)}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function SlowReport({ t, lang, state }) {
  const slow = rpMemo(() => state.products
    .filter(p => p.category !== 'service' && p.onHand > 0)
    .sort((a,b) => b.daysSinceSold - a.daysSinceSold)
    .slice(0, 40), [state.products]);
  const totalDeadVal = slow.filter(p => p.status === 'dead').reduce((s,p) => s + p.onHand * p.unitCost, 0);

  return (
    <div className="grid" style={{ gap: 16 }}>
      <div className="grid grid-3">
        <KpiTile label={lang === 'th' ? 'สินค้านิ่ง' : 'Dead SKUs'} value={fmtThousands(slow.filter(p => p.status === 'dead').length)} tone="gray" icon={<Icon.Clock className="icon icon-sm" />} />
        <KpiTile label={lang === 'th' ? 'มูลค่ารวมสินค้านิ่ง' : 'Dead stock value'} value={fmtCurrency(totalDeadVal/1000) + 'k'} tone="bad" icon={<Icon.Warning className="icon icon-sm" />} />
        <KpiTile label={lang === 'th' ? 'ค่าเฉลี่ยวันค้าง' : 'Avg days idle'} value={Math.round(slow.reduce((s,p) => s+p.daysSinceSold,0)/Math.max(slow.length,1))} tone="warn" icon={<Icon.Clock className="icon icon-sm" />} />
      </div>
      <div className="card" style={{ overflow: 'hidden' }}>
        <table className="tbl">
          <thead><tr>
            <th>{t.col_sku}</th>
            <th>{t.col_name}</th>
            <th className="num">{t.col_onhand}</th>
            <th className="num">{t.col_value}</th>
            <th className="num">{t.col_lastsold}</th>
            <th>{t.col_status}</th>
          </tr></thead>
          <tbody>
            {slow.map(p => (
              <tr key={p.sku}>
                <td className="mono">{p.sku}</td>
                <td>{(lang === 'th' ? p.nameTh : p.nameEn) || p.nameEn}</td>
                <td className="num">{p.onHand}</td>
                <td className="num">{fmtCurrency(p.onHand * p.unitCost)}</td>
                <td className="num t-muted">{p.daysSinceSold} {t.days_ago}</td>
                <td><StatusPill status={p.status} t={t} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ABCReport({ t, lang, state }) {
  const byClass = rpMemo(() => {
    const out = { A: [], B: [], C: [] };
    for (const p of state.products) out[p.abc].push(p);
    return out;
  }, [state.products]);

  return (
    <div className="grid grid-3">
      {['A','B','C'].map(k => {
        const items = byClass[k];
        const revenue = items.reduce((s,p) => s+p.monthlyRevenue,0);
        const value = items.reduce((s,p) => s+p.onHand*p.unitCost,0);
        const desc = k === 'A' ? (lang === 'th' ? 'มีผลต่อยอดขาย 70%' : 'Drives 70% of revenue') : (k === 'B' ? (lang === 'th' ? 'ยอดขาย 20%' : '20% of revenue') : (lang === 'th' ? 'ยอดขาย 10%' : '10% of revenue'));
        return (
          <div key={k} className="card">
            <div className="card-body">
              <div className="row" style={{ marginBottom: 12 }}>
                <ABCBadge abc={k} />
                <h2 style={{ margin: 0, fontSize: 18 }}>Class {k}</h2>
                <span className="spacer"></span>
                <span className="t-muted">{items.length} {t.items}</span>
              </div>
              <div className="t-muted" style={{ fontSize: 13, marginBottom: 14 }}>{desc}</div>
              <div className="hbar" style={{ marginBottom: 10 }}>
                <div className="bar"><span style={{ background: k === 'A' ? 'var(--accent)' : (k === 'B' ? 'var(--warn)' : 'var(--ink-4)') }}></span></div>
              </div>
              <div style={{ display: 'grid', gap: 8 }}>
                <InfoLine label={lang === 'th' ? 'ยอดขายเดือนนี้' : 'Revenue this month'} value={fmtCurrency(revenue/1000) + 'k ฿'} />
                <InfoLine label={lang === 'th' ? 'มูลค่าสต๊อก' : 'Stock value'} value={fmtCurrency(value/1000) + 'k ฿'} />
              </div>
              <div className="divider"></div>
              <div className="h-section">{lang === 'th' ? 'ตัวอย่าง' : 'Examples'}</div>
              {[...items].sort((a,b) => b.monthlyRevenue - a.monthlyRevenue).slice(0, 5).map(p => (
                <div key={p.sku} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0' }}>
                  <span className="mono t-muted" style={{ fontSize: 11, minWidth: 90 }}>{p.sku}</span>
                  <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: 12.5 }}>{(lang === 'th' ? p.nameTh : p.nameEn) || p.nameEn}</span>
                </div>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function KpiTile({ label, value, tone, icon }) {
  const bg = { ok: 'var(--ok-soft)', info: 'var(--info-soft)', warn: 'var(--warn-soft)', bad: 'var(--bad-soft)', gray: 'var(--gray-soft)' }[tone] || 'var(--accent-soft)';
  const fg = { ok: 'var(--ok)', info: 'var(--info)', warn: 'var(--warn)', bad: 'var(--bad)', gray: 'var(--ink-3)' }[tone] || 'var(--accent)';
  return (
    <div className="kpi">
      <div className="kpi-label">{label}</div>
      <div className="kpi-value">{value}</div>
      <div className="kpi-icon" style={{ background: bg, color: fg }}>{icon}</div>
    </div>
  );
}

function InfoLine({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
      <span className="t-muted">{label}</span>
      <span style={{ fontWeight: 600 }} className="num">{value}</span>
    </div>
  );
}

window.Reports = Reports;
