let isDownloading = false;

let playBtn;
let playText;
let homePlayBtn;
let uninstallBtn;
let playerNameInput;
let javaPathInput;

export function setupLauncher() {
  playBtn = document.getElementById('playBtn');
  playText = document.getElementById('playText');
  homePlayBtn = document.getElementById('homePlayBtn');
  uninstallBtn = document.getElementById('uninstallBtn');
  playerNameInput = document.getElementById('playerName');
  javaPathInput = document.getElementById('javaPath');

  if (playerNameInput) {
    playerNameInput.addEventListener('change', savePlayerName);
  }

  if (javaPathInput) {
    javaPathInput.addEventListener('change', saveJavaPath);
  }

  if (window.electronAPI && window.electronAPI.onProgressUpdate) {
    window.electronAPI.onProgressUpdate((data) => {
      if (!isDownloading) return;
      if (window.LauncherUI) {
        window.LauncherUI.updateProgress(data);
      }
    });
  }

  // Initial Profile Load
  loadProfiles();

  // Initial Identity Load
  loadIdentities();

  // Close dropdowns on outside click
  document.addEventListener('click', (e) => {
    const profileSelector = document.getElementById('profileSelector');
    if (profileSelector && !profileSelector.contains(e.target)) {
      const dropdown = document.getElementById('profileDropdown');
      if (dropdown) dropdown.classList.remove('show');
    }
    const identitySelector = document.getElementById('identitySelector');
    if (identitySelector && !identitySelector.contains(e.target)) {
      const dropdown = document.getElementById('identityDropdown');
      if (dropdown) dropdown.classList.remove('show');
    }
  });
}

// ==========================================
// PROFILE MANAGEMENT
// ==========================================

async function loadProfiles() {
  try {
    if (!window.electronAPI || !window.electronAPI.profile) return;

    const profiles = await window.electronAPI.profile.list();
    const activeProfile = await window.electronAPI.profile.getActive();

    renderProfileList(profiles, activeProfile);
    updateCurrentProfileUI(activeProfile);
  } catch (error) {
    console.error('Failed to load profiles:', error);
  }
}

function renderProfileList(profiles, activeProfile) {
  const list = document.getElementById('profileList');
  const managerList = document.getElementById('managerProfileList');

  if (!list) return;

  // Dropdown List
  list.innerHTML = profiles.map(p => `
        <div class="profile-item ${p.id === activeProfile.id ? 'active' : ''}" 
             onclick="switchProfile('${p.id}')">
            <span>${p.name}</span>
            ${p.id === activeProfile.id ? '<i class="fas fa-check ml-auto"></i>' : ''}
        </div>
    `).join('');

  // Manager Modal List
  if (managerList) {
    managerList.innerHTML = profiles.map(p => `
            <div class="profile-manager-item ${p.id === activeProfile.id ? 'active' : ''}">
                <div class="flex items-center gap-3">
                    <i class="fas fa-sliders-h text-xl text-gray-400"></i>
                    <div>
                        <div class="font-bold">${p.name}</div>
                        <div class="text-xs text-gray-500">ID: ${p.id.substring(0, 8)}...</div>
                    </div>
                </div>
                ${p.id !== activeProfile.id ? `
                    <button class="profile-delete-btn" onclick="deleteProfile('${p.id}')" title="Delete Profile">
                        <i class="fas fa-trash"></i>
                    </button>
                ` : '<span class="text-xs text-green-500 font-bold px-2">ACTIVE</span>'}
            </div>
        `).join('');
  }
}

function updateCurrentProfileUI(profile) {
  const nameEl = document.getElementById('currentProfileName');
  if (nameEl && profile) {
    nameEl.textContent = profile.name;
  }
}

window.openProfileManager = () => {
  const modal = document.getElementById('profileManagerModal');
  if (modal) {
    modal.style.display = 'flex';
    // Refresh list
    loadProfiles();
  }
  // Close dropdown
  const dropdown = document.getElementById('profileDropdown');
  if (dropdown) dropdown.classList.remove('show');
};

window.closeProfileManager = () => {
  const modal = document.getElementById('profileManagerModal');
  if (modal) modal.style.display = 'none';
};

window.createNewProfile = async () => {
  const input = document.getElementById('newProfileName');
  if (!input || !input.value.trim()) return;

  try {
    const name = input.value.trim();
    await window.electronAPI.profile.create(name);
    input.value = '';
    await loadProfiles();
  } catch (error) {
    console.error('Failed to create profile:', error);
    alert('Failed to create profile: ' + error.message);
  }
};

window.deleteProfile = async (id) => {
  if (!confirm('Are you sure you want to delete this configuration? Mod settings will be lost.')) return;

  try {
    await window.electronAPI.profile.delete(id);
    await loadProfiles();
  } catch (error) {
    console.error('Failed to delete profile:', error);
    alert('Failed to delete profile: ' + error.message);
  }
};

window.switchProfile = async (id) => {
  try {
    if (window.LauncherUI) window.LauncherUI.showProgress();
    const switchingMsg = window.i18n ? window.i18n.t('progress.switchingProfile') : 'Switching configuration...';
    if (window.LauncherUI) window.LauncherUI.updateProgress({ message: switchingMsg });

    await window.electronAPI.profile.activate(id);

    // Refresh UI
    await loadProfiles();

    // Refresh branch radio buttons in settings
    if (window.SettingsAPI?.reloadBranch) {
      await window.SettingsAPI.reloadBranch();
    }

    // Refresh game info bar on play page
    if (window.LauncherUI?.loadGameInfoBar) {
      window.LauncherUI.loadGameInfoBar();
    }

    // Refresh Mods
    if (window.modsManager) {
      if (window.modsManager.loadInstalledMods) await window.modsManager.loadInstalledMods();
      if (window.modsManager.loadBrowseMods) await window.modsManager.loadBrowseMods();
    }

    // Close dropdown
    const dropdown = document.getElementById('profileDropdown');
    if (dropdown) dropdown.classList.remove('show');

    if (window.LauncherUI) {
      const switchedMsg = window.i18n ? window.i18n.t('progress.profileSwitched') : 'Configuration switched!';
      window.LauncherUI.updateProgress({ message: switchedMsg });
      setTimeout(() => window.LauncherUI.hideProgress(), 1000);
    }

  } catch (error) {
    console.error('Failed to switch profile:', error);
    alert('Failed to switch profile: ' + error.message);
    if (window.LauncherUI) window.LauncherUI.hideProgress();
  }
};

export async function launch() {
  const btn = homePlayBtn || playBtn;
  if (isDownloading || (btn && btn.disabled)) return;

  // ==========================================================================
  // STEP 1: Check launch readiness from backend (single source of truth)
  // ==========================================================================
  let launchState = null;
  let playerName = null;

  try {
    if (window.electronAPI && window.electronAPI.checkLaunchReady) {
      launchState = await window.electronAPI.checkLaunchReady();
      playerName = launchState?.username;
    } else if (window.electronAPI && window.electronAPI.loadUsername) {
      // Fallback to loadUsername if checkLaunchReady not available
      playerName = await window.electronAPI.loadUsername();
      launchState = { ready: !!playerName, hasUsername: !!playerName, username: playerName, issues: [] };
    }
  } catch (error) {
    console.error('[Launcher] Error checking launch readiness:', error);
  }

  // Validate launch readiness
  if (!launchState?.ready || !playerName) {
    const issues = launchState?.issues || ['No username configured'];
    const errorMsg = window.i18n
      ? window.i18n.t('errors.noUsername')
      : 'Please set your username in Settings before playing.';

    console.error('[Launcher] Launch blocked:', issues.join(', '));

    // Show error to user
    if (window.LauncherUI && window.LauncherUI.showError) {
      window.LauncherUI.showError(errorMsg);
    } else {
      alert(errorMsg);
    }

    // Navigate to settings if possible
    if (window.LauncherUI && window.LauncherUI.showPage) {
      window.LauncherUI.showPage('settings-page');
      window.LauncherUI.setActiveNav('settings');
    }

    return;
  }

  // Warn if using default 'Player' name (shouldn't happen with new logic, but keep as safety)
  if (playerName === 'Player') {
    console.warn('[Launcher] Warning: Using default username "Player"');
  }

  console.log(`[Launcher] Launching game for: "${playerName}"`);

  // ==========================================================================
  // STEP 2: Load other settings from backend
  // ==========================================================================
  let javaPath = '';
  try {
    if (window.electronAPI && window.electronAPI.loadJavaPath) {
      javaPath = await window.electronAPI.loadJavaPath() || '';
    }
  } catch (error) {
    console.error('[Launcher] Error loading Java path:', error);
  }

  let gpuPreference = 'auto';
  try {
    if (window.electronAPI && window.electronAPI.loadGpuPreference) {
      gpuPreference = await window.electronAPI.loadGpuPreference();
    }
  } catch (error) {
    console.error('[Launcher] Error loading GPU preference:', error);
  }

  // ==========================================================================
  // STEP 3: Start launch process
  // ==========================================================================
  if (window.LauncherUI) window.LauncherUI.showProgress();
  lockPlayButton('LAUNCHING...');

  try {
    const startingMsg = window.i18n ? window.i18n.t('progress.startingGame') : 'Starting game...';
    if (window.LauncherUI) window.LauncherUI.updateProgress({ message: startingMsg });

    if (window.electronAPI && window.electronAPI.launchGame) {
      // Pass playerName from config - backend will validate again
      const result = await window.electronAPI.launchGame(playerName, javaPath, '', gpuPreference);

      if (result.usernameTaken) {
        // Username reserved by another player
        isDownloading = false;
        if (window.LauncherUI) window.LauncherUI.hideProgress();
        resetPlayButton();
        if (window.LauncherUI && window.LauncherUI.showError) {
          window.LauncherUI.showError('This username is reserved by another player. Please change your player name in Identity settings.');
        } else {
          showNotification('This username is reserved by another player. Please change your player name.', 'error');
        }
        return;
      }

      if (result.nameLocked) {
        // UUID is password-protected and locked to a specific name
        isDownloading = false;
        if (window.LauncherUI) window.LauncherUI.hideProgress();
        resetPlayButton();
        const msg = result.registeredName
          ? `This UUID is locked to username "${result.registeredName}". Change your identity name to "${result.registeredName}" in Settings.`
          : 'This UUID is locked to a different username. Check your identity settings.';
        if (window.LauncherUI && window.LauncherUI.showError) {
          window.LauncherUI.showError(msg);
        } else {
          showNotification(msg, 'error');
        }
        return;
      }

      if (result.passwordRequired) {
        // Check for saved password first
        let savedPw = null;
        try {
          const cfg = await window.electronAPI.loadConfig();
          const uuid = result.uuid || '';
          savedPw = cfg && cfg.savedPasswords && cfg.savedPasswords[uuid] ? cfg.savedPasswords[uuid] : null;
        } catch (e) { /* ignore */ }

        if (savedPw) {
          // Try saved password silently
          if (window.LauncherUI) window.LauncherUI.showProgress();
          lockPlayButton('LAUNCHING...');
          const autoResult = await window.electronAPI.launchGameWithPassword(playerName, javaPath, '', gpuPreference, savedPw);
          if (autoResult.success) {
            isDownloading = false;
            if (window.LauncherUI) window.LauncherUI.hideProgress();
            resetPlayButton();
            if (window.electronAPI.minimizeWindow) setTimeout(() => { window.electronAPI.minimizeWindow(); }, 500);
            return;
          }
          // Saved password failed — clear it and show popup
          isDownloading = false;
          if (window.LauncherUI) window.LauncherUI.hideProgress();
          resetPlayButton();
          try {
            const cfg2 = await window.electronAPI.loadConfig();
            const sp = cfg2.savedPasswords || {};
            delete sp[result.uuid || ''];
            await window.electronAPI.saveConfig({ savedPasswords: sp });
          } catch (e) { /* ignore */ }
        }

        // Show interactive password dialog
        const launchResult = await promptForPasswordAndLaunch(playerName, javaPath, gpuPreference, result.uuid);
        if (launchResult && launchResult.success) {
          if (window.electronAPI.minimizeWindow) setTimeout(() => { window.electronAPI.minimizeWindow(); }, 500);
        }
        return;
      }

      if (result.success) {
        // Keep button locked so user can't double-launch
        if (window.LauncherUI) window.LauncherUI.hideProgress();
        lockPlayButton('GAME RUNNING');
        setTimeout(() => {
          resetPlayButton();
        }, 10000); // Reset after 10s (game should be visible by then)
        if (window.electronAPI.minimizeWindow) {
          setTimeout(() => {
            window.electronAPI.minimizeWindow();
          }, 500);
        }
      } else {
        isDownloading = false;
        if (window.LauncherUI) window.LauncherUI.hideProgress();
        resetPlayButton();
        console.error('[Launcher] Launch failed:', result.error);

        // Handle specific error cases
        if (result.needsUsername) {
          const errorMsg = window.i18n
            ? window.i18n.t('errors.noUsername')
            : 'Please set your username in Settings before playing.';

          if (window.LauncherUI && window.LauncherUI.showError) {
            window.LauncherUI.showError(errorMsg);
          } else {
            alert(errorMsg);
          }

          // Navigate to settings
          if (window.LauncherUI && window.LauncherUI.showPage) {
            window.LauncherUI.showPage('settings-page');
            window.LauncherUI.setActiveNav('settings');
          }
        } else if (result.error) {
          // Show generic error
          const errorMsg = window.i18n
            ? window.i18n.t('errors.launchFailed').replace('{error}', result.error)
            : `Launch failed: ${result.error}`;

          if (window.LauncherUI && window.LauncherUI.showError) {
            window.LauncherUI.showError(errorMsg);
          }
        }
      }
    } else {
      isDownloading = false;

      if (window.LauncherUI) {
        window.LauncherUI.hideProgress();
      }
      resetPlayButton();
    }
  } catch (error) {
    isDownloading = false;

    if (window.LauncherUI) {
      window.LauncherUI.hideProgress();
    }
    resetPlayButton();
    console.error('[Launcher] Launch error:', error);

    // Show error to user
    const errorMsg = error.message || 'Unknown launch error';
    if (window.LauncherUI && window.LauncherUI.showError) {
      window.LauncherUI.showError(errorMsg);
    }
  }
}

function promptForPasswordAndLaunch(playerName, javaPath, gpuPreference, uuid) {
  return new Promise((resolve) => {
    // Remove any existing password prompt
    const existing = document.querySelector('.custom-confirm-modal');
    if (existing) existing.remove();

    const overlay = document.createElement('div');
    overlay.className = 'custom-confirm-modal';
    overlay.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.8);
      backdrop-filter: blur(4px);
      z-index: 20000;
      display: flex;
      align-items: center;
      justify-content: center;
    `;

    const dialog = document.createElement('div');
    dialog.style.cssText = `
      background: #1f2937;
      border-radius: 12px;
      padding: 0;
      min-width: 380px;
      max-width: 420px;
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.6);
      border: 1px solid rgba(255, 255, 255, 0.1);
    `;

    dialog.innerHTML = `
      <div style="padding: 20px 24px; border-bottom: 1px solid rgba(255,255,255,0.1);">
        <div style="display: flex; align-items: center; gap: 10px; color: #f59e0b;">
          <i class="fas fa-lock" style="font-size: 20px;"></i>
          <h3 style="margin: 0; font-size: 1.1rem; font-weight: 600; color: #e5e7eb;">Password Required</h3>
        </div>
      </div>
      <div style="padding: 20px 24px;">
        <p style="margin: 0 0 12px 0; color: #9ca3af; font-size: 0.9rem; line-height: 1.5;">This identity is password-protected. Enter your password to continue.</p>
        <div id="pwErrorMsg" style="display: none; margin-bottom: 12px; padding: 8px 12px; background: rgba(239,68,68,0.15); border: 1px solid rgba(239,68,68,0.3); border-radius: 6px; color: #f87171; font-size: 0.85rem;"></div>
        <input type="password" id="launchPasswordInput" style="
          width: 100%;
          box-sizing: border-box;
          padding: 10px 14px;
          background: rgba(0,0,0,0.3);
          border: 1px solid rgba(255,255,255,0.15);
          border-radius: 8px;
          color: #e5e7eb;
          font-size: 0.95rem;
          outline: none;
        " placeholder="Password" autofocus />
        <label style="display: flex; align-items: center; gap: 8px; margin-top: 12px; cursor: pointer; color: #9ca3af; font-size: 0.85rem; user-select: none;">
          <input type="checkbox" id="pwRememberCheck" style="accent-color: #f59e0b; width: 16px; height: 16px; cursor: pointer;" />
          Remember password
        </label>
      </div>
      <div style="padding: 16px 24px; display: flex; gap: 10px; justify-content: flex-end; border-top: 1px solid rgba(255,255,255,0.1);">
        <button id="pwCancelBtn" style="
          background: transparent;
          color: #9ca3af;
          border: 1px solid rgba(156,163,175,0.3);
          padding: 9px 18px;
          border-radius: 6px;
          cursor: pointer;
          font-size: 0.9rem;
        ">Cancel</button>
        <button id="pwConfirmBtn" style="
          background: #f59e0b;
          color: #000;
          border: none;
          padding: 9px 18px;
          border-radius: 6px;
          cursor: pointer;
          font-weight: 600;
          font-size: 0.9rem;
        ">Login</button>
      </div>
    `;

    overlay.appendChild(dialog);
    document.body.appendChild(overlay);

    const input = overlay.querySelector('#launchPasswordInput');
    const confirmBtn = overlay.querySelector('#pwConfirmBtn');
    const cancelBtn = overlay.querySelector('#pwCancelBtn');
    const errorMsg = overlay.querySelector('#pwErrorMsg');
    const rememberCheck = overlay.querySelector('#pwRememberCheck');

    let busy = false;

    const close = (result) => {
      overlay.remove();
      isDownloading = false;
      if (window.LauncherUI) window.LauncherUI.hideProgress();
      resetPlayButton();
      resolve(result);
    };

    const showError = (msg) => {
      errorMsg.textContent = msg;
      errorMsg.style.display = 'block';
      input.style.borderColor = 'rgba(239,68,68,0.5)';
      input.value = '';
      input.focus();
    };

    const tryLogin = async () => {
      const password = input.value;
      if (!password) {
        showError('Please enter your password.');
        return;
      }
      if (busy) return;
      busy = true;

      // Show loading state
      confirmBtn.disabled = true;
      confirmBtn.textContent = 'Logging in...';
      errorMsg.style.display = 'none';
      input.style.borderColor = 'rgba(255,255,255,0.15)';

      try {
        if (window.LauncherUI) window.LauncherUI.showProgress();
        lockPlayButton('LAUNCHING...');

        const result = await window.electronAPI.launchGameWithPassword(playerName, javaPath, '', gpuPreference, password);

        if (result.success) {
          // Save password if "Remember" checked
          if (rememberCheck.checked && uuid) {
            try {
              const cfg = await window.electronAPI.loadConfig();
              const sp = cfg.savedPasswords || {};
              sp[uuid] = password;
              await window.electronAPI.saveConfig({ savedPasswords: sp });
            } catch (e) { /* ignore */ }
          }
          overlay.remove();
          isDownloading = false;
          if (window.LauncherUI) window.LauncherUI.hideProgress();
          resetPlayButton();
          resolve(result);
          return;
        }

        // Wrong password
        if (result.passwordRequired) {
          showError(result.error || 'Incorrect password. Please try again.');
        } else {
          showError(result.error || 'Launch failed.');
        }

        isDownloading = false;
        if (window.LauncherUI) window.LauncherUI.hideProgress();
        resetPlayButton();
      } catch (err) {
        showError(err.message || 'An error occurred.');
        isDownloading = false;
        if (window.LauncherUI) window.LauncherUI.hideProgress();
        resetPlayButton();
      } finally {
        busy = false;
        confirmBtn.disabled = false;
        confirmBtn.textContent = 'Login';
      }
    };

    confirmBtn.addEventListener('click', tryLogin);
    cancelBtn.addEventListener('click', () => close(null));
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') tryLogin();
      if (e.key === 'Escape') close(null);
    });

    setTimeout(() => input.focus(), 100);
  });
}

function showCustomConfirm(message, title, onConfirm, onCancel = null, confirmText, cancelText) {
  // Apply defaults with i18n support
  title = title || (window.i18n ? window.i18n.t('confirm.defaultTitle') : 'Confirm Action');
  confirmText = confirmText || (window.i18n ? window.i18n.t('common.confirm') : 'Confirm');
  cancelText = cancelText || (window.i18n ? window.i18n.t('common.cancel') : 'Cancel');
  
  const existingModal = document.querySelector('.custom-confirm-modal');
  if (existingModal) {
    existingModal.remove();
  }

  const modal = document.createElement('div');
  modal.className = 'custom-confirm-modal';
  modal.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8);
    backdrop-filter: blur(4px);
    z-index: 20000;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
  `;

  const dialog = document.createElement('div');
  dialog.className = 'custom-confirm-dialog';
  dialog.style.cssText = `
    background: #1f2937;
    border-radius: 12px;
    padding: 0;
    min-width: 400px;
    max-width: 500px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.6);
    border: 1px solid rgba(239, 68, 68, 0.3);
    transform: scale(0.9);
    transition: transform 0.3s ease;
  `;

  dialog.innerHTML = `
    <div style="padding: 24px; border-bottom: 1px solid rgba(255,255,255,0.1);">
      <div style="display: flex; align-items: center; gap: 12px; color: #ef4444;">
        <i class="fas fa-exclamation-triangle" style="font-size: 24px;"></i>
        <h3 style="margin: 0; font-size: 1.2rem; font-weight: 600;">${title}</h3>
      </div>
    </div>
    <div style="padding: 24px; color: #e5e7eb;">
      <p style="margin: 0; line-height: 1.5; font-size: 1rem;">${message}</p>
    </div>
    <div style="padding: 20px 24px; display: flex; gap: 12px; justify-content: flex-end; border-top: 1px solid rgba(255,255,255,0.1);">
      <button class="custom-confirm-cancel" style="
        background: transparent;
        color: #9ca3af;
        border: 1px solid rgba(156, 163, 175, 0.3);
        padding: 10px 20px;
        border-radius: 6px;
        cursor: pointer;
        font-weight: 500;
        transition: all 0.2s;
      ">${cancelText}</button>
      <button class="custom-confirm-action" style="
        background: #ef4444;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 6px;
        cursor: pointer;
        font-weight: 500;
        transition: all 0.2s;
      ">${confirmText}</button>
    </div>
  `;

  modal.appendChild(dialog);
  document.body.appendChild(modal);

  // Animate in
  setTimeout(() => {
    modal.style.opacity = '1';
    dialog.style.transform = 'scale(1)';
  }, 10);

  // Event handlers
  const cancelBtn = dialog.querySelector('.custom-confirm-cancel');
  const actionBtn = dialog.querySelector('.custom-confirm-action');

  const closeModal = () => {
    modal.style.opacity = '0';
    dialog.style.transform = 'scale(0.9)';
    setTimeout(() => {
      modal.remove();
    }, 300);
  };

  cancelBtn.onclick = () => {
    closeModal();
    if (onCancel) onCancel();
  };

  actionBtn.onclick = () => {
    closeModal();
    onConfirm();
  };

  modal.onclick = (e) => {
    if (e.target === modal) {
      closeModal();
      if (onCancel) onCancel();
    }
  };

  // Escape key
  const handleEscape = (e) => {
    if (e.key === 'Escape') {
      closeModal();
      if (onCancel) onCancel();
      document.removeEventListener('keydown', handleEscape);
    }
  };
  document.addEventListener('keydown', handleEscape);
}

export async function uninstallGame() {
  const message = window.i18n ? window.i18n.t('confirm.uninstallGameMessage') : 'Are you sure you want to uninstall Hytale? All game files will be deleted.';
  const title = window.i18n ? window.i18n.t('confirm.uninstallGameTitle') : 'Uninstall Game';
  const confirmBtn = window.i18n ? window.i18n.t('confirm.uninstallGameButton') : 'Uninstall';
  const cancelBtn = window.i18n ? window.i18n.t('common.cancel') : 'Cancel';
  
  showCustomConfirm(
    message,
    title,
    async () => {
      await performUninstall();
    },
    null,
    confirmBtn,
    cancelBtn
  );
}

async function performUninstall() {

  if (window.LauncherUI) window.LauncherUI.showProgress();
  const uninstallingMsg = window.i18n ? window.i18n.t('progress.uninstallingGame') : 'Uninstalling game...';
  if (window.LauncherUI) window.LauncherUI.updateProgress({ message: uninstallingMsg });
  if (uninstallBtn) uninstallBtn.disabled = true;

  try {
    if (window.electronAPI && window.electronAPI.uninstallGame) {
      const result = await window.electronAPI.uninstallGame();

      if (result.success) {
        const successMsg = window.i18n ? window.i18n.t('progress.gameUninstalled') : 'Game uninstalled successfully!';
        if (window.LauncherUI) {
          window.LauncherUI.updateProgress({ message: successMsg });
          setTimeout(() => {
            window.LauncherUI.hideProgress();
            window.LauncherUI.showLauncherOrInstall(false);
          }, 2000);
        }
      } else {
        throw new Error(result.error || 'Uninstall failed');
      }
    } else {
      const successMsg = window.i18n ? window.i18n.t('progress.gameUninstalled') : 'Game uninstalled successfully!';
      setTimeout(() => {
        if (window.LauncherUI) {
          window.LauncherUI.updateProgress({ message: successMsg });
          setTimeout(() => {
            window.LauncherUI.hideProgress();
            window.LauncherUI.showLauncherOrInstall(false);
          }, 2000);
        }
      }, 2000);
    }
  } catch (error) {
    const errorMsg = window.i18n ? window.i18n.t('progress.uninstallFailed').replace('{error}', error.message) : `Uninstall failed: ${error.message}`;
    if (window.LauncherUI) {
      window.LauncherUI.updateProgress({ message: errorMsg });
      setTimeout(() => window.LauncherUI.hideProgress(), 3000);
    }
  } finally {
    if (uninstallBtn) uninstallBtn.disabled = false;
  }
}

export async function repairGame() {
  showCustomConfirm(
    'Are you sure you want to repair Hytale? This will reinstall the game files but keep your data (saves, screenshots, etc.).',
    'Repair Game',
    async () => {
      await performRepair();
    },
    null,
    'Repair',
    'Cancel'
  );
}

async function performRepair() {
  if (window.LauncherUI) window.LauncherUI.showProgress();
  if (window.LauncherUI) window.LauncherUI.updateProgress({ message: 'Repairing game...' });
  isDownloading = true;

  try {
    if (window.electronAPI && window.electronAPI.repairGame) {
      const result = await window.electronAPI.repairGame();

      if (result.success) {
        if (window.LauncherUI) {
          window.LauncherUI.updateProgress({ message: 'Game repaired successfully!' });
          setTimeout(() => {
            window.LauncherUI.hideProgress();
          }, 2000);
        }
      } else {
        throw new Error(result.error || 'Repair failed');
      }
    }
  } catch (error) {
    if (window.LauncherUI) {
      window.LauncherUI.updateProgress({ message: `Repair failed: ${error.message}` });
      setTimeout(() => window.LauncherUI.hideProgress(), 3000);
    }
  } finally {
    isDownloading = false;
  }
}

function resetPlayButton() {
  isDownloading = false;
  const btn = homePlayBtn || playBtn;
  if (btn) {
    btn.disabled = false;
    const textEl = btn.querySelector('span');
    if (textEl) textEl.textContent = window.i18n ? window.i18n.t('play.playButton') : 'PLAY HYTALE';
  }
}

function lockPlayButton(text) {
  isDownloading = true;
  const btn = homePlayBtn || playBtn;
  if (btn) {
    btn.disabled = true;
    const textEl = btn.querySelector('span');
    if (textEl) textEl.textContent = text || 'LAUNCHING...';
  }
}

async function savePlayerName() {
  try {
    if (window.electronAPI && window.electronAPI.saveSettings) {
      const playerName = (playerNameInput ? playerNameInput.value.trim() : '') || 'Player';
      await window.electronAPI.saveSettings({ playerName });
    }
  } catch (error) {
    console.error('Error saving player name:', error);
  }
}

async function saveJavaPath() {
  try {
    if (window.electronAPI && window.electronAPI.saveSettings) {
      const javaPath = (javaPathInput ? javaPathInput.value.trim() : '') || '';
      await window.electronAPI.saveSettings({ javaPath });
    }
  } catch (error) {
    console.error('Error saving Java path:', error);
  }
}

function toggleCustomJava() {
  if (!customJavaOptions) return;

  if (customJavaCheck && customJavaCheck.checked) {
    customJavaOptions.style.display = 'block';
  } else {
    customJavaOptions.style.display = 'none';
    if (customJavaPath) customJavaPath.value = '';
    saveCustomJavaPath('');
  }
}

async function browseJavaPath() {
  try {
    if (window.electronAPI && window.electronAPI.browseJavaPath) {
      const result = await window.electronAPI.browseJavaPath();
      if (result && result.filePaths && result.filePaths.length > 0) {
        const selectedPath = result.filePaths[0];
        if (customJavaPath) {
          customJavaPath.value = selectedPath;
        }
        await saveCustomJavaPath(selectedPath);
      }
    }
  } catch (error) {
    console.error('Error browsing Java path:', error);
  }
}

async function saveCustomJavaPath(path) {
  try {
    if (window.electronAPI && window.electronAPI.saveJavaPath) {
      await window.electronAPI.saveJavaPath(path);
    }
  } catch (error) {
    console.error('Error saving custom Java path:', error);
  }
}

async function loadCustomJavaPath() {
  try {
    if (window.electronAPI && window.electronAPI.loadJavaPath) {
      const savedPath = await window.electronAPI.loadJavaPath();
      if (savedPath && savedPath.trim()) {
        if (customJavaPath) {
          customJavaPath.value = savedPath;
        }
        if (customJavaCheck) {
          customJavaCheck.checked = true;
        }
        if (customJavaOptions) {
          customJavaOptions.style.display = 'block';
        }
      }
    }
  } catch (error) {
    console.error('Error loading custom Java path:', error);
  }
}

// ==========================================
// IDENTITY SWITCHER
// ==========================================

function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

async function loadIdentities() {
  try {
    if (!window.electronAPI) return;

    const nameEl = document.getElementById('currentIdentityName');

    // Load current username
    let currentUsername = 'Player';
    if (window.electronAPI.loadUsername) {
      const name = await window.electronAPI.loadUsername();
      if (name) currentUsername = name;
    }
    if (nameEl) nameEl.textContent = currentUsername;

    // Load all identities for dropdown
    const list = document.getElementById('identityList');
    if (!list || !window.electronAPI.getAllUuidMappings) return;

    const mappings = await window.electronAPI.getAllUuidMappings();
    renderIdentityList(mappings, currentUsername);
  } catch (error) {
    console.error('Failed to load identities:', error);
  }
}

async function renderIdentityList(mappings, currentUsername) {
  const list = document.getElementById('identityList');
  if (!list) return;

  if (!mappings || mappings.length === 0) {
    list.innerHTML = '<div class="identity-empty">No identities</div>';
    return;
  }

  // Check password status for all identities in parallel
  const statusChecks = mappings.map(async m => {
    try {
      if (m.uuid && window.electronAPI?.checkPasswordStatus) {
        const s = await window.electronAPI.checkPasswordStatus(m.uuid);
        return s?.hasPassword || false;
      }
    } catch {}
    return false;
  });
  const statuses = await Promise.all(statusChecks);

  list.innerHTML = mappings.map((m, i) => {
    const safe = escapeHtml(m.username);
    const isActive = m.username === currentUsername;
    const hasPassword = statuses[i];
    const pwBadge = hasPassword
      ? '<span class="pw-badge locked"><i class="fas fa-lock"></i></span>'
      : '<span class="pw-badge unlocked"><i class="fas fa-unlock"></i></span>';
    return `
    <div class="identity-item ${isActive ? 'active' : ''}"
         onclick="switchIdentity('${safe.replace(/'/g, "&#39;")}')">
        <span>${safe}</span>
        ${pwBadge}
        ${isActive ? '<i class="fas fa-check" style="margin-left:4px;"></i>' : ''}
    </div>
  `;
  }).join('');
}

window.toggleIdentityDropdown = () => {
  const dropdown = document.getElementById('identityDropdown');
  if (dropdown) {
    dropdown.classList.toggle('show');
    // Close profile dropdown
    const profileDropdown = document.getElementById('profileDropdown');
    if (profileDropdown) profileDropdown.classList.remove('show');
  }
};

window.openIdentityManager = () => {
  // Close dropdown
  const dropdown = document.getElementById('identityDropdown');
  if (dropdown) dropdown.classList.remove('show');
  // Open UUID modal from settings
  if (window.openUuidModal) {
    window.openUuidModal();
  }
};

window.switchIdentity = async (username) => {
  try {
    if (!window.electronAPI || !window.electronAPI.saveUsername) return;

    const result = await window.electronAPI.saveUsername(username);
    if (result && result.success === false) {
      throw new Error(result.error || 'Failed to switch identity');
    }

    // Refresh identity dropdown
    await loadIdentities();

    // Close dropdown
    const dropdown = document.getElementById('identityDropdown');
    if (dropdown) dropdown.classList.remove('show');

    // Update settings page username field and UUID display
    const settingsInput = document.getElementById('settingsPlayerName');
    if (settingsInput) settingsInput.value = username;
    if (window.loadCurrentUuid) window.loadCurrentUuid();

    // Update password shield icon for new identity
    if (window.updatePasswordShieldIcon) window.updatePasswordShieldIcon();

  } catch (error) {
    console.error('Failed to switch identity:', error);
  }
};

// Make loadIdentities available globally for settings.js to call
window.loadIdentities = loadIdentities;

window.toggleProfileDropdown = () => {
  const dropdown = document.getElementById('profileDropdown');
  if (dropdown) {
    dropdown.classList.toggle('show');
    // Close identity dropdown
    const identityDropdown = document.getElementById('identityDropdown');
    if (identityDropdown) identityDropdown.classList.remove('show');
  }
};

window.launch = launch;
window.uninstallGame = uninstallGame;
window.repairGame = repairGame;

window.openLogs = async () => {
  if (window.LauncherUI) {
    window.LauncherUI.showPage('logs-page');
    window.LauncherUI.setActiveNav('logs');
  }
  await refreshLogs();
};

window.openLogsFolder = async () => {
  try {
    if (window.electronAPI && window.electronAPI.openLogsFolder) {
      await window.electronAPI.openLogsFolder();
    }
  } catch (error) {
    console.error('Failed to open logs folder:', error);
  }
};

window.refreshLogs = async () => {
  const terminal = document.getElementById('logsTerminal');
  if (!terminal) return;

  try {
    if (window.electronAPI && window.electronAPI.getRecentLogs) {
      // Fetch up to MAX_LOG_LINES lines
      const logs = await window.electronAPI.getRecentLogs(MAX_LOG_LINES);
      if (logs) {
        // Formatting for colors could be done here if needed
        terminal.textContent = logs;
        terminal.scrollTop = terminal.scrollHeight;
      } else {
        terminal.textContent = 'No logs available.';
      }
    }
  } catch (error) {
    terminal.textContent = 'Error loading logs: ' + error.message;
  }
};

window.copyLogs = () => {
  const terminal = document.getElementById('logsTerminal');
  if (terminal) {
    navigator.clipboard.writeText(terminal.textContent)
      .then(() => alert('Logs copied to clipboard!'))
      .catch(err => console.error('Failed to copy logs:', err));
  }
};

window.repairGame = repairGame;

// Constants
const MAX_LOG_LINES = 500;

document.addEventListener('DOMContentLoaded', setupLauncher);
