/**
 * Keyboard shortcuts handler for SOUND UI
 */

class KeyboardShortcutsUI {
  constructor() {
    this.setupListeners();
  }

  setupListeners() {
    // Listen for global shortcut events from main process
    window.electronAPI.on("app:open-settings", () => {
      this.openSettings();
    });

    window.electronAPI.on("library:sync", () => {
      this.syncLibrary();
    });

    window.electronAPI.on("library:full-rescan", () => {
      this.fullRescanLibrary();
    });

    window.electronAPI.on("app:open-duplicates", () => {
      this.openDuplicateManager();
    });

    window.electronAPI.on("app:create-backup", () => {
      this.createBackup();
    });

    window.electronAPI.on("app:show-info", () => {
      this.showServerInfo();
    });
  }

  // App functions
  openSettings() {
    window.electronAPI.openSettingsWindow();
  }

  syncLibrary() {
    // Click the sync button if it exists
    const syncButton = document.getElementById("syncButton");
    if (syncButton) {
      syncButton.click();
    }
  }

  fullRescanLibrary() {
    if (
      confirm("Perform a full library rescan? This will re-scan all files and may take a while.")
    ) {
      // Trigger full rescan
      window.electronAPI.scanLibrary(null, false); // false = not incremental
    }
  }

  openDuplicateManager() {
    window.electronAPI.openWindow("duplicate-manager");
  }

  createBackup() {
    // Open settings on backup tab
    window.electronAPI.openSettingsWindow("advanced");
    setTimeout(() => {
      // Try to click the backup button
      const backupButton = document.querySelector('[onclick*="createBackup"]');
      if (backupButton) {
        backupButton.click();
      }
    }, 500);
  }

  showServerInfo() {
    // Show server information
    const info = `
SOUND Server Info:
- Status: Active
- Port: 51823
- Version: ${window.electronAPI.getVersion ? window.electronAPI.getVersion() : "1.0.0"}
- API: http://localhost:51823/api
    `.trim();

    alert(info);
  }

  // Toast notifications
  showToast(message) {
    const toast = document.createElement("div");
    toast.className = "keyboard-toast";
    toast.textContent = message;
    toast.style.cssText = `
      position: fixed;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 10px 20px;
      border-radius: 4px;
      font-size: 14px;
      z-index: 10000;
      transition: opacity 0.3s;
    `;

    document.body.appendChild(toast);

    setTimeout(() => {
      toast.style.opacity = "0";
      setTimeout(() => toast.remove(), 300);
    }, 2000);
  }
}

// Initialize when DOM is ready
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", () => {
    new KeyboardShortcutsUI();
  });
} else {
  new KeyboardShortcutsUI();
}
