import { loadSettings, saveSettings } from "./storage.js";

const initialSettings = loadSettings();

const state = {
  settings: initialSettings,
  selectedRepoPath: initialSettings.lastSelectedRepoPath || "",
  selectedRepoName: initialSettings.lastSelectedRepoPath ? initialSettings.lastSelectedRepoPath.split(/[/\\]/).filter(Boolean).pop() || "" : "",
  repoSearch: "",
  changesFilter: "",
  historyFilter: "",
  commitSummary: "",
  commitDescription: "",
  localRepoPathInput: "",
  localRepoScanRootInput: "",
  localRepoScanResults: [],
  localRepoScanLoading: false,
  localRepoScanError: "",
  installedIdes: [],
  installedIdeScanLoading: false,
  installedIdeScanError: "",
  cloneUrlInput: "",
  cloneDestinationInput: "",
  commitMessage: "",
  workingTree: {
    loading: false,
    error: "",
    branch: "",
    upstream: "",
    ahead: 0,
    behind: 0,
    files: [],
    selectedPaths: new Set(),
    selectedPath: "",
    selectedDiff: null,
    diffLoading: false,
    diffError: "",
  },
  sync: {
    loading: false,
    error: "",
    operation: "",
    branch: "",
    upstream: "",
    upstreamRemote: "",
    defaultRemote: "",
    ahead: 0,
    behind: 0,
    hasRemote: false,
    isDetached: false,
    isUnpublished: false,
    lastUpdated: 0,
  },
  branches: {
    loading: false,
    error: "",
    items: [],
    createName: "",
    menuOpen: false,
    switchingTo: "",
    dialog: {
      mode: "",
      target: "",
      value: "",
      error: "",
    },
  },
  history: {
    loading: false,
    error: "",
    commits: [],
    selectedHash: "",
    selectedCommit: null,
  },
  viewer: {
    source: "",
    repoName: "",
    repoPath: "",
    cloneUrl: "",
    defaultBranch: "",
    branch: "",
    branches: [],
    path: "",
    entries: [],
    selectedFile: null,
    readmeFile: null,
    loading: false,
    error: "",
  },
};

export function getState() {
  return state;
}

export function setSettings(nextSettings) {
  state.settings = nextSettings;
  saveSettings(state.settings);
}

export function updateSettings(patch) {
  setSettings({ ...state.settings, ...patch });
}

export function addRecentRepo(path) {
  if (!path) return;
  const current = state.settings.recentRepositories.filter((item) => item !== path);
  const next = [path, ...current].slice(0, 15);
  updateSettings({ recentRepositories: next, lastSelectedRepoPath: path });
}

export function getActiveServer() {
  const { activeServerId, servers } = state.settings;
  return servers.find((server) => server.id === activeServerId) ?? null;
}
