<template>
  <div class="page">
    <section class="card hero glass">
      <div>
        <p class="eyebrow">Atlas</p>
        <h1>Account</h1>
        <p class="lede">
          Self-service tools for services that don't support seamless Single Sign-On. This portal helps keep everything in
          sync with your Keycloak identity.
        </p>
      </div>
      <div class="hero-actions">
        <div v-if="auth.authenticated" class="pill mono pill-ok">{{ auth.username }}</div>
        <a
          v-if="auth.authenticated && auth.accountPasswordUrl"
          class="pill mono"
          :href="auth.accountPasswordUrl"
          target="_blank"
          rel="noreferrer"
        >
          Change password
        </a>
        <button v-else class="pill mono" type="button" @click="doLogin">Login</button>
        <a class="pill mono" :href="onboardingUrl">Onboarding</a>
      </div>
    </section>

    <section v-if="auth.ready && auth.authenticated">
      <div class="account-grid">
        <div class="account-column">
          <div class="card module">
            <div class="module-head">
              <h2>Firefly III</h2>
              <span
                class="pill mono"
                :class="
                  firefly.status === 'ready'
                    ? 'pill-ok'
                    : firefly.status === 'needs provisioning' || firefly.status === 'login required'
                      ? 'pill-warn'
                      : firefly.status === 'unavailable' || firefly.status === 'error'
                        ? 'pill-bad'
                        : ''
                "
              >
                {{ firefly.status }}
              </span>
            </div>
            <p class="muted">
              Personal finance manager for budgets and spending. Sign in with the email below and set the server URL to
              money.bstein.dev in the Abacus mobile app.
            </p>
            <div class="kv">
              <div class="row">
                <span class="k mono">URL</span>
                <a class="v mono link" href="https://money.bstein.dev" target="_blank" rel="noreferrer">
                  money.bstein.dev
                </a>
              </div>
              <div class="row">
                <span class="k mono">Email</span>
                <span class="v mono">{{ firefly.username || auth.email || auth.username }}</span>
              </div>
              <div class="row">
                <span class="k mono">Password updated</span>
                <span class="v mono">{{ firefly.passwordUpdatedAt || "unknown" }}</span>
              </div>
            </div>
            <div class="actions">
              <button class="primary" type="button" :disabled="firefly.resetting" @click="resetFirefly">
                {{ firefly.resetting ? "Resetting..." : "Reset Firefly password" }}
              </button>
            </div>
            <div v-if="firefly.password" class="secret-box">
              <div class="secret-head">
                <div class="pill mono">Password</div>
                <div class="secret-actions">
                  <button class="copy mono" type="button" @click="copy('firefly-password', firefly.password)">
                    copy
                    <span v-if="copied['firefly-password']" class="copied">copied</span>
                  </button>
                  <button class="copy mono" type="button" @click="firefly.revealPassword = !firefly.revealPassword">
                    {{ firefly.revealPassword ? "hide" : "show" }}
                  </button>
                </div>
              </div>
              <div class="mono secret">{{ firefly.revealPassword ? firefly.password : "••••••••••••••••" }}</div>
              <div class="hint mono">Use this in Firefly III and the Abacus app.</div>
            </div>
            <div v-else class="hint mono">No password available yet. Try resetting or check back later.</div>
            <div v-if="firefly.error" class="error-box">
              <div class="mono">{{ firefly.error }}</div>
            </div>
          </div>

          <div class="card module">
            <div class="module-head">
              <h2>Mail</h2>
              <span class="pill mono">{{ mailu.status }}</span>
            </div>
            <p class="muted">
              Use a dedicated app password for IMAP/SMTP clients (mobile mail, Thunderbird, Outlook). Rotate it any time.
            </p>
            <div class="kv">
              <div class="row">
                <span class="k mono">IMAP</span>
                <span class="v mono">{{ mailu.imap }}</span>
              </div>
              <div class="row">
                <span class="k mono">SMTP</span>
                <span class="v mono">{{ mailu.smtp }}</span>
              </div>
              <div class="row">
                <span class="k mono">Email</span>
                <span class="v mono">{{ mailu.username }}</span>
              </div>
            </div>

            <div class="actions">
              <button class="primary" type="button" :disabled="mailu.rotating" @click="rotateMailu">
                {{ mailu.rotating ? "Rotating..." : "Rotate mail app password" }}
              </button>
            </div>

            <div v-if="mailu.currentPassword" class="secret-box">
              <div class="secret-head">
                <div class="pill mono">Current password</div>
                <div class="secret-actions">
                  <button class="copy mono" type="button" @click="copy('mailu-current', mailu.currentPassword)">
                    copy
                    <span v-if="copied['mailu-current']" class="copied">copied</span>
                  </button>
                  <button class="copy mono" type="button" @click="mailu.revealPassword = !mailu.revealPassword">
                    {{ mailu.revealPassword ? "hide" : "show" }}
                  </button>
                </div>
              </div>
              <div class="mono secret">{{ mailu.revealPassword ? mailu.currentPassword : "••••••••••••••••" }}</div>
              <div class="hint mono">Use this in your mail client (IMAP/SMTP).</div>
            </div>

            <div v-else class="hint mono">No app password set yet. Rotate to generate one.</div>

            <div v-if="mailu.newPassword" class="secret-box">
              <div class="secret-head">
                <div class="pill mono pill-warn">Show once</div>
                <button class="copy mono" type="button" @click="copy('mailu-new', mailu.newPassword)">
                  copy
                  <span v-if="copied['mailu-new']" class="copied">copied</span>
                </button>
              </div>
              <div class="mono secret">{{ mailu.newPassword }}</div>
              <div class="hint mono">Update your mail client password to match.</div>
            </div>

            <div v-if="mailu.error" class="error-box">
              <div class="mono">{{ mailu.error }}</div>
            </div>

            <div class="divider"></div>

            <div class="module-head subhead">
              <h3>Nextcloud Mail</h3>
              <span class="pill mono">{{ nextcloudMail.status }}</span>
            </div>
            <p class="muted">
              Syncs your Nextcloud Mail app with your Mailu mailbox (dedupes accounts and keeps the app password updated).
            </p>
            <div class="kv">
              <div class="row">
                <span class="k mono">Primary</span>
                <span class="v mono">{{ nextcloudMail.primaryEmail || mailu.username }}</span>
              </div>
              <div class="row">
                <span class="k mono">Accounts</span>
                <span class="v mono">{{ nextcloudMail.accountCount || "0" }}</span>
              </div>
              <div class="row">
                <span class="k mono">Synced</span>
                <span class="v mono">{{ nextcloudMail.syncedAt || "never" }}</span>
              </div>
            </div>
            <div class="actions">
              <button class="primary" type="button" :disabled="nextcloudMail.syncing" @click="syncNextcloudMail">
                {{ nextcloudMail.syncing ? "Syncing..." : "Sync Nextcloud Mail now" }}
              </button>
            </div>
            <div v-if="nextcloudMail.error" class="error-box">
              <div class="mono">{{ nextcloudMail.error }}</div>
            </div>
          </div>
        </div>

        <div class="account-stack">
          <div class="card module">
            <div class="module-head">
              <h2>Vaultwarden</h2>
              <span
                class="pill mono"
                :class="
                  vaultwarden.status === 'ready' || vaultwarden.status === 'already_present'
                    ? 'pill-ok'
                    : vaultwarden.status === 'unavailable' || vaultwarden.status === 'error'
                      ? 'pill-bad'
                      : ''
                "
              >
                {{ vaultwarden.status }}
              </span>
            </div>
            <p v-if="vaultwarden.status !== 'ready' && vaultwarden.status !== 'already_present'" class="muted">
              Password manager for Atlas accounts. Store your Element recovery key here. Signups are admin-provisioned.
            </p>
            <div class="kv">
              <div class="row">
                <span class="k mono">URL</span>
                <a class="v mono link" href="https://vault.bstein.dev" target="_blank" rel="noreferrer">vault.bstein.dev</a>
              </div>
              <div class="row">
                <span class="k mono">Username</span>
                <span class="v mono">{{ vaultwarden.username }}</span>
              </div>
              <div class="row">
                <span class="k mono">Synced</span>
                <span class="v mono">{{ vaultwarden.syncedAt || "never" }}</span>
              </div>
            </div>
            <div v-if="vaultwarden.status === 'invited'" class="hint mono">
              Invitation created. Open Vaultwarden and complete setup by choosing a master password.
            </div>
            <div v-if="vaultwarden.error" class="error-box">
              <div class="mono">{{ vaultwarden.error }}</div>
            </div>
          </div>

          <div class="card module">
            <div class="module-head">
              <h2>Wger</h2>
              <span
                class="pill mono"
                :class="
                  wger.status === 'ready'
                    ? 'pill-ok'
                    : wger.status === 'needs provisioning' || wger.status === 'login required'
                      ? 'pill-warn'
                      : wger.status === 'unavailable' || wger.status === 'error'
                        ? 'pill-bad'
                        : ''
                "
              >
                {{ wger.status }}
              </span>
            </div>
            <p class="muted">
              Workout + nutrition tracking with the wger mobile app. Sign in with the credentials below and set the server
              URL to health.bstein.dev in the app.
            </p>
            <div class="kv">
              <div class="row">
                <span class="k mono">URL</span>
                <a class="v mono link" href="https://health.bstein.dev" target="_blank" rel="noreferrer">
                  health.bstein.dev
                </a>
              </div>
              <div class="row">
                <span class="k mono">Username</span>
                <span class="v mono">{{ wger.username || auth.username }}</span>
              </div>
              <div class="row">
                <span class="k mono">Password updated</span>
                <span class="v mono">{{ wger.passwordUpdatedAt || "unknown" }}</span>
              </div>
            </div>
            <div class="actions">
              <button class="primary" type="button" :disabled="wger.resetting" @click="resetWger">
                {{ wger.resetting ? "Resetting..." : "Reset wger password" }}
              </button>
            </div>
            <div v-if="wger.password" class="secret-box">
              <div class="secret-head">
                <div class="pill mono">Password</div>
                <div class="secret-actions">
                  <button class="copy mono" type="button" @click="copy('wger-password', wger.password)">
                    copy
                    <span v-if="copied['wger-password']" class="copied">copied</span>
                  </button>
                  <button class="copy mono" type="button" @click="wger.revealPassword = !wger.revealPassword">
                    {{ wger.revealPassword ? "hide" : "show" }}
                  </button>
                </div>
              </div>
              <div class="mono secret">{{ wger.revealPassword ? wger.password : "••••••••••••••••" }}</div>
              <div class="hint mono">Use this in the wger mobile app and web UI.</div>
            </div>
            <div v-else class="hint mono">No password available yet. Try resetting or check back later.</div>
            <div v-if="wger.error" class="error-box">
              <div class="mono">{{ wger.error }}</div>
            </div>
          </div>

          <div class="card module">
            <div class="module-head">
              <h2>Jellyfin</h2>
              <span
                class="pill mono"
                :class="jellyfin.syncStatus === 'ok' ? 'pill-ok' : jellyfin.syncStatus === 'degraded' ? 'pill-bad' : ''"
              >
                {{
                  jellyfin.syncStatus === "ok"
                    ? "in sync"
                    : jellyfin.syncStatus === "degraded"
                      ? "out of sync"
                      : jellyfin.status
                }}
              </span>
            </div>
            <p class="muted">
              Jellyfin authentication is backed by LDAP (Keycloak is the source of truth). Use your Keycloak username and
              password.
            </p>
            <div class="kv">
              <div class="row">
                <span class="k mono">URL</span>
                <a class="v mono link" href="https://stream.bstein.dev" target="_blank" rel="noreferrer">
                  stream.bstein.dev
                </a>
              </div>
              <div class="row">
                <span class="k mono">Username</span>
                <span class="v mono">{{ jellyfin.username }}</span>
              </div>
            </div>
            <div v-if="jellyfin.error" class="error-box">
              <div class="mono">{{ jellyfin.error }}</div>
            </div>
            <div v-if="jellyfin.syncDetail" class="hint mono jellyfin-detail">{{ jellyfin.syncDetail }}</div>
          </div>
        </div>
      </div>

      <div v-if="admin.enabled" class="card module admin">
        <div class="module-head">
          <h2>Admin Approvals</h2>
          <span class="pill mono">{{ admin.loading ? "loading..." : `${admin.requests.length} pending` }}</span>
        </div>
        <p class="muted">Approve or deny pending access requests.</p>

        <div v-if="admin.error" class="error-box">
          <div class="mono">{{ admin.error }}</div>
        </div>

        <div v-if="!admin.loading && admin.requests.length === 0" class="muted">No pending requests.</div>

        <div v-else class="requests">
          <div class="req-head mono">
            <span>User</span>
            <span>Email</span>
            <span>Note</span>
            <span></span>
          </div>
          <div v-for="req in admin.requests" :key="req.username" class="req-row">
            <div class="mono">{{ req.username }}</div>
            <div class="mono">{{ req.email }}</div>
            <div class="note">{{ req.note }}</div>
            <div class="req-actions">
              <button class="primary" type="button" :disabled="admin.acting[req.username]" @click="approve(req.username)">
                approve
              </button>
              <button class="pill mono" type="button" :disabled="admin.acting[req.username]" @click="deny(req.username)">
                deny
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>

    <section v-else class="card module">
      <h2>Login required</h2>
      <p class="muted">Log in to manage app passwords and view account status.</p>
      <div class="actions">
        <button class="primary" type="button" @click="doLogin">Login</button>
      </div>
    </section>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from "vue";
import { auth, authFetch, login } from "@/auth";

const mailu = reactive({
  status: "loading",
  imap: "mail.bstein.dev:993 (TLS)",
  smtp: "mail.bstein.dev:587 (STARTTLS)",
  username: "",
  currentPassword: "",
  revealPassword: false,
  rotating: false,
  newPassword: "",
  error: "",
});

const jellyfin = reactive({
  status: "loading",
  username: "",
  syncStatus: "",
  syncDetail: "",
  error: "",
});

const vaultwarden = reactive({
  status: "loading",
  username: "",
  syncedAt: "",
  error: "",
});

const nextcloudMail = reactive({
  status: "loading",
  primaryEmail: "",
  accountCount: "",
  syncedAt: "",
  syncing: false,
  error: "",
});

const wger = reactive({
  status: "loading",
  username: "",
  password: "",
  passwordUpdatedAt: "",
  revealPassword: false,
  resetting: false,
  error: "",
});

const firefly = reactive({
  status: "loading",
  username: "",
  password: "",
  passwordUpdatedAt: "",
  revealPassword: false,
  resetting: false,
  error: "",
});

const admin = reactive({
  enabled: false,
  loading: false,
  requests: [],
  error: "",
  acting: {},
});
const onboardingUrl = ref("/onboarding");

const doLogin = () => login("/account");

const copied = reactive({});

onMounted(() => {
  if (auth.ready && auth.authenticated) {
    refreshOverview();
    refreshAdminRequests();
  } else {
    mailu.status = "login required";
    nextcloudMail.status = "login required";
    jellyfin.status = "login required";
    vaultwarden.status = "login required";
    wger.status = "login required";
    firefly.status = "login required";
  }
});

watch(
  () => [auth.ready, auth.authenticated],
  ([ready, authenticated]) => {
    if (!ready) return;
    if (!authenticated) {
      mailu.status = "login required";
      nextcloudMail.status = "login required";
      jellyfin.status = "login required";
      vaultwarden.status = "login required";
      wger.status = "login required";
      firefly.status = "login required";
      onboardingUrl.value = "/onboarding";
      admin.enabled = false;
      admin.requests = [];
      return;
    }
    refreshOverview();
    refreshAdminRequests();
  },
  { immediate: false },
);

async function refreshOverview() {
  mailu.error = "";
  jellyfin.error = "";
  vaultwarden.error = "";
  nextcloudMail.error = "";
  wger.error = "";
  firefly.error = "";
  try {
    const resp = await authFetch("/api/account/overview", {
      headers: { Accept: "application/json" },
      cache: "no-store",
    });
    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(data?.error || `status ${resp.status}`);
    }
    const data = await resp.json();
    mailu.status = data.mailu?.status || "ready";
    mailu.username = data.mailu?.username || auth.email || auth.username;
    mailu.currentPassword = data.mailu?.app_password || "";
    nextcloudMail.status = data.nextcloud_mail?.status || "unknown";
    nextcloudMail.primaryEmail = data.nextcloud_mail?.primary_email || "";
    nextcloudMail.accountCount = data.nextcloud_mail?.account_count || "";
    nextcloudMail.syncedAt = data.nextcloud_mail?.synced_at || "";
    wger.status = data.wger?.status || "unknown";
    wger.username = data.wger?.username || auth.username;
    wger.password = data.wger?.password || "";
    wger.passwordUpdatedAt = data.wger?.password_updated_at || "";
    firefly.status = data.firefly?.status || "unknown";
    firefly.username = data.firefly?.username || auth.email || auth.username;
    firefly.password = data.firefly?.password || "";
    firefly.passwordUpdatedAt = data.firefly?.password_updated_at || "";
    vaultwarden.status = data.vaultwarden?.status || "unknown";
    vaultwarden.username = data.vaultwarden?.username || auth.email || auth.username;
    vaultwarden.syncedAt = data.vaultwarden?.synced_at || "";
    jellyfin.status = data.jellyfin?.status || "ready";
    jellyfin.username = data.jellyfin?.username || auth.username;
    jellyfin.syncStatus = data.jellyfin?.sync_status || "";
    jellyfin.syncDetail = data.jellyfin?.sync_detail || "";
    onboardingUrl.value = data.onboarding_url || "/onboarding";
  } catch (err) {
    mailu.status = "unavailable";
    nextcloudMail.status = "unavailable";
    wger.status = "unavailable";
    firefly.status = "unavailable";
    vaultwarden.status = "unavailable";
    jellyfin.status = "unavailable";
    jellyfin.syncStatus = "";
    jellyfin.syncDetail = "";
    onboardingUrl.value = "/onboarding";
    const message = err?.message ? `Failed to load account status (${err.message})` : "Failed to load account status.";
    mailu.error = message;
    nextcloudMail.error = message;
    wger.error = message;
    firefly.error = message;
    vaultwarden.error = message;
    jellyfin.error = message;
  }
}

async function refreshAdminRequests() {
  admin.error = "";
  admin.loading = true;
  try {
    const resp = await authFetch("/api/admin/access/requests", {
      headers: { Accept: "application/json" },
      cache: "no-store",
    });
    if (resp.status === 403) {
      admin.enabled = false;
      admin.requests = [];
      return;
    }
    if (!resp.ok) throw new Error(`status ${resp.status}`);
    const data = await resp.json();
    admin.enabled = true;
    admin.requests = Array.isArray(data.requests) ? data.requests : [];
  } catch (err) {
    admin.enabled = false;
    admin.requests = [];
    admin.error = err.message || "Failed to load access requests.";
  } finally {
    admin.loading = false;
  }
}

async function rotateMailu() {
  mailu.error = "";
  mailu.newPassword = "";
  mailu.rotating = true;
  try {
    const resp = await authFetch("/api/account/mailu/rotate", { method: "POST" });
    const data = await resp.json().catch(() => ({}));
    if (!resp.ok) throw new Error(data.error || `status ${resp.status}`);
    mailu.newPassword = data.password || "";
    if (mailu.newPassword) {
      mailu.currentPassword = mailu.newPassword;
      mailu.revealPassword = true;
    }
    const syncEnabled = Boolean(data.sync_enabled);
    const syncOk = Boolean(data.sync_ok);
    const syncError = data.sync_error || "";
    if (!syncEnabled) {
      mailu.status = "updated";
      mailu.error = "Mail sync is not configured; password may not take effect until an admin sync runs.";
    } else if (!syncOk) {
      mailu.status = "sync pending";
      mailu.error = syncError || "Mail sync did not confirm success yet. Try again in a moment.";
    } else {
      mailu.status = "updated";
    }
    await refreshOverview();
  } catch (err) {
    mailu.error = err.message || "Rotation failed";
  } finally {
    mailu.rotating = false;
  }
}

async function resetWger() {
  wger.error = "";
  wger.resetting = true;
  try {
    const resp = await authFetch("/api/account/wger/reset", { method: "POST" });
    const data = await resp.json().catch(() => ({}));
    if (!resp.ok) throw new Error(data.error || `status ${resp.status}`);
    if (data.password) {
      wger.password = data.password;
      wger.revealPassword = true;
    }
    await refreshOverview();
  } catch (err) {
    wger.error = err.message || "Reset failed";
  } finally {
    wger.resetting = false;
  }
}

async function resetFirefly() {
  firefly.error = "";
  firefly.resetting = true;
  try {
    const resp = await authFetch("/api/account/firefly/reset", { method: "POST" });
    const data = await resp.json().catch(() => ({}));
    if (!resp.ok) throw new Error(data.error || `status ${resp.status}`);
    if (data.password) {
      firefly.password = data.password;
      firefly.revealPassword = true;
    }
    await refreshOverview();
  } catch (err) {
    firefly.error = err.message || "Reset failed";
  } finally {
    firefly.resetting = false;
  }
}

async function syncNextcloudMail() {
  nextcloudMail.error = "";
  nextcloudMail.syncing = true;
  try {
    const resp = await authFetch("/api/account/nextcloud/mail/sync", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ wait: true }),
    });
    const data = await resp.json().catch(() => ({}));
    if (!resp.ok) throw new Error(data.error || `status ${resp.status}`);
    await refreshOverview();
  } catch (err) {
    nextcloudMail.error = err.message || "Sync failed";
  } finally {
    nextcloudMail.syncing = false;
  }
}

function fallbackCopy(text) {
  const textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.setAttribute("readonly", "");
  textarea.style.position = "fixed";
  textarea.style.top = "-9999px";
  textarea.style.left = "-9999px";
  document.body.appendChild(textarea);
  textarea.select();
  textarea.setSelectionRange(0, textarea.value.length);
  document.execCommand("copy");
  document.body.removeChild(textarea);
}

async function approve(username) {
  admin.error = "";
  admin.acting[username] = true;
  try {
    const resp = await authFetch(`/api/admin/access/requests/${encodeURIComponent(username)}/approve`, { method: "POST" });
    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(data.error || `status ${resp.status}`);
    }
    await refreshAdminRequests();
  } catch (err) {
    admin.error = err.message || "Approve failed";
  } finally {
    admin.acting[username] = false;
  }
}

async function deny(username) {
  admin.error = "";
  admin.acting[username] = true;
  try {
    const resp = await authFetch(`/api/admin/access/requests/${encodeURIComponent(username)}/deny`, { method: "POST" });
    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(data.error || `status ${resp.status}`);
    }
    await refreshAdminRequests();
  } catch (err) {
    admin.error = err.message || "Deny failed";
  } finally {
    admin.acting[username] = false;
  }
}

async function copy(key, text) {
  if (!text) return;
  try {
    if (navigator?.clipboard?.writeText) {
      await navigator.clipboard.writeText(text);
    } else {
      fallbackCopy(text);
    }
    copied[key] = true;
    window.setTimeout(() => {
      copied[key] = false;
    }, 1500);
  } catch (err) {
    try {
      fallbackCopy(text);
      copied[key] = true;
      window.setTimeout(() => {
        copied[key] = false;
      }, 1500);
    } catch {
      // ignore
    }
  }
}
</script>

<style scoped>
.page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 32px 22px 72px;
}

.hero {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 18px;
  margin-bottom: 12px;
}

.hero-actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-end;
  gap: 28px;
}

.divider {
  height: 1px;
  background: rgba(255, 255, 255, 0.08);
  margin: 18px 0;
}

.subhead h3 {
  margin: 0;
  font-size: 16px;
}

.eyebrow {
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: var(--text-muted);
  margin: 0 0 6px;
  font-size: 13px;
}

h1 {
  margin: 0 0 6px;
  font-size: 32px;
}

.lede {
  margin: 0;
  color: var(--text-muted);
  max-width: 640px;
}

.account-grid {
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
  gap: 12px;
  margin-top: 12px;
  align-items: stretch;
}

.account-column,
.account-stack {
  display: grid;
  gap: 12px;
  align-content: start;
}

.account-column .module,
.account-stack .module {
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.module {
  padding: 18px;
}

.module-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.muted {
  color: var(--text-muted);
  margin: 10px 0 0;
}

.kv {
  margin-top: 12px;
  border: 1px solid var(--card-border);
  border-radius: 12px;
  overflow: hidden;
}

.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 10px 12px;
  background: rgba(255, 255, 255, 0.02);
  border-top: 1px solid rgba(255, 255, 255, 0.06);
}

.row:first-child {
  border-top: none;
}

.k {
  color: var(--text-muted);
}

.v {
  color: var(--text-strong);
}

.link {
  color: var(--accent-cyan);
  text-decoration: none;
}

.actions {
  margin-top: 12px;
  display: flex;
  gap: 10px;
}

button.primary {
  background: linear-gradient(90deg, #4f8bff, #7dd0ff);
  color: #0b1222;
  padding: 10px 14px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 700;
}

.secret-box {
  margin-top: 12px;
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.14);
  background: rgba(255, 255, 255, 0.03);
  padding: 12px;
}

.secret-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-bottom: 8px;
}

.secret-actions {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.secret {
  word-break: break-word;
  color: var(--text-strong);
}

.hint {
  margin-top: 6px;
  color: var(--text-muted);
  font-size: 12px;
}

.jellyfin-detail {
  margin-top: auto;
}

.copy {
  background: transparent;
  border: 1px solid rgba(255, 255, 255, 0.14);
  color: var(--text-primary);
  border-radius: 10px;
  padding: 6px 10px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.copied {
  font-size: 12px;
  color: rgba(120, 255, 160, 0.9);
}

.error-box {
  margin-top: 12px;
  border-radius: 12px;
  border: 1px solid rgba(255, 87, 87, 0.5);
  background: rgba(255, 87, 87, 0.06);
  padding: 10px 12px;
}

@media (max-width: 820px) {
  .account-grid {
    grid-template-columns: 1fr;
  }

  .account-stack .module {
    flex: none;
  }

  .account-column .module {
    flex: none;
  }
}

.admin {
  margin-top: 12px;
}

.requests {
  margin-top: 12px;
  display: grid;
  gap: 10px;
}

.req-head {
  display: grid;
  grid-template-columns: 160px 220px 1fr 140px;
  gap: 12px;
  color: var(--text-muted);
  font-size: 12px;
  letter-spacing: 0.06em;
  text-transform: uppercase;
}

.req-row {
  display: grid;
  grid-template-columns: 160px 220px 1fr 140px;
  gap: 12px;
  align-items: center;
  border: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(0, 0, 0, 0.18);
  border-radius: 14px;
  padding: 10px 12px;
}

.note {
  color: var(--text-muted);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.req-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

@media (max-width: 900px) {
  .req-head {
    display: none;
  }

  .req-row {
    grid-template-columns: 1fr;
    gap: 8px;
    align-items: start;
  }

  .note {
    white-space: normal;
  }

  .req-actions {
    justify-content: flex-start;
  }
}
</style>
