// 2FA / Authenticator page — live TOTP codes per company + usage history.

function authRelTime(ms) {
  const n = Number(ms);
  if (!n) return '—';
  const s = Math.max(0, Math.floor((Date.now() - n) / 1000));
  if (s < 60) return s + ' วินาทีที่แล้ว';
  if (s < 3600) return Math.floor(s / 60) + ' นาทีที่แล้ว';
  if (s < 86400) return Math.floor(s / 3600) + ' ชั่วโมงที่แล้ว';
  return Math.floor(s / 86400) + ' วันที่แล้ว';
}
function authAbsTime(ms) {
  const d = new Date(Number(ms) || Date.now());
  return d.toLocaleString('th-TH', { timeZone: 'Asia/Bangkok', dateStyle: 'short', timeStyle: 'medium' });
}

function CompanyCodeCard({ c, remaining }) {
  const period = c.period || 30;
  const pct = Math.max(0, Math.min(100, (remaining / period) * 100));
  const color = remaining >= 15 ? 'var(--accent)' : remaining >= 5 ? 'var(--warn)' : 'var(--danger)';

  if (!c.configured) {
    return (
      <div className="card" style={{ padding: 18 }}>
        <div className="row between" style={{ marginBottom: 10 }}>
          <span style={{ fontWeight: 600 }}>🏢 {c.name}</span>
          <span className="chip warn">ยังไม่ตั้งค่า</span>
        </div>
        <div className="muted" style={{ fontSize: 12.5 }}>
          ตั้ง secret ใน <code>.env</code> (<code>TOTP_COMPANY_{c.key}</code>) เพื่อแสดงรหัส
        </div>
      </div>
    );
  }

  return (
    <div className="card" style={{ padding: 18 }}>
      <div className="row between" style={{ marginBottom: 12 }}>
        <span style={{ fontWeight: 600 }}>🏢 {c.name}</span>
        <span className="chip mono" style={{ color }}>{remaining}s</span>
      </div>
      <div
        title="คลิกเพื่อคัดลอก"
        onClick={() => { navigator.clipboard?.writeText(c.code).then(() => toast('คัดลอกรหัสแล้ว', 'success')).catch(() => {}); }}
        style={{
          fontFamily: 'var(--font-mono)', fontSize: 38, fontWeight: 700, letterSpacing: 4,
          textAlign: 'center', cursor: 'pointer', userSelect: 'all', color: 'var(--text)',
          padding: '6px 0',
        }}
      >
        {c.codeFormatted}
      </div>
      <div className="bar-track" style={{ marginTop: 8, height: 5 }}>
        <div className="bar-fill" style={{ width: pct + '%', background: color, transition: 'width 1s linear' }}/>
      </div>
      <div className="row between" style={{ marginTop: 10, fontSize: 12 }}>
        <span className="muted">ถัดไป</span>
        <span className="mono" style={{ color: 'var(--text-muted)' }}>{c.nextFormatted}</span>
      </div>
    </div>
  );
}

function PageAuth() {
  const conn = useConn();
  useRealData();
  const [, tick] = React.useReducer((x) => x + 1, 0);
  const live = conn.status === 'connected';

  React.useEffect(() => {
    const t1 = setInterval(() => tick(), 1000);
    const t2 = setInterval(() => { if (CONN.status === 'connected') REALDATA.fetchTotp(); }, 2500);
    if (CONN.status === 'connected') REALDATA.fetchTotp();
    return () => { clearInterval(t1); clearInterval(t2); };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const totp = REALDATA.totp || { companies: [], fetchedAt: 0 };
  const companies = totp.companies || [];
  const history = REALDATA.totpHistory || [];

  function liveRemaining(c) {
    if (!c.configured) return 0;
    const elapsed = (Date.now() - (totp.fetchedAt || Date.now())) / 1000;
    let r = Math.round((c.remaining || 0) - elapsed);
    if (r < 0) r = 0;
    return r;
  }

  const configuredCount = companies.filter((c) => c.configured).length;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">2FA · Authenticator</h1>
          <div className="page-sub">
            {live
              ? `รหัส 6 หลักปัจจุบันของแต่ละบริษัท · ตั้งค่าแล้ว ${configuredCount}/${companies.length}`
              : 'เชื่อมต่อบอทเพื่อดูรหัสจริง'}
          </div>
        </div>
        <button className="btn" disabled={!live} onClick={() => REALDATA.fetchTotp()}>
          <I.refresh width="13" height="13"/>รีเฟรช
        </button>
      </div>

      {!live && (
        <Card>
          <div className="muted" style={{ padding: 8 }}>ยังไม่ได้เชื่อมต่อบอท — ไปที่ Settings → Connection</div>
        </Card>
      )}

      {live && companies.length === 0 && (
        <Card><div className="muted" style={{ padding: 8 }}>กำลังโหลดรหัส…</div></Card>
      )}

      {live && companies.length > 0 && (
        <div className="grid grid-3">
          {companies.map((c) => (
            <CompanyCodeCard key={c.key} c={c} remaining={liveRemaining(c)}/>
          ))}
        </div>
      )}

      <Card title="ประวัติการขอรหัส" sub={`${history.length} รายการล่าสุด · จาก Discord`} padding={0}>
        <table className="tbl">
          <thead>
            <tr><th>ผู้ขอ</th><th>บริษัท</th><th>เวลา</th></tr>
          </thead>
          <tbody>
            {history.map((h, i) => (
              <tr key={i}>
                <td>
                  <div className="row">
                    {h.avatarURL
                      ? <img src={h.avatarURL} alt="" style={{ width: 24, height: 24, borderRadius: 999, objectFit: 'cover' }}/>
                      : <div style={{ width: 24, height: 24, borderRadius: 999, background: `hsl(${(h.displayName || '?').charCodeAt(0) * 9} 70% 60%)` }}/>}
                    <div>
                      <div>{h.displayName || h.username}</div>
                      <div className="mono muted" style={{ fontSize: 10.5 }}>{h.userId}</div>
                    </div>
                  </div>
                </td>
                <td>🏢 {h.companyName}</td>
                <td className="muted" title={authAbsTime(h.at)}>{authRelTime(h.at)}</td>
              </tr>
            ))}
            {history.length === 0 && (
              <tr><td colSpan={3} style={{ padding: 24, textAlign: 'center', color: 'var(--text-muted)' }}>
                {live ? 'ยังไม่มีประวัติการขอรหัส' : '—'}
              </td></tr>
            )}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

Object.assign(window, { PageAuth });
