<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="noopener 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="noopener 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 ? "Resetting..." : "Reset 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">
          <WolfAccountCard
            :wolf="wolf"
            @admin-unlock="adminUnlockWolfIp"
            @game-mode="setWolfGameMode"
            @pair="pairWolf"
            @refresh="refreshWolf"
            @unlock="unlockWolf"
          />

          <div class="card module" :style="{ order: vaultwardenOrder }">
            <div class="module-head">
              <h2>Vaultwarden</h2>
              <span
                class="pill mono"
                :class="
                  vaultwardenReady
                    ? 'pill-ok'
                    : vaultwarden.status === 'unavailable' || vaultwarden.status === 'error'
                      ? 'pill-bad'
                      : ''
                "
              >
                {{ vaultwardenDisplayStatus }}
              </span>
            </div>
            <p v-if="!vaultwardenReady" 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="noopener 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" :style="{ order: 1 }">
            <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="noopener 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" :style="{ order: 2 }">
            <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="noopener 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 WolfAccountCard from "../components/WolfAccountCard.vue";
import { useAccountDashboard } from "../account/useAccountDashboard";

const {
  auth,
  mailu,
  jellyfin,
  vaultwarden,
  nextcloudMail,
  wger,
  firefly,
  wolf,
  admin,
  onboardingUrl,
  vaultwardenReady,
  vaultwardenDisplayStatus,
  vaultwardenOrder,
  doLogin,
  copied,
  hasFlag,
  formatName,
  toggleFlag,
  rotateMailu,
  resetWger,
  resetFirefly,
  syncNextcloudMail,
  refreshWolf,
  unlockWolf,
  pairWolf,
  setWolfGameMode,
  adminUnlockWolfIp,
  approve,
  deny,
  copy,
} = useAccountDashboard();
</script>

<style scoped src="../styles/account.css"></style>
