<!doctype html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
  <title>{{$title}}</title>
  <script type="module" crossorigin src="/theme/{{$theme}}/assets/umi.js"></script>
</head>

<body>

  <script>
    window.routerBase = "/";
    window.settings = {
      title: '{{$title}}',
      assets_path: '/theme/{{$theme}}/assets',
      theme: {
        color: '{{ $theme_config['theme_color'] ?? "default" }}',
      },
      version: '{{$version}}',
      background_url: '{{$theme_config['background_url']}}',
      description: '{{$description}}',
      i18n: [
        'zh-CN',
        'en-US',
        'ja-JP',
        'vi-VN',
        'ko-KR',
        'zh-TW',
        'fa-IR'
      ],
      logo: '{{$logo}}'
    }
  </script>
  <style>
    .xboard-online-devices-trigger {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      margin-left: 12px;
      padding: 6px 12px;
      border-radius: 999px;
      background: rgba(24, 160, 88, 0.12);
      color: #176b3d;
      font-size: 12px;
      font-weight: 600;
      line-height: 1;
      white-space: nowrap;
    }

    .xboard-online-devices-trigger strong {
      font-size: 13px;
    }

    .xboard-online-devices-menu {
      padding: 10px 14px 12px;
      margin: 6px 8px 0;
      border-radius: 12px;
      background: rgba(24, 160, 88, 0.08);
      color: #1f2937;
    }

    .xboard-online-devices-menu-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      font-size: 13px;
      font-weight: 700;
      color: #176b3d;
    }

    .xboard-online-devices-menu-list {
      margin-top: 8px;
      display: grid;
      gap: 6px;
    }

    .xboard-online-devices-menu-item {
      font-size: 12px;
      color: #4b5563;
      word-break: break-all;
      line-height: 1.5;
    }

    .xboard-online-devices-menu-empty {
      margin-top: 8px;
      font-size: 12px;
      color: #6b7280;
      line-height: 1.5;
    }
  </style>
  <div id="app"></div>
  <script>
    (function () {
      const STORAGE_KEYS = ['access_token', 'AccessToken', 'ACCESS_TOKEN'];
      const SUMMARY_ENDPOINT = '/api/v1/user-online-devices/summary';
      const STATE = {
        loaded: false,
        loading: false,
        enabled: false,
        data: null
      };

      function readTokenFromStorage(storage) {
        if (!storage) return '';
        for (const key of STORAGE_KEYS) {
          const value = storage.getItem(key);
          if (value) return value.replace(/^"|"$/g, '');
        }
        return '';
      }

      function getAccessToken() {
        return readTokenFromStorage(window.localStorage) || readTokenFromStorage(window.sessionStorage);
      }

      function getAuthHeader() {
        const token = getAccessToken();
        if (!token) return '';
        return token.startsWith('Bearer ') ? token : 'Bearer ' + token;
      }

      async function loadSummary() {
        if (STATE.loading || STATE.loaded) return;
        const authorization = getAuthHeader();
        if (!authorization) return;

        STATE.loading = true;

        try {
          const response = await fetch(SUMMARY_ENDPOINT, {
            method: 'GET',
            headers: {
              'Accept': 'application/json',
              'Authorization': authorization
            },
            credentials: 'same-origin'
          });

          if (!response.ok) {
            STATE.enabled = false;
            return;
          }

          const result = await response.json();
          if (result && result.data) {
            STATE.data = result.data;
            STATE.enabled = true;
            STATE.loaded = true;
            injectIntoAvatarArea();
            injectIntoDropdowns();
          }
        } catch (error) {
          STATE.enabled = false;
        } finally {
          STATE.loading = false;
        }
      }

      function buildTriggerHtml() {
        const count = STATE.data?.user?.online_count ?? 0;
        return '<span>在线 IP</span><strong>' + count + '</strong>';
      }

      function buildMenuNode() {
        const wrapper = document.createElement('div');
        wrapper.className = 'xboard-online-devices-menu';
        wrapper.setAttribute('data-user-online-devices-menu', '1');

        const devices = Array.isArray(STATE.data?.online_devices) ? STATE.data.online_devices : [];
        const title = document.createElement('div');
        title.className = 'xboard-online-devices-menu-title';
        title.innerHTML = '<span>在线 IP / 设备</span><span>' + (STATE.data?.user?.online_count ?? 0) + '</span>';
        wrapper.appendChild(title);

        if (!devices.length) {
          const empty = document.createElement('div');
          empty.className = 'xboard-online-devices-menu-empty';
          empty.textContent = '当前没有检测到在线 IP。';
          wrapper.appendChild(empty);
          return wrapper;
        }

        const list = document.createElement('div');
        list.className = 'xboard-online-devices-menu-list';

        devices.forEach(function (device) {
          const item = document.createElement('div');
          item.className = 'xboard-online-devices-menu-item';
          item.textContent = device.name + ': ' + device.ip;
          list.appendChild(item);
        });

        wrapper.appendChild(list);
        return wrapper;
      }

      function injectIntoAvatarArea() {
        if (!STATE.enabled || !STATE.data) return;
        if (document.querySelector('[data-user-online-devices-trigger="1"]')) {
          const current = document.querySelector('[data-user-online-devices-trigger="1"]');
          current.innerHTML = buildTriggerHtml();
          return;
        }

        const avatar = document.querySelector('.n-avatar');
        if (!avatar) return;

        const anchor = avatar.closest('button, .n-button, .n-space, .n-flex, div');
        if (!anchor || !anchor.parentElement) return;

        const badge = document.createElement('span');
        badge.className = 'xboard-online-devices-trigger';
        badge.setAttribute('data-user-online-devices-trigger', '1');
        badge.innerHTML = buildTriggerHtml();
        anchor.parentElement.insertBefore(badge, anchor.nextSibling);
      }

      function injectIntoDropdowns() {
        if (!STATE.enabled || !STATE.data) return;

        const dropdowns = document.querySelectorAll('.n-dropdown-menu');
        dropdowns.forEach(function (dropdown) {
          if (dropdown.querySelector('[data-user-online-devices-menu="1"]')) return;

          const menuNode = buildMenuNode();
          const host = document.createElement('div');
          host.className = 'n-dropdown-option';
          host.appendChild(menuNode);
          dropdown.appendChild(host);
        });
      }

      const observer = new MutationObserver(function () {
        injectIntoAvatarArea();
        injectIntoDropdowns();
      });

      observer.observe(document.documentElement, {
        childList: true,
        subtree: true
      });

      document.addEventListener('click', function () {
        loadSummary();
        window.setTimeout(function () {
          injectIntoAvatarArea();
          injectIntoDropdowns();
        }, 120);
      }, true);

      window.setTimeout(loadSummary, 1200);
      window.setInterval(function () {
        STATE.loaded = false;
        loadSummary();
      }, 30000);
    })();
  </script>
  {!! $theme_config['custom_html'] !!}
</body>

</html>
