<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 { 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 installationKey = ref("");
const installationId = ref<number | null>(null);
const apiBaseUrl = ref<string | null>(null);
const platforms = ref<StoredPlatformState[]>([]);

const connectedCount = computed(() => platforms.value.filter((item) => item.connected).length);

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 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 {
    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);
  } finally {
    loading.value = false;
  }
}

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

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;
  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");
    }
    const state = await getExtensionState();
    installationId.value = state.plugin_installation_id;
    apiBaseUrl.value = state.api_base_url;
    platforms.value = clonePlatforms(state.platforms);
  } finally {
    refreshing.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>

        <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>
          </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-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>
