const {
  clamp,
  displayCompactDate,
  escapeHtml,
  formatNumber,
  formatTimestamp,
  localDateString,
  number,
  parseLocalDate,
  todayString,
} = window.XiaobaiUI;

const {
  emptyStateHtml,
  renderEmptyState,
} = window.XiaobaiComponents;


const state = window.XiaobaiState.create({
  session: {
    user: null,
    csrfToken: "",
    authMode: "login",
    started: false,
    activeView: "sentimentCycleView",
    dashboardLoading: false,
    dashboardRequestSequence: 0,
    dashboardRequestDate: "",
    adminModels: [],
    globalSearchResults: [],
    globalSearchActiveIndex: -1,
    globalSearchRequestSequence: 0,
  },
  market: {
    dashboard: null,
    filter: "all",
    query: "",
    sortKey: "streak",
    sortDirection: "desc",
    brokenQuery: "",
    brokenSortKey: "",
    brokenSortDirection: "desc",
    downQuery: "",
    downSortKey: "",
    downSortDirection: "asc",
    yesterdayFilter: "all",
    yesterdayQuery: "",
    yesterdaySortKey: "",
    yesterdaySortDirection: "desc",
    dragonTiger: null,
    dragonViewMode: "daily",
    dragonFilter: "all",
    dragonQuery: "",
    selectedDragonTraderId: "",
    hotMoneyProfiles: null,
    hotMoneyProfileQuery: "",
    selectedHotMoneyProfileId: "",
    rotationHistory: null,
    rotationHistoryKey: "",
    rotationSelectedSector: "",
    rotationSelectedDate: "",
    rotationMembers: null,
    rotationMembersKey: "",
    rotationMembersLoading: false,
    rotationOrder: localStorage.getItem("xiaobaiRotationOrder") === "latest" ? "latest" : "oldest",
    rotationLoading: false,
    auctionData: null,
    auctionDataset: "focus",
    auctionFilter: "all",
    auctionQuery: "",
    auctionSortKey: "attention_score",
    auctionSortDirection: "desc",
    auctionLoading: false,
    auctionTimer: null,
    themeLibrary: null,
    themeQuery: "",
    selectedThemeCode: "",
    themeDetail: null,
    themeLoading: false,
    popularityData: null,
    popularitySource: "combined",
    popularityQuery: "",
    popularityLoading: false,
    expandedLadderLevels: new Set(),
    ladderSortMode: "time",
    sentimentHistory: null,
    sentimentRange: 20,
    sentimentHistoryKey: "",
    sentimentLoading: false,
  },
  details: {
    stockDetail: null,
    activeStock: null,
    stockDetailChartMode: "daily",
    stockDetailIntraday: null,
    stockDetailRequestSequence: 0,
    entityDetailItem: null,
    entityDetailPayload: null,
    entityDetailChartMode: "daily",
    entityDetailIntraday: null,
    entityDetailRequestSequence: 0,
    stockPreviewCode: "",
    stockPreviewType: "stock",
    stockPreviewItem: null,
    stockPreviewPayload: null,
    stockPreviewChart: "daily",
    stockPreviewFallback: null,
    initialStockOpened: false,
  },
  review: {
    watchlist: [],
    watchlistSelection: null,
    watchlistSearchResults: [],
    watchlistSearchRequestSequence: 0,
    editingDailyNoteId: 0,
    notes: [],
    tradeEntries: [],
    tradeSummary: {},
    editingTradeId: 0,
    alerts: [],
    alertFilter: "all",
    alertUnreadCount: 0,
    assistantMessages: [],
    assistantLoading: false,
    assistantController: null,
  },
  screener: {
    screenerSetup: null,
    screenerSetupKey: "",
    screenerSetupRequestKey: "",
    screenerSetupPromise: null,
    selectedRegime: "",
    selectedStrategy: null,
    customStrategyDraft: null,
    screenerRunning: false,
    screenerRunningMode: "",
    screenerResults: { smart: null, curated: null, quant: null },
    screenerResultContexts: { smart: null, curated: null, quant: null },
    screenerResultStore: {},
    screenerArchiveView: "latest",
    screenerTracking: null,
    screenerMode: ["smart", "curated", "quant"].includes(localStorage.getItem("xiaobaiScreenerMode"))
      ? localStorage.getItem("xiaobaiScreenerMode")
      : "smart",
    curatedCategory: "全部",
    curatedSchool: "全部",
    curatedQuery: "",
    curatedViewMode: localStorage.getItem("xiaobaiCuratedViewMode") === "grid" ? "grid" : "list",
    selectedCuratedStrategyId: 0,
    quantFilters: [],
    quantScores: [],
    screenerMobileView: "strategy",
  },
  mentor: {
    mentorSetup: null,
    selectedMentorId: "",
    mentorMessages: [],
    mentorLoading: false,
    mentorQuery: "",
    mentorGrade: "all",
    mentorDirectoryOpen: false,
    mentorSortMode: false,
    mentorSavingPreferences: false,
    mentorController: null,
  },
  heaven: {
    heavenSetup: null,
    heavenManualData: null,
    personalField: null,
    heavenPanel: "trend",
    heavenInterpretations: { trend: "", fortune: "", heart: "" },
    heavenReadingMode: "trend",
    heavenReadingTab: "current",
    heavenReadingHistory: { trend: [], fortune: [], heart: [] },
    heavenReadingSelectedId: 0,
    heavenReadingLoading: false,
    heavenReadingError: "",
    heartStage: "intro",
    heartTimer: null,
    heartSeconds: HEART_BREATH_TOTAL_MS / 1000,
    heartBreathingEndsAt: 0,
    heartLines: [],
    heartThrows: [],
    heartHexagram: null,
    heartQuestion: "",
    heartQuestionPreset: "custom",
    heartCastAt: "",
    heartCurtainTimer: null,
    heartStageToken: 0,
    heartRevealToken: 0,
    heavenPerformanceKey: "",
    heavenPerformancePanels: new Set(),
    heavenPerformanceActive: "",
    heavenRequestSequence: 0,
  },
});


const elements = {
  tradeDate: document.querySelector("#tradeDate"),
  loading: document.querySelector("#loadingOverlay"),
  toast: document.querySelector("#toast"),
  stockDialog: document.querySelector("#stockDialog"),
  tradeLogDialog: document.querySelector("#tradeLogDialog"),
  watchlistDialog: document.querySelector("#watchlistDialog"),
  alertsDialog: document.querySelector("#alertsDialog"),
  assistantDialog: document.querySelector("#assistantDialog"),
  heavenReadingDialog: document.querySelector("#heavenReadingDialog"),
  globalSearchDialog: document.querySelector("#globalSearchDialog"),
  globalSearchInput: document.querySelector("#globalSearchInput"),
  globalSearchResults: document.querySelector("#globalSearchResults"),
  entityDetailDialog: document.querySelector("#entityDetailDialog"),
  entityDetailChart: document.querySelector("#entityDetailChart"),
  settingsDialog: document.querySelector("#settingsDialog"),
  adminDialog: document.querySelector("#adminDialog"),
  priceChart: document.querySelector("#priceChart"),
  stockPreview: document.querySelector("#stockPreview"),
  stockPreviewBackdrop: document.querySelector("#stockPreviewBackdrop"),
  stockPreviewChart: document.querySelector("#stockPreviewChart"),
};
