<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 v-for="req in admin.requests" :key="req.username" class="req-row">
            <div class="req-summary">
              <div class="req-label mono">Name</div>
              <div class="mono">{{ formatName(req) }}</div>
              <div class="req-label mono">User</div>
              <div class="mono">{{ req.username }}</div>
              <div class="req-label mono">Email</div>
              <div class="mono">{{ req.email }}</div>
              <div v-if="req.request_code" class="req-label mono">Request code</div>
              <div v-if="req.request_code" class="mono">{{ req.request_code }}</div>
              <div class="req-label mono">Note</div>
              <div class="note">{{ req.note || "no note" }}</div>
            </div>
            <div class="req-flags">
              <div class="req-label mono">Flags</div>
              <div class="req-flag-grid">
                <div v-if="admin.flagsLoading" class="muted">loading flags...</div>
                <label v-for="flag in admin.flags" :key="flag" class="flag-pill">
                  <input
                    type="checkbox"
                    :checked="hasFlag(req.username, flag)"
                    :disabled="admin.acting[req.username]"
                    @change="toggleFlag(req.username, flag, $event)"
                  />
                  <span class="mono">{{ flag }}</span>
                </label>
                <div v-if="!admin.flagsLoading && !admin.flags.length" class="muted">no flags</div>
              </div>
            </div>
            <div class="req-note">
              <div class="req-label mono">Decision note</div>
              <input
                v-model="admin.notes[req.username]"
                class="input mono"
                type="text"
                placeholder="Optional note"
                :disabled="admin.acting[req.username]"
              />
            </div>
            <div class="req-actions">
              <div class="req-label mono">Decision</div>
              <div class="req-action-stack">
                <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>
      </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: {},
  flags: [],
  flagsLoading: false,
  notes: {},
  selectedFlags: {},
});
const onboardingUrl = ref("/onboarding");

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

const copied = reactive({});
onMounted(() => {
  if (auth.ready && auth.authenticated) {
    refreshOverview();
    refreshAdminRequests();
    refreshAdminFlags();
  } 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 = [];
      admin.flags = [];
      return;
    }
    refreshOverview();
    refreshAdminRequests();
    refreshAdminFlags();
  },
  { 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 || mailu.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 || mailu.username || 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 || mailu.username || 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() {
  if (!auth.authenticated) {
    admin.enabled = false;
    admin.requests = [];
    return;
  }
  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 : [];
    for (const req of admin.requests) {
      if (!req?.username) continue;
      if (!(req.username in admin.notes)) admin.notes[req.username] = "";
      if (!(req.username in admin.selectedFlags)) admin.selectedFlags[req.username] = [];
    }
  } catch (err) {
    admin.enabled = false;
    admin.requests = [];
    admin.error = err.message || "Failed to load access requests.";
  } finally {
    admin.loading = false;
  }
}

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

function hasFlag(username, flag) {
  const selected = admin.selectedFlags[username];
  return Array.isArray(selected) && selected.includes(flag);
}

function formatName(req) {
  if (!req) return "unknown";
  const parts = [];
  if (req.first_name && String(req.first_name).trim()) {
    parts.push(String(req.first_name).trim());
  }
  if (req.last_name && String(req.last_name).trim()) {
    parts.push(String(req.last_name).trim());
  }
  return parts.length ? parts.join(" ") : "unknown";
}

function toggleFlag(username, flag, event) {
  const checked = Boolean(event?.target?.checked);
  const selected = Array.isArray(admin.selectedFlags[username]) ? [...admin.selectedFlags[username]] : [];
  const next = checked ? Array.from(new Set([...selected, flag])) : selected.filter((item) => item !== flag);
  admin.selectedFlags[username] = next;
}

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 flags = Array.isArray(admin.selectedFlags[username]) ? admin.selectedFlags[username] : [];
    const note = (admin.notes[username] || "").trim();
    const payload = {};
    if (flags.length) payload.flags = flags;
    if (note) payload.note = note;
    const resp = await authFetch(`/api/admin/access/requests/${encodeURIComponent(username)}/approve`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    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 note = (admin.notes[username] || "").trim();
    const payload = note ? { note } : {};
    const resp = await authFetch(`/api/admin/access/requests/${encodeURIComponent(username)}/deny`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    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-row {
  display: grid;
  grid-template-columns: minmax(220px, 1.2fr) minmax(200px, 1fr) minmax(200px, 1fr) minmax(140px, 0.6fr);
  gap: 16px;
  align-items: start;
  border: 1px solid rgba(255, 255, 255, 0.08);
  background: rgba(0, 0, 0, 0.18);
  border-radius: 14px;
  padding: 10px 12px;
}

.req-summary {
  display: grid;
  gap: 6px;
}

.req-label {
  color: var(--text-muted);
  font-size: 11px;
  letter-spacing: 0.06em;
  text-transform: uppercase;
}

.req-flags {
  display: grid;
  gap: 8px;
  align-content: start;
}

.req-flag-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

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

.flag-pill {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  border-radius: 999px;
  border: 1px solid rgba(255, 255, 255, 0.12);
  background: rgba(0, 0, 0, 0.2);
  font-size: 12px;
}

.flag-pill input {
  width: 14px;
  height: 14px;
}

.req-note .input {
  width: 100%;
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.14);
  background: rgba(0, 0, 0, 0.22);
  color: var(--text-primary);
  padding: 8px 10px;
}

.req-actions {
  display: grid;
  gap: 8px;
  align-content: start;
}

.req-action-stack {
  display: grid;
  gap: 8px;
}

@media (max-width: 900px) {
  .req-row {
    grid-template-columns: 1fr;
    gap: 12px;
    align-items: start;
  }

  .note {
    white-space: normal;
  }
}
</style>
