<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" 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.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.newPassword)">copy</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. If your login ever fails, rotate an app password and re-sync.
        </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 class="actions">
          <button class="primary" type="button" :disabled="jellyfin.rotating" @click="rotateJellyfin">
            {{ jellyfin.rotating ? "Rotating..." : "Rotate Jellyfin app password" }}
          </button>
        </div>
        <div v-if="jellyfin.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(jellyfin.newPassword)">copy</button>
          </div>
          <div class="mono secret">{{ jellyfin.newPassword }}</div>
          <div class="hint mono">Use your Keycloak username and this password on Jellyfin.</div>
        </div>
        <div v-if="jellyfin.error" class="error-box">
          <div class="mono">{{ jellyfin.error }}</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 } 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: "",
  rotating: false,
  newPassword: "",
  error: "",
});

const jellyfin = reactive({
  status: "loading",
  username: "",
  rotating: false,
  newPassword: "",
  error: "",
});

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

onMounted(async () => {
  if (!auth.authenticated) {
    mailu.status = "login required";
    jellyfin.status = "login required";
    return;
  }

  await refreshOverview();
});

async function refreshOverview() {
  try {
    const resp = await authFetch("/api/account/overview", { headers: { Accept: "application/json" } });
    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.username;
    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 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 || "";
    mailu.status = "updated";
  } catch (err) {
    mailu.error = err.message || "Rotation failed";
  } finally {
    mailu.rotating = false;
  }
}

async function rotateJellyfin() {
  jellyfin.error = "";
  jellyfin.newPassword = "";
  jellyfin.rotating = true;
  try {
    const resp = await authFetch("/api/account/jellyfin/rotate", { method: "POST" });
    const data = await resp.json().catch(() => ({}));
    if (!resp.ok) throw new Error(data.error || `status ${resp.status}`);
    jellyfin.newPassword = data.password || "";
    jellyfin.status = "updated";
  } catch (err) {
    jellyfin.error = err.message || "Rotation failed";
  } finally {
    jellyfin.rotating = false;
  }
}

async function copy(text) {
  if (!text) return;
  try {
    await navigator.clipboard.writeText(text);
  } 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 {
  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;
}

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