// Moderation, Logs, Errors pages.

function PageModeration() {
  const counts = MOD_ACTIONS.reduce((acc, m) => { acc[m.action] = (acc[m.action] || 0) + 1; return acc; }, {});
  const colorFor = {
    ban: 'var(--danger)', kick: 'var(--warn)', timeout: 'var(--violet)',
    warn: 'var(--warn)', clear: 'var(--info)', lock: 'var(--info)', role: 'var(--accent)',
  };
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Moderation</h1>
          <div className="page-sub">Last 7 days · {MOD_ACTIONS.length} actions across {new Set(MOD_ACTIONS.map((m) => m.guild)).size} guilds</div>
        </div>
      </div>

      <div className="grid grid-4">
        {[
          { k: 'ban', label: 'Bans', n: counts.ban || 0 },
          { k: 'kick', label: 'Kicks', n: counts.kick || 0 },
          { k: 'timeout', label: 'Timeouts', n: counts.timeout || 0 },
          { k: 'warn', label: 'Warns', n: counts.warn || 0 },
        ].map((m) => (
          <div key={m.k} className="card stat">
            <div className="stat-label">
              <span style={{ width: 6, height: 6, borderRadius: 2, background: colorFor[m.k] }}/>
              {m.label}
            </div>
            <div className="stat-value" style={{ color: colorFor[m.k] }}>{m.n}</div>
            <div className="stat-delta">last 7 days</div>
          </div>
        ))}
      </div>

      <Card title="Action log" padding={0}>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ width: 110 }}>When</th>
              <th style={{ width: 100 }}>Action</th>
              <th>Target</th>
              <th>Guild</th>
              <th>Moderator</th>
              <th>Reason</th>
              <th>Duration</th>
            </tr>
          </thead>
          <tbody>
            {MOD_ACTIONS.map((m, i) => (
              <tr key={i}>
                <td className="mono muted">{m.t}</td>
                <td><span className="chip" style={{ background: `color-mix(in oklab, ${colorFor[m.action] || 'var(--text-dim)'} 16%, transparent)`, color: colorFor[m.action] || 'var(--text)', borderColor: 'transparent' }}>{m.action}</span></td>
                <td className="mono">{m.target}</td>
                <td className="muted">{m.guild}</td>
                <td>{m.mod}</td>
                <td className="muted">{m.reason}</td>
                <td className="mono">{m.duration}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function PageLogs() {
  const live = useLive();
  const [level, setLevel] = React.useState('all');
  const [src, setSrc] = React.useState('all');
  const sources = ['all', ...Array.from(new Set(live.logs.map((l) => l.source)))];

  const filtered = live.logs.filter((l) => (level === 'all' || l.level === level) && (src === 'all' || l.source === src));

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Logs</h1>
          <div className="page-sub">Live event stream · auto-scroll</div>
        </div>
        <div className="row">
          {live.paused
            ? <span className="chip warn">paused</span>
            : <span className="chip"><span className="dot" style={{ width: 5, height: 5, boxShadow: 'none' }}/>streaming</span>}
          <button className="btn" onClick={() => LIVE.pause(!live.paused)}>{live.paused ? 'Resume' : 'Pause'}</button>
        </div>
      </div>

      <div className="tabs">
        {['all', 'info', 'warn', 'error'].map((l) => (
          <button key={l} className="tab" aria-current={level === l} onClick={() => setLevel(l)}>
            {l[0].toUpperCase() + l.slice(1)}
          </button>
        ))}
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="muted" style={{ fontSize: 12 }}>source</span>
          {sources.map((s) => (
            <button key={s} className="tab" aria-current={src === s} onClick={() => setSrc(s)} style={{ padding: '6px 10px' }}>{s}</button>
          ))}
        </div>
      </div>

      <Card padding={0}>
        <div className="log-stream" style={{ maxHeight: '60vh', border: 0 }}>
          {filtered.map((l, i) => (
            <div className="log-line" key={i}>
              <span className="t">{l.t}</span>
              <span className={`lvl ${l.level}`}>{l.level}</span>
              <span className="src">{l.source}</span>
              <span className="msg">{l.msg}</span>
            </div>
          ))}
          {filtered.length === 0 && <div style={{ padding: 24, color: 'var(--text-muted)', textAlign: 'center' }}>no matching events</div>}
        </div>
      </Card>
    </div>
  );
}

function PageErrors() {
  const conn = useConn();
  const liveData = useLive();
  const isLive = conn.status === 'connected';

  // Live: build error rows from REAL bot logs. Offline: fall back to mock ERRORS.
  const liveErrors = liveData.logs
    .filter((l) => l.level === 'error')
    .map((l, i) => ({ id: i, when: l.t, msg: l.msg, source: l.source }));

  const clearErrors = () =>
    REALDATA.doAction('clearlogs', { level: 'error' })
      .then(() => { REALDATA.refreshAll(); toast('เคลียร์ error แล้ว', 'success'); })
      .catch((e) => toast(e.message, 'error'));

  const reloadCommands = () => {
    toastConfirm('Hot-reload โค้ดคำสั่งทั้งหมดเพื่อแก้ error?').then((ok) => {
      if (!ok) return;
      REALDATA.doAction('reload')
        .then((r) => { toast('Reload สำเร็จ', 'success'); REALDATA.refreshAll(); })
        .catch((e) => toast(e.message, 'error'));
    });
  };

  const restartBot = () => {
    toastConfirm('Restart บอท?', { danger: true }).then((ok) => {
      if (!ok) return;
      REALDATA.doAction('restart')
        .then(() => toast('สั่ง restart แล้ว', 'success'))
        .catch((e) => toast(e.message, 'error'));
    });
  };

  if (isLive) {
    return (
      <div className="page">
        <div className="page-head">
          <div>
            <h1 className="page-title">Errors</h1>
            <div className="page-sub">{liveErrors.length} error{liveErrors.length === 1 ? '' : 's'} · live</div>
          </div>
          <div className="row">
            <button className="btn" onClick={clearErrors}>เคลียร์ Error</button>
            <button className="btn primary" onClick={reloadCommands}>Reload commands (แก้ &amp; รันใหม่)</button>
            <button className="btn danger" onClick={restartBot}>Restart bot</button>
          </div>
        </div>

        <Card padding={0}>
          {liveErrors.length === 0 ? (
            <div style={{ padding: 48, color: 'var(--text-muted)', textAlign: 'center' }}>
              ✓ ไม่มี error — ระบบทำงานปกติ
            </div>
          ) : (
            <table className="tbl">
              <thead>
                <tr>
                  <th>Time</th>
                  <th>Source</th>
                  <th>Error</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {liveErrors.map((e) => (
                  <tr key={e.id}>
                    <td className="mono muted">{e.when}</td>
                    <td><span className="chip">{e.source}</span></td>
                    <td className="mono ellipsis" style={{ maxWidth: 480, whiteSpace: 'pre-wrap' }}>{e.msg}</td>
                    <td className="num">
                      <button className="btn" style={{ padding: '3px 8px', fontSize: 11 }} onClick={reloadCommands}>ลองแก้ (reload)</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </Card>
      </div>
    );
  }

  return <PageErrorsMock />;
}

function PageErrorsMock() {
  const [openId, setOpenId] = React.useState(ERRORS[0].id);
  const open = ERRORS.find((e) => e.id === openId) || ERRORS[0];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Errors</h1>
          <div className="page-sub">{ERRORS.filter((e) => e.status === 'open').length} open · {ERRORS.length} total tracked</div>
        </div>
        <div className="row">
          <button className="btn" disabled>เคลียร์ Error</button>
          <button className="btn primary" disabled>Reload commands (แก้ &amp; รันใหม่)</button>
          <button className="btn danger" disabled>Restart bot</button>
        </div>
      </div>

      <div className="grid grid-12-5">
        <Card padding={0}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Status</th>
                <th>Error</th>
                <th>Command</th>
                <th className="num">Count</th>
                <th>Last seen</th>
              </tr>
            </thead>
            <tbody>
              {ERRORS.map((e) => (
                <tr key={e.id} onClick={() => setOpenId(e.id)} style={{ cursor: 'pointer', background: e.id === openId ? 'var(--surface-2)' : undefined }}>
                  <td>
                    {e.status === 'open' && <span className="chip danger">open</span>}
                    {e.status === 'ignored' && <span className="chip">ignored</span>}
                    {e.status === 'resolved' && <span className="chip solid">resolved</span>}
                  </td>
                  <td className="ellipsis" style={{ maxWidth: 280 }}>{e.msg}</td>
                  <td className="mono">{e.cmd}</td>
                  <td className="num">{e.count}</td>
                  <td className="mono muted">{e.when}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <Card title={open.msg} sub={`${open.id} · last seen ${open.when}`}>
          <div className="kv"><div className="kv-key">Command</div><div className="kv-val mono">{open.cmd}</div></div>
          <div className="kv"><div className="kv-key">Guild</div><div className="kv-val">{open.guild}</div></div>
          <div className="kv"><div className="kv-key">User</div><div className="kv-val mono">{open.user}</div></div>
          <div className="kv"><div className="kv-key">Occurrences</div><div className="kv-val mono">{open.count}</div></div>
          <div className="kv"><div className="kv-key">Status</div><div className="kv-val">
            {open.status === 'open' && <span className="chip danger">open</span>}
            {open.status === 'ignored' && <span className="chip">ignored</span>}
            {open.status === 'resolved' && <span className="chip solid">resolved</span>}
          </div></div>

          <div style={{ marginTop: 14 }}>
            <div className="card-title" style={{ marginBottom: 8 }}>Stack trace</div>
            <pre style={{
              fontFamily: 'var(--font-mono)', fontSize: 11.5,
              background: 'var(--bg-2)', border: '1px solid var(--border)',
              borderRadius: 8, padding: 12, margin: 0,
              color: 'var(--text-muted)', overflow: 'auto', whiteSpace: 'pre-wrap', lineHeight: 1.6,
            }}>{open.stack}</pre>
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { PageModeration, PageLogs, PageErrors });
