// restock-demo.jsx — interactive embed of the restock app.
// Renders a faithful but simplified mock of the real Flask app with tab navigation.

const { useState, useMemo } = React;

const tone = (t) => ({
  danger: { bg: 'var(--bg-danger)', fg: 'var(--fg-danger)' },
  warn:   { bg: 'var(--bg-warn)',   fg: 'var(--fg-warn)' },
  ok:     { bg: 'var(--bg-ok)',     fg: 'var(--fg-ok)' },
  info:   { bg: 'var(--bg-info)',   fg: 'var(--fg-info)' },
  neutral:{ bg: 'transparent',      fg: 'var(--ink-2)' },
}[t] || { bg: 'transparent', fg: 'var(--ink-2)' });

function StatusPill({ kind, children }) {
  const t = tone(kind === 'warning' ? 'warn' : kind);
  return (
    <span style={{
      background: t.bg, color: t.fg,
      padding: '3px 9px', borderRadius: 999, fontSize: 11.5, fontWeight: 500,
      fontFamily: "'JetBrains Mono', ui-monospace, monospace",
      letterSpacing: '.02em', whiteSpace: 'nowrap',
    }}>{children}</span>
  );
}

function MiniKPI({ k }) {
  const t = tone(k.tone === 'warning' ? 'warn' : k.tone);
  const accent = k.tone === 'danger' ? 'var(--fg-danger)'
    : k.tone === 'warning' ? 'var(--fg-warn)'
    : 'var(--ink-1)';
  return (
    <div style={{
      background: 'var(--card)',
      borderTop: `2px solid ${k.tone === 'danger' ? 'var(--fg-danger)' : k.tone === 'warning' ? 'var(--fg-warn)' : 'var(--accent)'}`,
      borderLeft: '1px solid var(--rule)',
      borderRight: '1px solid var(--rule)',
      borderBottom: '1px solid var(--rule)',
      borderRadius: 4, padding: '14px 16px', minWidth: 0,
    }}>
      <div style={{ fontSize: 11, color: 'var(--ink-2)', letterSpacing: '.02em', marginBottom: 6,
                    fontFamily: "'JetBrains Mono', monospace", textTransform: 'uppercase' }}>{k.label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span style={{ fontSize: 30, fontWeight: 600, color: accent, lineHeight: 1,
                       fontVariantNumeric: 'tabular-nums', fontFamily: 'var(--font-display)' }}>{k.value}</span>
        {k.unit && <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>{k.unit}</span>}
      </div>
    </div>
  );
}

// Sales/forecast bar+line chart, inline SVG.
function ForecastChart({ legend }) {
  const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  // historical (past 6) and forecast (next 6) - simulated seasonal curve
  const data = [620, 580, 640, 720, 810, 920, 1020, 1180, 1320, 1240, 980, 820];
  const isHistorical = (i) => i < 6;
  const W = 720, H = 220, pad = { l: 36, r: 12, t: 16, b: 28 };
  const max = 1400;
  const barW = (W - pad.l - pad.r) / months.length;
  const yScale = (v) => H - pad.b - (v / max) * (H - pad.t - pad.b);
  const xCenter = (i) => pad.l + barW * (i + 0.5);

  // smooth line over the forecast
  const linePts = data.map((v, i) => ({ x: xCenter(i), y: yScale(v), i }));

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto' }}>
      {/* horizontal grid */}
      {[0, 350, 700, 1050, 1400].map((g) => (
        <g key={g}>
          <line x1={pad.l} x2={W - pad.r} y1={yScale(g)} y2={yScale(g)}
                stroke="var(--rule)" strokeWidth="0.5" />
          <text x={pad.l - 6} y={yScale(g) + 3} fontSize="9" textAnchor="end"
                fill="var(--ink-2)" fontFamily="JetBrains Mono">{g}</text>
        </g>
      ))}
      {/* bars - historical solid, forecast hatched */}
      <defs>
        <pattern id="hatch" patternUnits="userSpaceOnUse" width="4" height="4" patternTransform="rotate(45)">
          <line x1="0" y1="0" x2="0" y2="4" stroke="var(--accent)" strokeWidth="1.2" opacity="0.5" />
        </pattern>
      </defs>
      {data.map((v, i) => {
        const h = (H - pad.b) - yScale(v);
        return (
          <rect key={i}
                x={xCenter(i) - barW * 0.35} y={yScale(v)}
                width={barW * 0.7} height={h}
                fill={isHistorical(i) ? 'var(--ink-1)' : 'url(#hatch)'}
                stroke={isHistorical(i) ? 'none' : 'var(--accent)'}
                strokeWidth="0.8"
                opacity={isHistorical(i) ? 0.85 : 1}
          />
        );
      })}
      {/* dashed AI forecast line over forecast bars */}
      <polyline
        points={linePts.slice(5).map(p => `${p.x},${p.y}`).join(' ')}
        fill="none" stroke="var(--accent)" strokeWidth="1.5"
        strokeDasharray="4 3" />
      {linePts.slice(5).map((p, i) => (
        <circle key={i} cx={p.x} cy={p.y} r={2.5} fill="var(--accent)" />
      ))}
      {/* x-axis labels */}
      {months.map((m, i) => (
        <text key={m} x={xCenter(i)} y={H - 10} fontSize="9.5"
              textAnchor="middle" fill="var(--ink-2)"
              fontFamily="JetBrains Mono">{m}</text>
      ))}
      {/* divider between historical and forecast */}
      <line x1={pad.l + barW * 6} x2={pad.l + barW * 6}
            y1={pad.t} y2={H - pad.b}
            stroke="var(--ink-2)" strokeWidth="0.5" strokeDasharray="2 3" opacity="0.5" />
      <text x={pad.l + barW * 6 + 4} y={pad.t + 10} fontSize="9"
            fill="var(--ink-2)" fontFamily="JetBrains Mono">NOW</text>
    </svg>
  );
}

function DashboardTab({ d }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(130px, 1fr))', gap: 10 }}>
        {d.kpi.map((k, i) => <MiniKPI key={i} k={k} />)}
      </div>
      {/* Chart */}
      <div style={{
        background: 'var(--card)', border: '1px solid var(--rule)', borderRadius: 4, padding: 18,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                      marginBottom: 10, flexWrap: 'wrap', gap: 8 }}>
          <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-1)' }}>{d.chartTitle}</div>
          <div style={{ display: 'flex', gap: 14, fontSize: 11, color: 'var(--ink-2)',
                        fontFamily: "'JetBrains Mono', monospace" }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 10, height: 10, background: 'var(--ink-1)' }}></span>
              {d.chartLegend[0]}
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 10, height: 10, background: 'var(--accent)', opacity: .5 }}></span>
              {d.chartLegend[1]}
            </span>
          </div>
        </div>
        <ForecastChart legend={d.chartLegend} />
      </div>
    </div>
  );
}

function RestockTab({ d }) {
  return (
    <div style={{ background: 'var(--card)', border: '1px solid var(--rule)', borderRadius: 4,
                  overflow: 'hidden' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
        <thead>
          <tr style={{ background: 'var(--ink-1)', color: 'var(--card)' }}>
            {d.tableHeaders.map((h, i) => (
              <th key={i} style={{
                padding: '11px 14px', textAlign: i >= 2 && i <= 5 ? 'right' : 'left',
                fontWeight: 500, fontSize: 11.5, letterSpacing: '.02em',
                fontFamily: "'JetBrains Mono', monospace", textTransform: 'uppercase',
              }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {d.tableRows.map((r, i) => {
            const [style, cs, sales, stock, transit, qty, statusKind, statusText] = r;
            const tdStyle = { padding: '12px 14px', borderTop: '1px solid var(--rule)',
                              fontVariantNumeric: 'tabular-nums' };
            return (
              <tr key={i}>
                <td style={{ ...tdStyle, fontWeight: 500, fontFamily: "'JetBrains Mono', monospace" }}>{style}</td>
                <td style={{ ...tdStyle, color: 'var(--ink-2)' }}>{cs}</td>
                <td style={{ ...tdStyle, textAlign: 'right' }}>{sales}</td>
                <td style={{ ...tdStyle, textAlign: 'right' }}>{stock}</td>
                <td style={{ ...tdStyle, textAlign: 'right', color: 'var(--ink-2)' }}>{transit || '—'}</td>
                <td style={{ ...tdStyle, textAlign: 'right', fontWeight: 600,
                              color: qty ? 'var(--fg-danger)' : 'var(--ink-2)' }}>
                  {qty || '—'}
                </td>
                <td style={tdStyle}>
                  <StatusPill kind={statusKind}>{statusText}</StatusPill>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <div style={{ padding: '10px 14px', borderTop: '1px solid var(--rule)',
                    fontSize: 11, color: 'var(--ink-2)',
                    fontFamily: "'JetBrains Mono', monospace",
                    display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
        <span>显示 6 / 247 SKU · 实时计算 · 工厂确认 3d + 生产 26d + 海运 32d + 入仓 7d</span>
        <span style={{ color: 'var(--accent)' }}>→ 导出 XLSX</span>
      </div>
    </div>
  );
}

function StockoutTab({ d }) {
  return (
    <div style={{ background: 'var(--card)', border: '1px solid var(--rule)', borderRadius: 4,
                  padding: 20 }}>
      <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 4 }}>{d.stockoutTitle}</div>
      <div style={{ fontSize: 12, color: 'var(--ink-2)', marginBottom: 18 }}>{d.stockoutNote}</div>

      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {d.stockoutRows.map((r, i) => {
          const [sku, eta, kind, note] = r;
          return (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '1.2fr 0.7fr 1.6fr', gap: 16,
              padding: '14px 0', borderTop: i ? '1px solid var(--rule)' : 'none',
              alignItems: 'center',
            }}>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 13, fontWeight: 500 }}>
                {sku}
              </div>
              <div>
                <StatusPill kind={kind}>{eta}</StatusPill>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>{note}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ForecastTab({ d }) {
  return (
    <div style={{ background: 'var(--card)', border: '1px solid var(--rule)', borderRadius: 4, padding: 20 }}>
      <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 6 }}>{d.chartTitle}</div>
      <div style={{ fontSize: 12, color: 'var(--ink-2)', marginBottom: 18 }}>{d.forecastNote}</div>
      <ForecastChart legend={d.chartLegend} />
      <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
        {[
          ['Q1 预测', '2,180', '件 / 月均', 'info'],
          ['Q2 预测', '2,940', '+35% 旺季', 'warn'],
          ['Q3 预测', '3,810', '+30% 旺季', 'danger'],
        ].map((c, i) => (
          <div key={i} style={{ border: '1px solid var(--rule)', borderRadius: 4, padding: '12px 14px' }}>
            <div style={{ fontSize: 11, color: 'var(--ink-2)', fontFamily: "'JetBrains Mono', monospace",
                          textTransform: 'uppercase', marginBottom: 4 }}>{c[0]}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <span style={{ fontSize: 24, fontWeight: 600, fontFamily: 'var(--font-display)' }}>{c[1]}</span>
              <span style={{ fontSize: 11, color: 'var(--ink-2)' }}>{c[2]}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function RestockDemo({ lang }) {
  const d = (window.I18N || I18N)[lang].demo;
  const [tab, setTab] = useState(0);

  return (
    <div style={{
      background: 'var(--app-bg)', border: '1px solid var(--rule-strong)',
      borderRadius: 8, overflow: 'hidden',
      boxShadow: '0 1px 0 rgba(0,0,0,.04), 0 24px 60px -20px rgba(40,28,16,.15), 0 8px 24px -12px rgba(40,28,16,.08)',
    }}>
      {/* Window chrome */}
      <div style={{
        background: 'var(--chrome)', borderBottom: '1px solid var(--rule-strong)',
        padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{ display: 'flex', gap: 6 }}>
          {['#FF5F57', '#FEBC2E', '#28C840'].map((c) => (
            <span key={c} style={{ width: 11, height: 11, borderRadius: '50%', background: c, opacity: 0.85 }}></span>
          ))}
        </div>
        <div style={{
          flex: 1, textAlign: 'center', fontSize: 11.5,
          color: 'var(--ink-2)', fontFamily: "'JetBrains Mono', monospace",
        }}>
          localhost:5050 — 亚马逊补货系统 / restock.app
        </div>
        <span style={{ width: 11, height: 11 }}></span>
      </div>

      {/* Tabs */}
      <div style={{
        display: 'flex', background: 'var(--chrome)',
        borderBottom: '1px solid var(--rule)', padding: '0 14px',
        overflowX: 'auto',
      }}>
        {d.tabs.map((label, i) => (
          <button key={i} onClick={() => setTab(i)}
            style={{
              background: 'transparent', border: 'none',
              padding: '12px 16px', fontSize: 13,
              color: tab === i ? 'var(--ink-1)' : 'var(--ink-2)',
              fontWeight: tab === i ? 600 : 400,
              borderBottom: tab === i ? '2px solid var(--accent)' : '2px solid transparent',
              marginBottom: -1, cursor: 'pointer', whiteSpace: 'nowrap',
            }}>
            {label}
          </button>
        ))}
      </div>

      {/* Body */}
      <div style={{ padding: 20 }}>
        {tab === 0 && <DashboardTab d={d} />}
        {tab === 1 && <RestockTab d={d} />}
        {tab === 2 && <StockoutTab d={d} />}
        {tab === 3 && <ForecastTab d={d} />}
      </div>
    </div>
  );
}

Object.assign(window, { RestockDemo });
