<template>
  <NuxtLayout name="default">
    <div class="dashboard-container">
      <header class="dashboard-header">
        <div class="header-copy">
          <p class="section-kicker">Operations</p>
          <h1 class="font-display text-3xl font-bold tracking-tight text-m-text">
            Backup
          </h1>
          <p class="header-description">
            Centralisez la selection des dossiers, l'execution des scripts et le telechargement
            des fichiers depuis une seule vue.
          </p>
        </div>
      </header>
      <div class="dashboard-grid">
        <section class="grid-left" aria-label="Commandes de sauvegarde">
          <BackupButtonSee
            class="animate-fade-in-up backup-selector"
            style="animation-delay: 120ms"
            @select="selectedBackup = $event"
          />
          <BackupRun
            class="animate-fade-in-up"
            style="animation-delay: 180ms"
            @result="handleScriptResult"
          />
        </section>

        <section class="grid-middle" aria-labelledby="backup-files-title">
          <div class="files-panel animate-fade-in-up" style="animation-delay: 240ms">
            <div class="files-panel-header">
              <div>
                <p class="section-kicker">Fichiers</p>
                <h2 id="backup-files-title" class="files-panel-title">
                  Historique des sauvegardes
                </h2>
              </div>
              <p class="files-panel-meta">
                {{ selectedBackup ? `Source ${selectedBackup}` : "En attente de selection" }}
              </p>
            </div>

            <BackupList
              class="backup-list-mobile"
              :folder="selectedBackup"
            />
          </div>

          <section
            class="files-panel output-panel animate-fade-in-up"
            style="animation-delay: 300ms"
            aria-labelledby="backup-output-title"
          >
            <div class="files-panel-header">
              <div>
                <p class="section-kicker">Execution</p>
                <h2 id="backup-output-title" class="files-panel-title">Resultat du script</h2>
              </div>
              <span
                class="panel-badge"
                :class="{
                  'panel-badge-idle': !scriptResult.label,
                  'panel-badge-success': scriptResult.label && !scriptResult.isError,
                  'panel-badge-error': scriptResult.isError
                }"
              >
                {{ scriptResult.label || "Pret" }}
              </span>
            </div>

            <div
              v-if="!scriptResult.output"
              class="output-empty"
              role="status"
              aria-live="polite"
            >
              <p class="output-empty-title">Aucune sortie disponible</p>
              <p class="output-empty-text">
                Lancez un script depuis le panneau de gauche pour afficher son retour ici.
              </p>
            </div>

            <pre
              v-else
              class="output-console"
              :class="{ 'output-console-error': scriptResult.isError }"
            >{{ scriptResult.output }}</pre>
          </section>
        </section>
      </div>
    </div>
  </NuxtLayout>
</template>

<script setup lang="ts">
import { ref } from "vue"
import BackupRun from "~/components/BackupRun.vue"

definePageMeta({ layout: false })

type ScriptResult = {
  key: string | null
  label: string
  output: string
  isError: boolean
  downloadFolders: string[]
}

const emptyScriptResult = (): ScriptResult => ({
  key: null,
  label: "",
  output: "",
  isError: false,
  downloadFolders: []
})

const selectedBackup = ref<string | null>(null)
const scriptResult = ref<ScriptResult>(emptyScriptResult())

const fetchLatestBackup = async (folder: string) => {
  const files = await $fetch<string[]>(`/api/backups?folder=${encodeURIComponent(folder)}`)
  return files[0] || null
}

const triggerDownload = (folder: string, file: string) => {
  const link = document.createElement("a")
  link.href = `/api/download?folder=${encodeURIComponent(folder)}&file=${encodeURIComponent(file)}`
  link.style.display = "none"
  document.body.appendChild(link)
  link.click()
  link.remove()
}

const downloadLatestBackup = async (folder: string) => {
  const latestFile = await fetchLatestBackup(folder)

  if (latestFile) {
    triggerDownload(folder, latestFile)
  }
}

const handleScriptResult = async (payload: ScriptResult) => {
  scriptResult.value = { ...emptyScriptResult(), ...payload }

  if (payload.isError || payload.downloadFolders.length === 0) {
    return
  }

  for (const folder of payload.downloadFolders) {
    try {
      await downloadLatestBackup(folder)
    } catch (error) {
      console.error(`Erreur telechargement automatique pour ${folder}:`, error)
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 2rem 2.5rem;
}

.dashboard-header {
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(260px, 320px);
  gap: 1.5rem;
  align-items: end;
  margin-bottom: 1.5rem;
}

.header-copy {
  min-width: 0;
}

.section-kicker {
  margin: 0 0 0.5rem;
  font-family: var(--font-mono);
  font-size: 0.7rem;
  letter-spacing: 0.18em;
  text-transform: uppercase;
  color: rgb(var(--m-accent));
}

.header-description {
  max-width: 62ch;
  margin-top: 0.9rem;
  color: rgb(var(--m-muted));
  line-height: 1.65;
}

.dashboard-grid {
  display: grid;
  grid-template-columns: 300px minmax(0, 1fr);
  gap: 1.5rem;
  align-items: start;
}

.grid-left,
.grid-middle {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  min-width: 0;
}

.files-panel {
  padding: 1.25rem;
  border-radius: 20px;
  background: rgb(var(--m-secondary) / 0.4);
  border: 1px solid rgb(var(--m-accent) / 0.08);
}

.output-panel {
  min-height: 220px;
}

.files-panel-header {
  display: flex;
  align-items: end;
  justify-content: space-between;
  gap: 1rem;
  margin-bottom: 1rem;
}

.files-panel-title {
  margin: 0;
  font-family: var(--font-display);
  font-size: 1.4rem;
  font-weight: 700;
  color: rgb(var(--m-text));
}

.files-panel-meta {
  margin: 0;
  font-family: var(--font-mono);
  font-size: 0.75rem;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  color: rgb(var(--m-muted));
  text-align: right;
}

.panel-badge {
  display: inline-flex;
  align-items: center;
  border-radius: 999px;
  padding: 0.35rem 0.7rem;
  font-family: var(--font-mono);
  font-size: 0.68rem;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  border: 1px solid transparent;
}

.panel-badge-idle {
  color: rgb(var(--m-muted));
  background: rgb(var(--m-tertiary) / 0.45);
  border-color: rgb(var(--m-border) / 0.25);
}

.panel-badge-success {
  color: rgb(var(--m-success));
  background: rgb(var(--m-success) / 0.08);
  border-color: rgb(var(--m-success) / 0.18);
}

.panel-badge-error {
  color: rgb(var(--m-error));
  background: rgb(var(--m-error) / 0.08);
  border-color: rgb(var(--m-error) / 0.18);
}

.output-empty {
  display: flex;
  min-height: 132px;
  flex-direction: column;
  justify-content: center;
  border-radius: 14px;
  border: 1px dashed rgb(var(--m-border) / 0.55);
  background: rgb(var(--m-tertiary) / 0.38);
  padding: 1.25rem;
}

.output-empty-title {
  margin: 0;
  font-family: var(--font-display);
  font-size: 1rem;
  font-weight: 700;
  color: rgb(var(--m-text));
}

.output-empty-text {
  margin: 0.5rem 0 0;
  max-width: 52ch;
  color: rgb(var(--m-muted));
  line-height: 1.65;
}

.output-console {
  margin: 0;
  min-height: 132px;
  overflow-x: auto;
  border-radius: 14px;
  border: 1px solid rgb(var(--m-border) / 0.3);
  background:
    linear-gradient(180deg, rgb(var(--m-bg) / 0.96), rgb(var(--m-secondary) / 0.92));
  padding: 1rem 1.1rem;
  font-family: var(--font-mono);
  font-size: 0.78rem;
  line-height: 1.7;
  white-space: pre-wrap;
  word-break: break-word;
  color: rgb(var(--m-success));
}

.output-console-error {
  color: rgb(var(--m-error));
}

@media (max-width: 1180px) {
  .dashboard-header,
  .dashboard-grid {
    grid-template-columns: 1fr;
  }

  .files-panel-header {
    align-items: flex-start;
    flex-direction: column;
  }

  .files-panel-meta {
    text-align: left;
  }
}

@media (max-width: 820px) {
  .dashboard-container {
    padding: 4.5rem 1.25rem 1.25rem;
  }

  .files-panel {
    padding: 1rem;
  }
}
</style>
