// Real bot connection — fetches /metrics from a user-supplied endpoint
// and falls back to mock data when not connected.
//
// Bot side: drop the adapter snippet shown in Settings → Connection into the bot.

const CONN = (() => {
  const KEY = 'shiftbot.conn';
  const saved = (() => {
    try { return JSON.parse(localStorage.getItem(KEY) || '{}'); } catch { return {}; }
  })();

  // dashboard ถูกเสิร์ฟจากบอทเอง → default endpoint = origin เดียวกัน (ไม่ต้องกรอก URL)
  const sameOrigin = (typeof location !== 'undefined' && /^https?:/.test(location.protocol)) ? location.origin : '';

  const state = {
    endpoint: saved.endpoint || sameOrigin,
    token: saved.token || '',
    autoConnect: saved.autoConnect ?? true,
    status: 'disconnected', // disconnected | connecting | connected | error
    lastSeen: null,
    lastError: null,
    listeners: new Set(),
  };

  function persist() {
    try {
      localStorage.setItem(KEY, JSON.stringify({
        endpoint: state.endpoint, token: state.token, autoConnect: state.autoConnect,
      }));
    } catch {}
  }
  function notify() { state.listeners.forEach((cb) => cb()); }

  async function testConnection() {
    if (!state.endpoint) { state.status = 'error'; state.lastError = 'No endpoint set'; notify(); return false; }
    state.status = 'connecting'; state.lastError = null; notify();
    try {
      const url = state.endpoint.replace(/\/$/, '') + '/health';
      const res = await fetch(url, {
        headers: state.token ? { 'Authorization': 'Bearer ' + state.token } : {},
      });
      if (!res.ok) throw new Error('HTTP ' + res.status);
      const data = await res.json().catch(() => ({}));
      state.status = 'connected';
      state.lastSeen = new Date();
      state.lastError = null;
      notify();
      return data;
    } catch (e) {
      state.status = 'error';
      state.lastError = e.message || String(e);
      notify();
      return false;
    }
  }

  function set(patch) { Object.assign(state, patch); persist(); notify(); }
  function subscribe(cb) { state.listeners.add(cb); return () => state.listeners.delete(cb); }

  return {
    get endpoint() { return state.endpoint; },
    get token() { return state.token; },
    get autoConnect() { return state.autoConnect; },
    get status() { return state.status; },
    get lastSeen() { return state.lastSeen; },
    get lastError() { return state.lastError; },
    set, testConnection, subscribe,
  };
})();

function useConn() {
  const [, force] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => CONN.subscribe(force), []);
  return CONN;
}

// Adapter snippet — copy/paste into the user's bot.
const ADAPTER_SNIPPET = `// adapter.js — drop into your discord.js bot
// npm i express cors
const express = require('express');
const cors = require('cors');

module.exports = function mountDashboardAdapter(client, { port = 3001, token = 'CHANGE-ME' } = {}) {
  const app = express();
  app.use(cors());

  // Auth middleware
  app.use((req, res, next) => {
    if ((req.headers.authorization || '') !== 'Bearer ' + token) {
      return res.status(401).json({ error: 'unauthorized' });
    }
    next();
  });

  app.get('/health', (req, res) => {
    res.json({
      ok: true,
      bot: client.user?.tag,
      uptime: process.uptime(),
      ping: client.ws.ping,
      guilds: client.guilds.cache.size,
      version: require('./package.json').version,
    });
  });

  app.get('/metrics', (req, res) => {
    res.json({
      ping: client.ws.ping,
      uptime: process.uptime(),
      memory: process.memoryUsage().rss,
      cpu: process.cpuUsage(),
      guilds: client.guilds.cache.map(g => ({
        id: g.id, name: g.name,
        members: g.memberCount,
        online: g.presences?.cache.filter(p => p.status !== 'offline').size ?? 0,
      })),
    });
  });

  app.get('/logs', (req, res) => res.json({ logs: getRecentLogs() }));

  app.listen(port, () => console.log('Dashboard adapter listening on :' + port));
};

// in your bot entrypoint:
// const mountDashboard = require('./adapter');
// mountDashboard(client, { port: 3001, token: process.env.DASH_TOKEN });`;

Object.assign(window, { CONN, useConn, ADAPTER_SNIPPET });
