
import {
  AggregationModule,ServerSideRowModelApiModule ,UndoRedoEditModule,  CellStyleModule,
  ClientSideRowModelModule,
  ColumnAutoSizeModule,
  LargeTextEditorModule,
  LocaleModule,
  ModuleRegistry,
  NumberEditorModule,
  PinnedRowModule,
  RowAutoHeightModule,
  TextEditorModule,
  TooltipModule,ClientSideRowModelApiModule ,
RenderApiModule  ,ColumnApiModule ,CellSpanModule ,RowStyleModule ,RowSelectionModule ,
  CellSelectionModule,
  ClipboardModule,ScrollApiModule ,
  LicenseManager,
  RowGroupingModule,
  TreeDataModule,ContextMenuModule,ValidationModule 
} from 'ag-grid-enterprise'
import { createPinia } from 'pinia'
import piniaPersistedstate from '@/pinia/Plugin/indexdb'
import { useUiPrefsStore } from '@/pinia/uiPrefs'
import { createApp } from 'vue'
import App from './App.vue'
import './style.css'
import { i18n } from '@/i18n'
import { ensureProjectIdInUrl, getProjectDbName } from '@/lib/workspace'
import { listProjects } from '@/lib/projectRegistry'

LicenseManager.setLicenseKey(
  '[v3][RELEASE][0102]_NDg2Njc4MzY3MDgzNw==16d78ca762fb5d2ff740aed081e2af7b'
)

const AG_GRID_MODULES = [
  ClientSideRowModelModule,
  ColumnAutoSizeModule,
  TextEditorModule,
  NumberEditorModule,
  RowAutoHeightModule,ContextMenuModule,
  LargeTextEditorModule,
  UndoRedoEditModule,
  CellStyleModule,ClientSideRowModelApiModule ,
  PinnedRowModule,RenderApiModule  ,ColumnApiModule ,
  TooltipModule,
  TreeDataModule,ScrollApiModule ,
  AggregationModule,
  RowGroupingModule,
  CellSelectionModule,
  ClipboardModule,
  LocaleModule,ValidationModule ,CellSpanModule ,RowStyleModule ,RowSelectionModule ,ServerSideRowModelApiModule 
]

const pickBootstrapProjectId = () => {
  try {
    const url = new URL(window.location.href)
    const explicit = String(url.searchParams.get('projectId') || '').trim()
    if (explicit) return ensureProjectIdInUrl()
    const projects = listProjects()
    if (projects.length > 0) {
      const lastEdited = projects[0]
      url.searchParams.set('projectId', lastEdited.id)
      window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`)
    }
    return ensureProjectIdInUrl()
  } catch {
    return ensureProjectIdInUrl()
  }
}

const pinia = createPinia()
const currentProjectId = pickBootstrapProjectId()
pinia.use(
  piniaPersistedstate({
    name: getProjectDbName(currentProjectId),
    storeName: 'pinia',
    mode: 'multiple'
  })
)
const uiPrefsStore = useUiPrefsStore(pinia)
uiPrefsStore.initFromStorage()

// 在应用启动时一次性注册 AG Grid 运行所需模块。
ModuleRegistry.registerModules(AG_GRID_MODULES)

createApp(App).use(pinia).use(i18n).mount('#app')
