<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>
        <button v-else class="pill mono" type="button" @click="doLogin">Login</button>
      </div>
    </section>

    <section v-if="auth.ready && auth.authenticated">
      <div class="grid two">
        <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">Username</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>

        <div class="card module">
        <div class="module-head">
          <h2>Jellyfin</h2>
          <span class="pill mono">{{ 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>
      </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, 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: "",
  error: "",
});

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

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

const copied = reactive({});

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

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

async function refreshOverview() {
  mailu.error = "";
  jellyfin.error = "";
  try {
    const resp = await authFetch("/api/account/overview", {
      headers: { Accept: "application/json" },
      cache: "no-store",
    });
    if (!resp.ok) throw new 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 || "";
    jellyfin.status = data.jellyfin?.status || "ready";
    jellyfin.username = data.jellyfin?.username || auth.username;
  } catch (err) {
    mailu.status = "unavailable";
    jellyfin.status = "unavailable";
    mailu.error = "Failed to load account status.";
    jellyfin.error = "Failed to load account status.";
  }
}

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";
    }
  } catch (err) {
    mailu.error = err.message || "Rotation failed";
  } finally {
    mailu.rotating = 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;
}

.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;
}

.grid.two {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-top: 12px;
}

.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;
}

.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) {
  .grid.two {
    grid-template-columns: 1fr;
  }
}

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