<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { browser } from "wxt/browser";

import { normalizeRemoteUrl } from "../../src/adapters/common";
import { getExtensionState } from "../../src/storage";
import type { StoredMonitoringPlatformState } from "../../src/monitoring-platforms";
import type { StoredPlatformState } from "../../src/platforms";

type BackgroundSuccessResponse = {
  ok: true;
  data: unknown;
};

type BackgroundErrorResponse = {
  ok: false;
  error?: string;
};

const loading = ref(true);
const refreshing = ref(false);
const monitoringRefreshing = ref(false);
const monitoringHeartbeating = ref(false);
const monitoringCycling = ref(false);

const installationKey = ref("");
const installationId = ref<number | null>(null);
const apiBaseUrl = ref<string | null>(null);
const platforms = ref<StoredPlatformState[]>([]);
const monitoringPlatforms = ref<StoredMonitoringPlatformState[]>([]);
const monitoringLastHeartbeatAt = ref<string | null>(null);
const monitoringLastHeartbeatStatus = ref<string | null>(null);
const monitoringLastCycleAt = ref<string | null>(null);
const monitoringLastCycleStatus = ref<string | null>(null);
const popupError = ref<string | null>(null);
const monitoringMessage = ref<string | null>(null);

const connectedCount = computed(() => platforms.value.filter((item) => item.connected).length);
const monitoringAccessibleCount = computed(() => monitoringPlatforms.value.filter((item) => item.accessible).length);
const monitoringBusy = computed(
  () => loading.value || monitoringRefreshing.value || monitoringHeartbeating.value || monitoringCycling.value,
);

const statusText = computed(() => {
  if (loading.value || refreshing.value) {
    return "正在检测平台状态...";
  }
  return `已连接 ${connectedCount.value}/${platforms.value.length} 个平台`;
});

onMounted(() => {
  void initializePopup();
});

function clonePlatforms(items: StoredPlatformState[]): StoredPlatformState[] {
  return items.map((platform) => ({ ...platform }));
}

function cloneMonitoringPlatforms(items: StoredMonitoringPlatformState[]): StoredMonitoringPlatformState[] {
  return items.map((platform) => ({ ...platform }));
}

function isBackgroundResponse(value: unknown): value is BackgroundSuccessResponse | BackgroundErrorResponse {
  return typeof value === "object" && value !== null && "ok" in value;
}

async function loadState(): Promise<void> {
  loading.value = true;
  try {
    await syncStateFromStorage();
  } finally {
    loading.value = false;
  }
}

async function initializePopup(): Promise<void> {
  try {
    await loadState();
    await Promise.allSettled([refreshDetectedPlatforms(), refreshMonitoringPlatforms()]);
  } finally {
    loading.value = false;
  }
}

async function syncStateFromStorage(): Promise<void> {
  const state = await getExtensionState();
  installationKey.value = state.installation_key;
  installationId.value = state.plugin_installation_id;
  apiBaseUrl.value = state.api_base_url;
  platforms.value = clonePlatforms(state.platforms);
  monitoringPlatforms.value = cloneMonitoringPlatforms(state.monitoring_platforms);
  monitoringLastHeartbeatAt.value = state.monitoring_last_heartbeat_at;
  monitoringLastHeartbeatStatus.value = state.monitoring_last_heartbeat_status;
  monitoringLastCycleAt.value = state.monitoring_last_cycle_at;
  monitoringLastCycleStatus.value = state.monitoring_last_cycle_status;
}

function titleFor(platform: StoredPlatformState): string {
  return platform.nickname?.trim() || platform.platform_name;
}

function uidFor(platform: StoredPlatformState): string {
  return platform.platform_uid != null ? String(platform.platform_uid).trim() : "未检测到平台账号";
}

function avatarFor(platform: StoredPlatformState): string | null {
  const normalizedAvatar = normalizeRemoteUrl(platform.avatar_url);
  if (normalizedAvatar) {
    return normalizedAvatar;
  }
  if (platform.connected) {
    return `https://api.dicebear.com/9.x/initials/svg?seed=${encodeURIComponent(titleFor(platform))}`;
  }
  return null;
}

function statusTone(platform: StoredPlatformState): "success" | "danger" | "pending" {
  if (refreshing.value || loading.value) {
    return "pending";
  }
  return platform.connected ? "success" : "danger";
}

function loginButtonLabel(platform: StoredPlatformState): string {
  if (refreshing.value || loading.value) {
    return "检测中...";
  }
  return "未登录";
}

async function openLoginPage(platform: StoredPlatformState): Promise<void> {
  if (!platform.login_url || refreshing.value || loading.value) {
    return;
  }
  await browser.tabs.create({ url: platform.login_url });
}

async function simulateDetect(): Promise<void> {
  await refreshDetectedPlatforms();
}

async function refreshDetectedPlatforms(): Promise<void> {
  refreshing.value = true;
  popupError.value = null;
  try {
    const response = await browser.runtime.sendMessage({
      type: "geo.publisher.request",
      action: "detectPlatforms",
    });
    if (isBackgroundResponse(response) && !response.ok) {
      throw new Error(response.error || "publisher_plugin_unknown_error");
    }
    await syncStateFromStorage();
  } catch (error) {
    popupError.value = error instanceof Error ? error.message : "publisher_plugin_unknown_error";
  } finally {
    refreshing.value = false;
  }
}

function monitoringStatusLabel(platform: StoredMonitoringPlatformState): string {
  if (platform.reason_code === "runtime_sync_pending") {
    return "待同步";
  }
  if (platform.accessible) {
    return "可采集";
  }
  if (platform.reason_code === "not_logged_in") {
    return "需登录";
  }
  return "不可用";
}

function monitoringTone(platform: StoredMonitoringPlatformState): "success" | "danger" | "pending" {
  if (monitoringBusy.value) {
    return "pending";
  }
  if (platform.reason_code === "runtime_sync_pending") {
    return "pending";
  }
  return platform.accessible ? "success" : "danger";
}

function monitoringHeartbeatSummary(): string {
  if (!monitoringLastHeartbeatAt.value) {
    return `可采集 ${monitoringAccessibleCount.value}/${monitoringPlatforms.value.length} 个平台`;
  }
  return `可采集 ${monitoringAccessibleCount.value}/${monitoringPlatforms.value.length} 个平台 · 最近心跳 ${formatDateTime(monitoringLastHeartbeatAt.value)}`;
}

function formatDateTime(value?: string | null): string {
  if (!value) {
    return "--";
  }
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }
  return date.toLocaleString("zh-CN", {
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function monitoringHeartbeatStatusText(): string {
  switch (monitoringLastHeartbeatStatus.value) {
    case "success":
      return `心跳在线 ${formatDateTime(monitoringLastHeartbeatAt.value)}`;
    case "failed":
      return `心跳失败 ${formatDateTime(monitoringLastHeartbeatAt.value)}`;
    case "local_only":
      return "插件尚未绑定到 SaaS";
    default:
      return "尚未同步心跳";
  }
}

function monitoringCycleStatusText(): string {
  switch (monitoringLastCycleStatus.value) {
    case "success":
      return `巡检完成 ${formatDateTime(monitoringLastCycleAt.value)}`;
    case "partial_failed":
      return `巡检部分失败 ${formatDateTime(monitoringLastCycleAt.value)}`;
    case "skipped":
      return `巡检已跳过 ${formatDateTime(monitoringLastCycleAt.value)}`;
    case "idle":
      return `巡检空闲 ${formatDateTime(monitoringLastCycleAt.value)}`;
    case "no_query_capable_platforms":
      return "已在线，采集适配器待接入";
    case "not_configured":
      return "插件尚未绑定到 SaaS";
    case "heartbeat_failed":
      return `巡检前心跳失败 ${formatDateTime(monitoringLastCycleAt.value)}`;
    default:
      return "尚未执行巡检";
  }
}

function monitoringStatusPillTone(): "success" | "danger" | "pending" {
  if (monitoringBusy.value) {
    return "pending";
  }
  if (monitoringAccessibleCount.value > 0 && monitoringLastHeartbeatStatus.value === "success") {
    return "success";
  }
  return "danger";
}

async function openMonitoringLoginPage(platform: StoredMonitoringPlatformState): Promise<void> {
  if (!platform.login_url || monitoringBusy.value) {
    return;
  }
  await browser.tabs.create({ url: platform.login_url });
}

async function refreshMonitoringPlatforms(): Promise<void> {
  monitoringRefreshing.value = true;
  monitoringMessage.value = null;
  try {
    const response = await browser.runtime.sendMessage({
      type: "geo.monitoring.request",
      action: "detectPlatforms",
    });
    if (isBackgroundResponse(response) && !response.ok) {
      throw new Error(response.error || "monitoring_plugin_unknown_error");
    }
    await syncStateFromStorage();
    monitoringMessage.value = "已刷新本地监测平台状态";
  } catch (error) {
    monitoringMessage.value = error instanceof Error ? error.message : "monitoring_plugin_unknown_error";
  } finally {
    monitoringRefreshing.value = false;
  }
}

async function syncMonitoringHeartbeat(): Promise<void> {
  monitoringHeartbeating.value = true;
  monitoringMessage.value = null;
  try {
    const response = await browser.runtime.sendMessage({
      type: "geo.monitoring.request",
      action: "syncHeartbeat",
    });
    if (isBackgroundResponse(response) && !response.ok) {
      throw new Error(response.error || "monitoring_plugin_unknown_error");
    }
    await syncStateFromStorage();
    monitoringMessage.value = "已同步 monitoring heartbeat";
  } catch (error) {
    monitoringMessage.value = error instanceof Error ? error.message : "monitoring_plugin_unknown_error";
  } finally {
    monitoringHeartbeating.value = false;
  }
}

async function runMonitoringCycle(): Promise<void> {
  monitoringCycling.value = true;
  monitoringMessage.value = null;
  try {
    const response = await browser.runtime.sendMessage({
      type: "geo.monitoring.request",
      action: "runCycle",
    });
    if (isBackgroundResponse(response) && !response.ok) {
      throw new Error(response.error || "monitoring_plugin_unknown_error");
    }
    await syncStateFromStorage();
    monitoringMessage.value = "已执行一轮 monitoring 巡检";
  } catch (error) {
    monitoringMessage.value = error instanceof Error ? error.message : "monitoring_plugin_unknown_error";
  } finally {
    monitoringCycling.value = false;
  }
}
</script>

<template>
  <main class="popup-shell">
    <header class="popup-header">
      <p class="popup-brand">My GEO</p>
      <p class="popup-subtitle">{{ loading || refreshing ? "正在检测平台状态..." : "管理您的媒体平台账号" }}</p>
    </header>

    <section v-if="loading" class="popup-loading">
      <div class="popup-spinner" />
      <p>正在读取插件状态...</p>
    </section>

    <template v-else>
      <section class="popup-list">
        <article
          v-for="platform in platforms"
          :key="platform.platform_id"
          class="platform-card"
          :class="[`is-${statusTone(platform)}`]"
          :style="{ '--platform-accent': platform.accent_color }"
        >
          <div class="platform-card__accent" />

          <div class="platform-card__body">
            <div class="platform-card__identity">
              <div class="platform-card__logo">
                <img v-if="platform.logo_path" :src="platform.logo_path" :alt="platform.platform_name" />
                <span v-else>{{ platform.short_name }}</span>
                <i />
              </div>

              <div class="platform-card__meta">
                <h2>{{ platform.platform_name }}</h2>
                <p
                  v-if="!platform.connected && !loading && !refreshing && platform.message"
                  class="platform-card__hint"
                  :title="platform.message"
                >
                  {{ platform.message }}
                </p>
              </div>
            </div>

            <div v-if="platform.connected && !refreshing" class="platform-card__account">
              <img v-if="avatarFor(platform)" :src="avatarFor(platform)!" :alt="titleFor(platform)" class="platform-card__avatar" />
              <div class="platform-card__account-copy">
                <strong>{{ titleFor(platform) }}</strong>
                <span>{{ uidFor(platform) }}</span>
              </div>
            </div>

            <button
              v-else
              type="button"
              class="platform-card__status-chip"
              :class="`is-${statusTone(platform)}`"
              :disabled="!platform.login_url || refreshing || loading"
              @click.stop="openLoginPage(platform)"
            >
              {{ loginButtonLabel(platform) }}
            </button>
          </div>
        </article>

        <p class="popup-status">{{ statusText }}</p>
        <p v-if="popupError" class="popup-status popup-status--error">{{ popupError }}</p>

        <section class="popup-monitoring">
          <div class="popup-monitoring__header">
            <div>
              <h3>AI 监测平台</h3>
              <p>{{ monitoringHeartbeatSummary() }}</p>
            </div>
            <span class="popup-monitoring__pill" :class="`is-${monitoringStatusPillTone()}`">
              {{ monitoringAccessibleCount }}/{{ monitoringPlatforms.length }} 可采集
            </span>
          </div>

          <div class="popup-monitoring__stats">
            <div class="popup-monitoring__stat">
              <span>Heartbeat</span>
              <strong>{{ monitoringHeartbeatStatusText() }}</strong>
            </div>
            <div class="popup-monitoring__stat">
              <span>Cycle</span>
              <strong>{{ monitoringCycleStatusText() }}</strong>
            </div>
          </div>

          <div class="popup-monitoring__actions">
            <button type="button" :disabled="monitoringBusy" @click="refreshMonitoringPlatforms">
              {{ monitoringRefreshing ? "检测中" : "检测" }}
            </button>
            <button type="button" :disabled="monitoringBusy" @click="syncMonitoringHeartbeat">
              {{ monitoringHeartbeating ? "同步中" : "心跳" }}
            </button>
            <button type="button" :disabled="monitoringBusy" @click="runMonitoringCycle">
              {{ monitoringCycling ? "巡检中" : "巡检" }}
            </button>
          </div>

          <p v-if="monitoringMessage" class="popup-monitoring__message">
            {{ monitoringMessage }}
          </p>

          <div class="popup-monitoring__list">
            <article
              v-for="platform in monitoringPlatforms"
              :key="platform.ai_platform_id"
              class="popup-monitoring__item"
              :class="`is-${monitoringTone(platform)}`"
              :style="{ '--monitoring-accent': platform.accent_color }"
            >
              <div class="popup-monitoring__identity">
                <div class="popup-monitoring__logo">
                  <span>{{ platform.short_name }}</span>
                </div>
                <div class="popup-monitoring__copy">
                  <strong>{{ platform.platform_name }}</strong>
                  <span>{{ platform.access_requirement === "login_required" ? "登录后可采集" : "可匿名采集" }}</span>
                </div>
              </div>

              <div class="popup-monitoring__meta">
                <em>{{ monitoringStatusLabel(platform) }}</em>
                <small>{{ platform.reason_message || formatDateTime(platform.detected_at) }}</small>
              </div>

              <button
                v-if="platform.access_requirement === 'login_required' && !platform.connected && platform.login_url"
                type="button"
                class="popup-monitoring__login"
                :disabled="monitoringBusy"
                @click.stop="openMonitoringLoginPage(platform)"
              >
                去登录
              </button>
            </article>
          </div>
        </section>

        <details class="popup-debug">
          <summary>调试信息</summary>
          <dl>
            <div>
              <dt>安装实例 ID</dt>
              <dd>{{ installationId ?? "--" }}</dd>
            </div>
            <div>
              <dt>SaaS 地址</dt>
              <dd>{{ apiBaseUrl || "--" }}</dd>
            </div>
            <div>
              <dt>Installation Key</dt>
              <dd>{{ installationKey }}</dd>
            </div>
            <div>
              <dt>Monitoring Heartbeat</dt>
              <dd>{{ monitoringLastHeartbeatStatus || "--" }}</dd>
            </div>
            <div>
              <dt>Monitoring Cycle</dt>
              <dd>{{ monitoringLastCycleStatus || "--" }}</dd>
            </div>
          </dl>
        </details>
      </section>

      <footer class="popup-footer">
        <button type="button" class="popup-detect" :disabled="refreshing" @click="simulateDetect">
          <span class="popup-detect__icon" :class="{ 'is-spinning': refreshing }">↻</span>
          <span>{{ refreshing ? "检测中..." : "重新检测" }}</span>
        </button>
      </footer>
    </template>
  </main>
</template>

<style scoped>
:global(html) {
  width: 360px;
  height: 600px;
}

:global(body) {
  margin: 0;
  height: 100%;
  overflow: hidden;
  color: #516173;
  font-family: "SF Pro Display", "PingFang SC", "Microsoft YaHei", sans-serif;
  background:
    radial-gradient(circle at top, rgba(140, 179, 255, 0.32), transparent 42%),
    linear-gradient(180deg, #edf4ff 0%, #f8fbff 100%);
}

:global(#app) {
  height: 100%;
  overflow: hidden;
}

:global(*) {
  box-sizing: border-box;
}

.popup-shell {
  display: flex;
  flex-direction: column;
  position: relative;
  height: 100%;
  padding: 0;
}

.popup-header {
  flex-shrink: 0;
  padding: 24px 24px 14px;
  text-align: center;
  background: rgba(248, 251, 255, 0.92);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-bottom: 1px solid rgba(216, 225, 238, 0.5);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.04);
  z-index: 10;
}

.popup-brand {
  margin: 0;
  color: #18263a;
  font-size: 24px;
  font-weight: 800;
  letter-spacing: 0.02em;
}

.popup-subtitle {
  margin: 6px 0 0;
  color: #6c7b90;
  font-size: 14px;
  font-weight: 600;
}

.popup-loading {
  display: grid;
  place-items: center;
  gap: 12px;
  flex: 1;
  color: #7a8698;
  padding: 16px 14px;
}

.popup-spinner {
  width: 28px;
  height: 28px;
  border: 3px solid rgba(71, 122, 255, 0.18);
  border-top-color: #4f7dff;
  border-radius: 999px;
  animation: spin 0.9s linear infinite;
}

.popup-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex: 1;
  overflow-y: auto;
  padding: 16px 14px;
}

.popup-list::-webkit-scrollbar {
  width: 6px;
}

.popup-list::-webkit-scrollbar-thumb {
  border-radius: 999px;
  background: rgba(122, 144, 179, 0.28);
}

.platform-card {
  flex-shrink: 0;
  position: relative;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background: #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
  transition:
    transform 180ms ease,
    box-shadow 180ms ease,
    border-color 180ms ease;
}

.platform-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.platform-card__accent {
  position: absolute;
  inset: 0 auto 0 0;
  width: 4px;
  background: #ff7f86;
}

.platform-card.is-success .platform-card__accent {
  background: linear-gradient(180deg, #55d7b7, #47b69f);
}

.platform-card.is-danger .platform-card__accent {
  background: linear-gradient(180deg, #ff8b91, #ff6c74);
}

.platform-card.is-pending .platform-card__accent {
  background: linear-gradient(180deg, #ff8b91, #ff6c74);
}

.platform-card__body {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  align-items: center;
  gap: 14px;
  padding: 16px 20px;
}

.platform-card__identity {
  display: flex;
  align-items: center;
  gap: 14px;
  min-width: 0;
}

.platform-card__logo {
  position: relative;
  display: grid;
  place-items: center;
  width: 44px;
  height: 44px;
  border: 1px solid #f0f0f0;
  border-radius: 10px;
  background: #ffffff;
  color: var(--platform-accent);
  font-size: 24px;
  font-weight: 800;
}

.platform-card__logo img {
  width: 30px;
  height: 30px;
  object-fit: contain;
}

.platform-card__logo i {
  position: absolute;
  right: -2px;
  bottom: -2px;
  width: 10px;
  height: 10px;
  border: 2px solid #ffffff;
  border-radius: 999px;
  background: #f7bf4b;
}

.platform-card__meta h2 {
  margin: 0;
  color: #333333;
  font-size: 16px;
  font-weight: 600;
}

.platform-card__hint {
  margin: 4px 0 0;
  overflow: hidden;
  color: #9aa5b5;
  font-size: 11px;
  font-weight: 500;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.platform-card__account {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
}

.platform-card__avatar {
  width: 36px;
  height: 36px;
  border: 1px solid #f0f0f0;
  border-radius: 999px;
  object-fit: cover;
  background: #f3f6fb;
}

.platform-card__account-copy {
  min-width: 0;
  text-align: left;
}

.platform-card__account-copy strong,
.platform-card__account-copy span {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.platform-card__account-copy strong {
  color: #333333;
  font-size: 14px;
  font-weight: 600;
}

.platform-card__account-copy span {
  margin-top: 2px;
  color: #999999;
  font-size: 12px;
  font-weight: 400;
}

.platform-card__status-chip {
  appearance: none;
  min-width: 72px;
  padding: 6px 12px;
  border: 1px solid transparent;
  border-radius: 6px;
  text-align: center;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition:
    transform 150ms ease,
    opacity 150ms ease,
    box-shadow 150ms ease;
}

.platform-card__status-chip:hover:not(:disabled) {
  transform: translateY(-1px);
}

.platform-card__status-chip:disabled {
  cursor: not-allowed;
  opacity: 0.72;
  transform: none;
}

.platform-card__status-chip.is-danger,
.platform-card__status-chip.is-pending {
  color: #ff6b6b;
  border-color: rgba(255, 107, 107, 0.3);
  background: #ffffff;
}

.platform-card__status-chip.is-success {
  color: #4ab79f;
  border-color: rgba(74, 183, 159, 0.3);
  background: #ffffff;
}
.popup-detect {
  appearance: none;
  border: none;
  border-radius: 14px;
  font: inherit;
  cursor: pointer;
  transition:
    transform 150ms ease,
    opacity 150ms ease,
    box-shadow 150ms ease;
}

.popup-detect:hover {
  transform: translateY(-1px);
}

.popup-detect:disabled {
  cursor: not-allowed;
  opacity: 0.68;
  transform: none;
}

.popup-footer {
  flex-shrink: 0;
  margin: 0;
  padding: 12px 14px;
  padding-bottom: max(12px, env(safe-area-inset-bottom));
  background: rgba(248, 251, 255, 0.92);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-top: 1px solid rgba(216, 225, 238, 0.5);
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.04);
  z-index: 10;
}

.popup-detect {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  min-height: 48px;
  border-radius: 12px;
  background: linear-gradient(180deg, #a5aab7, #9197a5);
  color: #ffffff;
  font-size: 15px;
  font-weight: 700;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.22);
}

.popup-detect__icon {
  display: inline-block;
  font-size: 18px;
  line-height: 1;
}

.popup-detect__icon.is-spinning {
  animation: spin 0.9s linear infinite;
}

.popup-status {
  margin: 4px 0 0;
  padding: 0;
  color: #7f8b9d;
  font-size: 14px;
  font-weight: 700;
  text-align: center;
}

.popup-status--error {
  color: #c84545;
}

.popup-monitoring {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 14px;
  padding: 14px;
  border: 1px solid rgba(216, 225, 238, 0.95);
  border-radius: 18px;
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.94), rgba(246, 249, 255, 0.94));
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.86);
}

.popup-monitoring__header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.popup-monitoring__header h3 {
  margin: 0;
  color: #213247;
  font-size: 15px;
  font-weight: 800;
}

.popup-monitoring__header p {
  margin: 4px 0 0;
  color: #7d8ca0;
  font-size: 12px;
  font-weight: 600;
}

.popup-monitoring__pill {
  flex-shrink: 0;
  padding: 6px 10px;
  border: 1px solid transparent;
  border-radius: 999px;
  font-size: 11px;
  font-weight: 800;
}

.popup-monitoring__pill.is-success {
  color: #167a61;
  background: rgba(37, 182, 135, 0.12);
  border-color: rgba(37, 182, 135, 0.18);
}

.popup-monitoring__pill.is-danger {
  color: #b64d4d;
  background: rgba(224, 95, 95, 0.12);
  border-color: rgba(224, 95, 95, 0.18);
}

.popup-monitoring__pill.is-pending {
  color: #8d6b17;
  background: rgba(243, 190, 68, 0.15);
  border-color: rgba(243, 190, 68, 0.22);
}

.popup-monitoring__stats {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px;
}

.popup-monitoring__stat {
  padding: 10px 12px;
  border: 1px solid rgba(223, 230, 240, 0.92);
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.82);
}

.popup-monitoring__stat span {
  display: block;
  margin-bottom: 6px;
  color: #8a96a7;
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
}

.popup-monitoring__stat strong {
  display: block;
  color: #324459;
  font-size: 12px;
  font-weight: 700;
  line-height: 1.4;
}

.popup-monitoring__actions {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 8px;
}

.popup-monitoring__actions button,
.popup-monitoring__login {
  appearance: none;
  min-height: 36px;
  padding: 0 10px;
  border: 1px solid rgba(76, 114, 255, 0.18);
  border-radius: 12px;
  background: #ffffff;
  color: #3351b8;
  font-size: 12px;
  font-weight: 800;
  cursor: pointer;
  transition:
    transform 150ms ease,
    opacity 150ms ease,
    box-shadow 150ms ease;
}

.popup-monitoring__actions button:hover:not(:disabled),
.popup-monitoring__login:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 6px 14px rgba(56, 91, 205, 0.12);
}

.popup-monitoring__actions button:disabled,
.popup-monitoring__login:disabled {
  cursor: not-allowed;
  opacity: 0.6;
  transform: none;
  box-shadow: none;
}

.popup-monitoring__message {
  margin: 0;
  padding: 10px 12px;
  border-radius: 12px;
  background: rgba(67, 102, 215, 0.08);
  color: #4d6180;
  font-size: 12px;
  font-weight: 600;
}

.popup-monitoring__list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.popup-monitoring__item {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  align-items: center;
  gap: 10px;
  padding: 12px;
  border: 1px solid rgba(223, 230, 240, 0.92);
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.88);
}

.popup-monitoring__item.is-success {
  border-color: rgba(56, 176, 142, 0.22);
}

.popup-monitoring__item.is-danger {
  border-color: rgba(226, 104, 104, 0.2);
}

.popup-monitoring__item.is-pending {
  border-color: rgba(232, 188, 73, 0.2);
}

.popup-monitoring__identity {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
}

.popup-monitoring__logo {
  display: grid;
  place-items: center;
  width: 38px;
  height: 38px;
  border-radius: 12px;
  background: color-mix(in srgb, var(--monitoring-accent) 12%, white);
  color: var(--monitoring-accent);
  font-size: 18px;
  font-weight: 900;
}

.popup-monitoring__copy {
  min-width: 0;
}

.popup-monitoring__copy strong,
.popup-monitoring__copy span,
.popup-monitoring__meta em,
.popup-monitoring__meta small {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.popup-monitoring__copy strong {
  color: #223244;
  font-size: 13px;
  font-weight: 800;
}

.popup-monitoring__copy span {
  margin-top: 3px;
  color: #7c8a9c;
  font-size: 11px;
  font-weight: 600;
}

.popup-monitoring__meta {
  min-width: 0;
  text-align: right;
}

.popup-monitoring__meta em {
  color: #2a405e;
  font-size: 12px;
  font-style: normal;
  font-weight: 800;
}

.popup-monitoring__meta small {
  margin-top: 4px;
  color: #8895a6;
  font-size: 11px;
  font-weight: 600;
}

.popup-debug {
  margin-top: 12px;
  border: 1px solid rgba(216, 225, 238, 0.95);
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.7);
}

.popup-debug summary {
  padding: 12px 14px;
  color: #76859a;
  font-size: 13px;
  font-weight: 800;
  cursor: pointer;
}

.popup-debug dl {
  margin: 0;
  padding: 0 14px 14px;
}

.popup-debug dl div + div {
  margin-top: 10px;
}

.popup-debug dt {
  color: #8b97a8;
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
}

.popup-debug dd {
  margin: 6px 0 0;
  color: #526275;
  font-size: 12px;
  font-weight: 600;
  word-break: break-all;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
