// screens-draws.jsx — 彩票开奖管理
// 实时大盘、历史开奖、单期 drill-down、停期/重开/异常标记/强制开奖

const _DRAWS_API = window.NebulaAdmin.API_BASE();

function DrawsScreen({ t, push }) {
  const [lotteries, setLotteries] = React.useState([]);
  const [activeId, setActiveId] = React.useState('cqssc');
  const [data, setData] = React.useState(null);
  const [selected, setSelected] = React.useState(null);

  const fetchAll = React.useCallback(() => {
    fetch(`${_DRAWS_API}/api/draws`).then(r => r.json()).then(d => setLotteries(d.lotteries || []));
  }, []);
  const fetchOne = React.useCallback(() => {
    fetch(`${_DRAWS_API}/api/draws/${activeId}`).then(r => r.json()).then(d => {
      setData(d);
      if (!selected || selected.period !== (d?.history?.[0]?.period)) {
        setSelected(d?.history?.[0] || null);
      }
    });
  }, [activeId, selected]);
  React.useEffect(() => { fetchAll(); }, [fetchAll]);
  React.useEffect(() => { fetchOne(); }, [fetchOne]);
  // Poll current period every 4s
  React.useEffect(() => { const i = setInterval(fetchOne, 4000); return () => clearInterval(i); }, [fetchOne]);

  const adminFetch = async (url, opts = {}) => fetch(url, {
    ...opts,
    headers: { ...window.NebulaAdmin.authHeaders(), ...(opts.headers || {}) },
  });

  const doControl = async (action, note) => {
    const r = await adminFetch(`${_DRAWS_API}/api/draws/${activeId}/control`, {
      method: 'POST',
      body: JSON.stringify({ action, note: note || '' }),
    });
    if (!r.ok) { push(t.tx('操作失败：', 'Operation failed: ') + r.status + (r.status === 401 ? t.tx(' 未登录', ' Not logged in') : '')); return; }
    push({
      pause: t.tx('已暂停', 'Paused'),
      resume: t.tx('已恢复', 'Resumed'),
      reopen: t.tx('已重开', 'Reopened'),
      'flag-anomaly': t.tx('已标记异常', 'Flagged as anomaly'),
    }[action] || action);
    fetchOne();
  };
  const doForceDraw = async () => {
    if (!confirm(t.tx('强制立即开奖？此操作会立即结算当期所有投注且无法撤销。', 'Force draw now? This will immediately settle all bets in the current period and cannot be undone.'))) return;
    const r = await adminFetch(`${_DRAWS_API}/api/draws/${activeId}/force-draw`, { method: 'POST', body: JSON.stringify({}) });
    if (!r.ok) { push(t.tx('强制开奖失败：', 'Force draw failed: ') + r.status); return; }
    push(t.tx('已强制开奖', 'Force-drawn'));
    fetchOne();
  };

  if (!data) return <div className="stack"><div className="page-h"><h1>{t.tx('开奖管理', 'Draw Mgmt')}</h1><div className="sub">{t.tx('加载中…', 'Loading…')}</div></div></div>;
  const cur = data.current || {};
  const history = data.history || [];

  return (
    <div className="stack">
      <div className="page-h">
        <div>
          <h1>{t.tx('开奖管理', 'Draw Mgmt')}</h1>
          <div className="sub">{t.tx('实时大盘 · 历史回放 · 异常标记 · 手动控盘', 'Live board · History · Anomaly flagging · Manual control')}</div>
        </div>
        <div className="actions">
          <button className="btn btn-sm" onClick={() => fetchOne()}>{t.tx('刷新', 'Refresh')}</button>
          <button className="btn btn-sm" onClick={() => doControl(cur.status === 'paused' ? 'resume' : 'pause')}>
            {cur.status === 'paused' ? t.tx('恢复开奖', 'Resume') : t.tx('暂停当期', 'Pause current')}
          </button>
          <button className="btn btn-sm" onClick={() => doControl('flag-anomaly', t.tx('人工标记', 'Manual flag'))}>{t.tx('标记异常', 'Flag anomaly')}</button>
          <button className="btn btn-pri btn-sm" onClick={doForceDraw}>{t.tx('强制立即开奖', 'Force draw now')}</button>
        </div>
      </div>

      {/* Lottery tabs */}
      <div className="tabs">
        {lotteries.map(l => (
          <div key={l.lottery}
               className={'tab' + (activeId === l.lottery ? ' active' : '')}
               onClick={() => { setActiveId(l.lottery); setSelected(null); }}>
            {l.name} · {l.frequency}
          </div>
        ))}
      </div>

      {/* Current period hero */}
      <div className="card" style={{ padding: 16, background: 'linear-gradient(135deg, var(--accent-soft, rgba(99,102,241,.06)) 0%, var(--bg-card) 60%)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
          <div>
            <div className="text-muted" style={{ fontSize: 11, marginBottom: 2 }}>{t.tx('当前期号', 'Current period')} · {data.name}</div>
            <div className="text-mono" style={{ fontSize: 20, fontWeight: 700 }}>{cur.period}</div>
          </div>
          <div style={{ width: 1, height: 32, background: 'var(--border)' }} />
          <div>
            <div className="text-muted" style={{ fontSize: 11, marginBottom: 2 }}>{t.tx('状态', 'Status')}</div>
            <span className={'badge ' + (cur.status === 'live' ? 'accent' : cur.status === 'paused' ? 'warning' : cur.status === 'flagged' ? 'danger' : 'outline')}>
              {cur.status === 'live' ? t.tx('🟢 进行中', '🟢 Live') : cur.status === 'paused' ? t.tx('⏸ 已暂停', '⏸ Paused') : cur.status === 'flagged' ? t.tx('⚠️ 异常', '⚠️ Anomaly') : cur.status}
            </span>
          </div>
          <div style={{ width: 1, height: 32, background: 'var(--border)' }} />
          <div>
            <div className="text-muted" style={{ fontSize: 11, marginBottom: 2 }}>{t.tx('距封盘', 'Until close')}</div>
            <CountdownLabel seconds={cur.close_seconds} />
          </div>
          <div style={{ width: 1, height: 32, background: 'var(--border)' }} />
          <div>
            <div className="text-muted" style={{ fontSize: 11, marginBottom: 2 }}>{t.tx('本期投注', 'Stakes this period')}</div>
            <div className="tabular" style={{ fontSize: 18, fontWeight: 700 }}>¥{(cur.stake || 0).toLocaleString()}</div>
          </div>
          <div style={{ width: 1, height: 32, background: 'var(--border)' }} />
          <div>
            <div className="text-muted" style={{ fontSize: 11, marginBottom: 2 }}>{t.tx('预计派彩', 'Projected payout')}</div>
            <div className="tabular" style={{ fontSize: 18, fontWeight: 700, color: 'var(--warning)' }}>¥{(cur.projected_payout || 0).toLocaleString()}</div>
          </div>
          <div style={{ width: 1, height: 32, background: 'var(--border)' }} />
          <div>
            <div className="text-muted" style={{ fontSize: 11, marginBottom: 2 }}>{t.tx('预计净收', 'Projected net')}</div>
            <div className="tabular" style={{ fontSize: 18, fontWeight: 700, color: (cur.stake - cur.projected_payout) >= 0 ? 'var(--success)' : 'var(--danger)' }}>
              {(cur.stake - cur.projected_payout) >= 0 ? '+' : '-'}¥{Math.abs((cur.stake || 0) - (cur.projected_payout || 0)).toLocaleString()}
            </div>
          </div>
          <div style={{ width: 1, height: 32, background: 'var(--border)' }} />
          <div>
            <div className="text-muted" style={{ fontSize: 11, marginBottom: 2 }}>{t.tx('投注笔数', 'Bet count')}</div>
            <div className="tabular" style={{ fontSize: 18, fontWeight: 700 }}>{cur.bets_count || 0}</div>
          </div>
        </div>
      </div>

      {/* History + drill-down */}
      <div className="row-2 row-detail-split">
        <div className="card">
          <div className="card-h"><h3>{t.tx('历史开奖 · 近 ', 'History · last ')}{history.length}{t.tx(' 期', ' draws')}</h3><span className="meta">{t.tx('点行查看单期详情', 'Click row for details')}</span></div>
          <div className="tbl-scroll">
          <table className="tbl tbl-stack">
            <thead><tr><th>{t.tx('期号', 'Period')}</th><th>{t.tx('开奖号', 'Winning numbers')}</th><th>{t.tx('状态', 'Status')}</th><th className="right">{t.tx('投注', 'Stake')}</th><th className="right">{t.tx('派彩', 'Payout')}</th><th className="right">{t.tx('净收', 'Net')}</th><th>{t.tx('笔数', 'Bets')}</th><th>{t.tx('时间', 'Time')}</th></tr></thead>
            <tbody>
              {history.map(h => {
                const sel = selected && selected.period === h.period;
                const isProfit = (h.profit || 0) >= 0;
                return (
                  <tr key={h.period} onClick={() => setSelected(h)} style={{ background: sel ? 'var(--bg-inset)' : '', cursor: 'pointer' }}>
                    <td data-label={t.tx('期号','Period')} className="text-mono" style={{ fontSize: 11 }}>{String(h.period).slice(-6)}</td>
                    <td data-label={t.tx('开奖号','Numbers')}><DrawBalls numbers={h.numbers} /></td>
                    <td data-label={t.tx('状态','Status')}>
                      {h.status === 'flagged' && <span className="badge warning" style={{ fontSize: 10 }}>{t.tx('⚠ 已标记', '⚠ Flagged')}</span>}
                      {h.status === 'anomaly' && <span className="badge danger" style={{ fontSize: 10 }}>{t.tx('🚨 异常', '🚨 Anomaly')}</span>}
                      {h.status === 'normal' && <span className="text-faint" style={{ fontSize: 11 }}>{t.tx('正常', 'Normal')}</span>}
                    </td>
                    <td data-label={t.tx('投注','Stake')} className="right tabular">¥{h.stake?.toLocaleString()}</td>
                    <td data-label={t.tx('派彩','Payout')} className="right tabular">¥{h.payout?.toLocaleString()}</td>
                    <td data-label={t.tx('净收','Net')} className="right tabular" style={{ color: isProfit ? 'var(--success)' : 'var(--danger)' }}>
                      {isProfit ? '+' : '-'}¥{Math.abs(h.profit || 0).toLocaleString()}
                    </td>
                    <td data-label={t.tx('笔数','Bets')}>{h.bets_count}</td>
                    <td data-label={t.tx('时间','Time')} className="muted text-mono" style={{ fontSize: 10 }}>{new Date(h.time).toLocaleTimeString('zh-CN', { hour12: false })}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          </div>
        </div>

        <div className="card" style={{ position: 'sticky', top: 0 }}>
          <div className="card-h"><h3>{t.tx('单期详情', 'Period detail')}</h3><span className="meta">{selected ? '#' + selected.period : t.tx('未选', 'None')}</span></div>
          {!selected ? (
            <div style={{ padding: 18, fontSize: 11, color: 'var(--text-faint)' }}>{t.tx('点击左侧任意一行查看详情、派奖、风控信号', 'Click any row on the left for details, payout, and risk signals')}</div>
          ) : (
            <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div>
                <div className="text-muted" style={{ fontSize: 11, marginBottom: 4 }}>{t.tx('开奖号', 'Winning numbers')}</div>
                <DrawBalls numbers={selected.numbers} big />
              </div>

              <dl className="kv">
                <dt>{t.tx('期号', 'Period')}</dt><dd className="text-mono">{selected.period}</dd>
                <dt>{t.tx('开奖时间', 'Draw time')}</dt><dd className="text-mono" style={{ fontSize: 11 }}>{new Date(selected.time).toLocaleString('zh-CN')}</dd>
                <dt>{t.tx('投注总额', 'Total stake')}</dt><dd className="tabular">¥{(selected.stake || 0).toLocaleString()}</dd>
                <dt>{t.tx('派彩总额', 'Total payout')}</dt><dd className="tabular">¥{(selected.payout || 0).toLocaleString()}</dd>
                <dt>{t.tx('净收益', 'Net profit')}</dt><dd className="tabular" style={{ color: (selected.profit || 0) >= 0 ? 'var(--success)' : 'var(--danger)', fontWeight: 700 }}>
                  {(selected.profit || 0) >= 0 ? '+' : '-'}¥{Math.abs(selected.profit || 0).toLocaleString()}
                </dd>
                <dt>{t.tx('投注笔数', 'Bet count')}</dt><dd>{selected.bets_count}</dd>
                <dt>{t.tx('结算', 'Settled')}</dt><dd>{selected.settled ? <span className="badge accent" style={{ fontSize: 10 }}>{t.tx('已结算', 'Settled')}</span> : <span className="badge warning" style={{ fontSize: 10 }}>{t.tx('待结算', 'Pending')}</span>}</dd>
                {selected.flag_reason && (<><dt>{t.tx('异常原因', 'Anomaly reason')}</dt><dd className="text-faint" style={{ fontSize: 11 }}>{selected.flag_reason}</dd></>)}
              </dl>

              <div className="divider" />
              <div className="text-muted" style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.05em' }}>{t.tx('派彩分布（mock）', 'Payout breakdown (mock)')}</div>
              <PayoutBreakdown total={selected.payout || 0} t={t} />
            </div>
          )}
        </div>
      </div>

      {/* Ops log */}
      {(data.ops || []).length > 0 && (
        <div className="card">
          <div className="card-h"><h3>{t.tx('控盘操作日志', 'Control operation log')}</h3><span className="meta">{t.tx('近 ', 'last ')}{Math.min((data.ops || []).length, 50)}{t.tx(' 条', ' entries')}</span></div>
          <div className="tbl-scroll">
          <table className="tbl tbl-stack">
            <thead><tr><th>{t.tx('时间', 'Time')}</th><th>{t.tx('操作', 'Action')}</th><th>{t.tx('操作人', 'Operator')}</th><th>{t.tx('说明', 'Note')}</th></tr></thead>
            <tbody>
              {(data.ops || []).map((op, i) => (
                <tr key={i}>
                  <td data-label={t.tx('时间', 'Time')} className="text-mono" style={{ fontSize: 11 }}>{new Date(op.at).toLocaleString('zh-CN', { hour12: false })}</td>
                  <td data-label={t.tx('操作', 'Action')}>
                    <span className={'badge ' + (op.op === 'pause' ? 'warning' : op.op === 'flag-anomaly' ? 'danger' : 'accent')} style={{ fontSize: 10 }}>
                      {({
                        pause: t.tx('暂停', 'Pause'),
                        resume: t.tx('恢复', 'Resume'),
                        reopen: t.tx('重开', 'Reopen'),
                        'flag-anomaly': t.tx('标记异常', 'Flag anomaly'),
                      })[op.op] || op.op}
                    </span>
                  </td>
                  <td data-label={t.tx('操作人', 'Operator')}>{op.by}</td>
                  <td data-label={t.tx('说明', 'Note')} className="text-faint" style={{ fontSize: 11 }}>{op.note || '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        </div>
      )}
    </div>
  );
}

function CountdownLabel({ seconds }) {
  const [s, setS] = React.useState(seconds || 0);
  React.useEffect(() => { setS(seconds || 0); }, [seconds]);
  React.useEffect(() => { const i = setInterval(() => setS(v => Math.max(0, v - 1)), 1000); return () => clearInterval(i); }, []);
  const m = Math.floor(s / 60), r = s % 60;
  return <div className="tabular" style={{ fontSize: 20, fontWeight: 700, color: s < 30 ? 'var(--danger)' : 'var(--text)' }}>{String(m).padStart(2, '0')}:{String(r).padStart(2, '0')}</div>;
}

function DrawBalls({ numbers, big }) {
  return (
    <div style={{ display: 'flex', gap: big ? 6 : 3 }}>
      {(numbers || []).map((n, i) => (
        <span key={i} className="text-mono"
              style={{
                width: big ? 30 : 22, height: big ? 30 : 22, borderRadius: '50%',
                background: i % 2 === 0 ? 'oklch(0.65 0.18 30)' : 'oklch(0.65 0.16 230)',
                color: 'white', fontWeight: 700, fontSize: big ? 14 : 11,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
          {n}
        </span>
      ))}
    </div>
  );
}

function PayoutBreakdown({ total, t }) {
  const tx = (zh, en) => (t ? t.tx(zh, en) : zh);
  const cuts = [
    { lbl: tx('直选', 'Straight'), pct: 0.35 },
    { lbl: tx('组选', 'Group'), pct: 0.22 },
    { lbl: tx('大小单双', 'Big/Small Odd/Even'), pct: 0.18 },
    { lbl: tx('不定位', 'Any-position'), pct: 0.12 },
    { lbl: tx('趣味', 'Fun bets'), pct: 0.08 },
    { lbl: tx('其他', 'Other'), pct: 0.05 },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {cuts.map(c => (
        <div key={c.lbl}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 3 }}>
            <span>{c.lbl}</span>
            <span className="tabular text-muted">¥{Math.floor(total * c.pct).toLocaleString()}</span>
          </div>
          <div style={{ height: 4, background: 'var(--bg-inset)', borderRadius: 100, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: (c.pct * 100) + '%', background: 'var(--accent)' }} />
          </div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { DrawsScreen });
