<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";

const screen = ref("login"); // login | main
const serverUrl = ref("https://");
const username = ref("");
const password = ref("");
const loginError = ref("");
const loginLoading = ref(false);

const syncDir = ref("");
const syncLog = ref([]);
const syncing = ref(false);
const syncStatus = ref("Nicht verbunden");
const userInfo = ref(null);
const fileTree = ref([]);
const fileChanges = ref([]);
const autoSyncActive = ref(false);

let unlistenStatus = null;
let unlistenLog = null;
let unlistenError = null;
let unlistenFileChange = null;

async function handleLogin() {
  loginError.value = "";
  loginLoading.value = true;
  try {
    const result = await invoke("login", {
      serverUrl: serverUrl.value,
      username: username.value,
      password: password.value,
    });
    userInfo.value = result;
    screen.value = "main";
    syncStatus.value = `Verbunden als ${result.username}`;

    // Default sync dir
    const home = navigator.platform.includes("Win") ? "C:\\Users\\" + result.username : "/home/" + result.username;
    syncDir.value = `${home}/MiniCloud`;

    await loadFileTree();
  } catch (err) {
    loginError.value = String(err);
  } finally {
    loginLoading.value = false;
  }
}

async function runSync() {
  syncing.value = true;
  syncStatus.value = "Erster Sync...";
  try {
    await invoke("set_sync_dir", { path: syncDir.value });
    const log = await invoke("start_sync");
    syncLog.value = [...log, ...syncLog.value].slice(0, 100);
    syncStatus.value = "Synchronisiert";
    autoSyncActive.value = true;
    await loadFileTree();
  } catch (err) {
    syncStatus.value = `Fehler: ${err}`;
  } finally {
    syncing.value = false;
  }
}

async function loadFileTree() {
  try {
    fileTree.value = await invoke("get_file_tree");
  } catch (err) {
    console.error("Tree-Fehler:", err);
  }
}

function formatSize(bytes) {
  if (!bytes) return "";
  const units = ["B", "KB", "MB", "GB"];
  let i = 0;
  let size = bytes;
  while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
  return `${size.toFixed(i > 0 ? 1 : 0)} ${units[i]}`;
}

function timestamp() {
  return new Date().toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit", second: "2-digit" });
}

onMounted(async () => {
  // Listen for sync events from Rust backend
  unlistenStatus = await listen("sync-status", (event) => {
    if (event.payload === "syncing") {
      syncStatus.value = "Synchronisiere...";
      syncing.value = true;
    } else if (event.payload === "synced") {
      syncStatus.value = "Synchronisiert";
      syncing.value = false;
      loadFileTree();
    }
  });

  unlistenLog = await listen("sync-log", (event) => {
    const entries = event.payload.map(msg => `[${timestamp()}] ${msg}`);
    syncLog.value = [...entries, ...syncLog.value].slice(0, 200);
  });

  unlistenError = await listen("sync-error", (event) => {
    syncStatus.value = `Fehler: ${event.payload}`;
    syncLog.value = [`[${timestamp()}] FEHLER: ${event.payload}`, ...syncLog.value].slice(0, 200);
    syncing.value = false;
  });

  unlistenFileChange = await listen("file-change", (event) => {
    fileChanges.value = [`[${timestamp()}] ${event.payload}`, ...fileChanges.value].slice(0, 50);
  });
});

onUnmounted(() => {
  unlistenStatus?.();
  unlistenLog?.();
  unlistenError?.();
  unlistenFileChange?.();
});
</script>

<template>
  <!-- Login -->
  <div v-if="screen === 'login'" class="login-screen">
    <div class="login-card">
      <div class="login-header">
        <div class="logo-icon">☁</div>
        <h1>Mini-Cloud</h1>
        <p>Desktop Sync Client</p>
      </div>
      <form @submit.prevent="handleLogin">
        <div class="field">
          <label>Server-URL</label>
          <input v-model="serverUrl" placeholder="https://cloud.example.com" />
        </div>
        <div class="field">
          <label>Benutzername</label>
          <input v-model="username" placeholder="Benutzername" autofocus />
        </div>
        <div class="field">
          <label>Passwort</label>
          <input v-model="password" type="password" placeholder="Passwort" />
        </div>
        <div v-if="loginError" class="error">{{ loginError }}</div>
        <button type="submit" :disabled="loginLoading" class="btn-primary">
          {{ loginLoading ? "Verbinde..." : "Anmelden" }}
        </button>
      </form>
    </div>
  </div>

  <!-- Main -->
  <div v-else class="main-screen">
    <div class="toolbar">
      <div class="toolbar-left">
        <span class="logo-small">☁</span>
        <strong>Mini-Cloud Sync</strong>
        <span class="status-badge" :class="{ syncing: syncing, error: syncStatus.startsWith('Fehler') }">
          <span v-if="syncing" class="spin">⟳</span>
          {{ syncStatus }}
        </span>
      </div>
      <div class="toolbar-right">
        <span class="user-info">{{ userInfo?.username }}</span>
      </div>
    </div>

    <div class="content">
      <!-- Sync Settings -->
      <div class="section">
        <h3>Sync-Ordner</h3>
        <div class="sync-row">
          <input v-model="syncDir" class="sync-input" :disabled="autoSyncActive" />
          <button @click="runSync" :disabled="syncing" class="btn-primary">
            {{ autoSyncActive ? "⟳ Auto-Sync aktiv" : (syncing ? "Synchronisiere..." : "Sync starten") }}
          </button>
        </div>
        <div v-if="autoSyncActive" class="auto-sync-info">
          Auto-Sync alle 30 Sekunden aktiv. Datei-Watcher ueberwacht lokale Aenderungen.
        </div>
      </div>

      <!-- File Tree -->
      <div class="section">
        <div class="section-header">
          <h3>Server-Dateien</h3>
          <button v-if="autoSyncActive" @click="loadFileTree" class="btn-small">Aktualisieren</button>
        </div>
        <div class="file-tree">
          <template v-for="entry in fileTree" :key="entry.id">
            <div class="tree-item">
              <span class="tree-icon">{{ entry.is_folder ? "📁" : "📄" }}</span>
              <span class="tree-name">{{ entry.name }}</span>
              <span v-if="entry.locked" class="tree-lock">🔒 {{ entry.locked_by }}</span>
              <span v-if="!entry.is_folder" class="tree-size">{{ formatSize(entry.size) }}</span>
            </div>
            <div v-if="entry.children" v-for="child in entry.children" :key="child.id" class="tree-item indent">
              <span class="tree-icon">{{ child.is_folder ? "📁" : "📄" }}</span>
              <span class="tree-name">{{ child.name }}</span>
              <span v-if="child.locked" class="tree-lock">🔒 {{ child.locked_by }}</span>
              <span v-if="!child.is_folder" class="tree-size">{{ formatSize(child.size) }}</span>
            </div>
          </template>
          <div v-if="!fileTree.length" class="empty">Keine Dateien</div>
        </div>
      </div>

      <!-- File Changes (Watcher) -->
      <div v-if="fileChanges.length" class="section">
        <h3>Lokale Aenderungen</h3>
        <div class="log-list">
          <div v-for="(msg, i) in fileChanges" :key="i" class="log-item change">{{ msg }}</div>
        </div>
      </div>

      <!-- Sync Log -->
      <div v-if="syncLog.length" class="section">
        <h3>Sync-Protokoll</h3>
        <div class="log-list">
          <div v-for="(msg, i) in syncLog" :key="i" class="log-item">{{ msg }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 14px; color: #1a1a1a; background: #f0f2f5;
}
.login-screen { height: 100vh; display: flex; align-items: center; justify-content: center; }
.login-card {
  background: white; border-radius: 12px; padding: 2rem; width: 360px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
.login-header { text-align: center; margin-bottom: 1.5rem; }
.logo-icon { font-size: 2.5rem; }
.login-header h1 { font-size: 1.3rem; margin: 0.5rem 0 0.25rem; }
.login-header p { color: #666; font-size: 0.85rem; }
.field { margin-bottom: 0.75rem; }
.field label { display: block; margin-bottom: 0.25rem; font-weight: 500; font-size: 0.85rem; }
.field input {
  width: 100%; padding: 0.5rem; border: 1px solid #ddd; border-radius: 6px;
  font-size: 0.9rem; background: #fafafa;
}
.field input:focus { border-color: #4a90d9; outline: none; background: white; }
.error { color: #e53e3e; font-size: 0.85rem; margin-bottom: 0.75rem; }
.btn-primary {
  padding: 0.6rem 1rem; background: #4a90d9; color: white;
  border: none; border-radius: 6px; font-size: 0.9rem; cursor: pointer; font-weight: 500;
  white-space: nowrap;
}
.btn-primary:hover { background: #3a7bc8; }
.btn-primary:disabled { opacity: 0.6; cursor: not-allowed; }
.btn-small {
  padding: 0.25rem 0.5rem; background: #e8e8e8; border: none; border-radius: 4px;
  font-size: 0.8rem; cursor: pointer;
}
.btn-small:hover { background: #ddd; }

.main-screen { height: 100vh; display: flex; flex-direction: column; }
.toolbar {
  display: flex; align-items: center; justify-content: space-between;
  padding: 0.5rem 1rem; background: white; border-bottom: 1px solid #e0e0e0;
}
.toolbar-left { display: flex; align-items: center; gap: 0.5rem; }
.logo-small { font-size: 1.2rem; }
.status-badge {
  font-size: 0.8rem; padding: 0.2rem 0.5rem; border-radius: 4px;
  background: #e8f5e9; color: #2e7d32;
}
.status-badge.syncing { background: #fff3e0; color: #e65100; }
.status-badge.error { background: #ffebee; color: #c62828; }
.spin { display: inline-block; animation: spin 1s linear infinite; }
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
.user-info { font-size: 0.85rem; color: #666; }
.content { flex: 1; overflow-y: auto; padding: 1rem; }
.section { background: white; border-radius: 8px; padding: 1rem; margin-bottom: 0.75rem; }
.section h3 { margin-bottom: 0.5rem; font-size: 0.95rem; }
.section-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.5rem; }
.section-header h3 { margin: 0; }
.sync-row { display: flex; gap: 0.5rem; }
.sync-input {
  flex: 1; padding: 0.5rem; border: 1px solid #ddd; border-radius: 6px; font-size: 0.85rem;
}
.sync-input:disabled { background: #f5f5f5; color: #999; }
.auto-sync-info { margin-top: 0.5rem; font-size: 0.8rem; color: #2e7d32; }
.file-tree { max-height: 250px; overflow-y: auto; }
.tree-item {
  display: flex; align-items: center; gap: 0.5rem;
  padding: 0.3rem 0; border-bottom: 1px solid #f5f5f5; font-size: 0.85rem;
}
.tree-item.indent { padding-left: 1.5rem; }
.tree-icon { flex-shrink: 0; }
.tree-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tree-lock { font-size: 0.75rem; color: #e67e22; flex-shrink: 0; }
.tree-size { font-size: 0.75rem; color: #999; flex-shrink: 0; }
.empty { text-align: center; color: #999; padding: 1rem; }
.log-list { max-height: 150px; overflow-y: auto; font-family: monospace; font-size: 0.78rem; }
.log-item { padding: 0.2rem 0; border-bottom: 1px solid #f8f8f8; color: #555; }
.log-item.change { color: #1565c0; }

@media (prefers-color-scheme: dark) {
  body { color: #e0e0e0; background: #1a1a1a; }
  .login-card, .section { background: #2a2a2a; }
  .toolbar { background: #2a2a2a; border-color: #3a3a3a; }
  .field input, .sync-input { background: #333; border-color: #444; color: #e0e0e0; }
  .status-badge { background: #1b5e20; color: #a5d6a7; }
  .status-badge.syncing { background: #e65100; color: #ffcc80; }
  .tree-item { border-color: #333; }
  .log-item { border-color: #333; color: #aaa; }
  .log-item.change { color: #64b5f6; }
}
</style>
