import { appState } from './shared.js';
import { networkStatePart, fetchNetworkStatsAction } from './network.js';
import { certificateStatePart, fetchCertificateOverviewAction } from './certificates.js';

export interface IUiState {
  activeView: string;
  activeSubview: string | null;
  sidebarCollapsed: boolean;
  autoRefresh: boolean;
  refreshInterval: number; // milliseconds
  theme: 'light' | 'dark';
}

// Determine initial view from URL path
const getInitialView = (): string => {
  const path = typeof window !== 'undefined' ? window.location.pathname : '/';
  const validViews = ['overview', 'network', 'email', 'logs', 'access', 'security', 'domains'];
  const segments = path.split('/').filter(Boolean);
  const view = segments[0];
  return validViews.includes(view) ? view : 'overview';
};

// Determine initial subview (second URL segment) from the path
const getInitialSubview = (): string | null => {
  const path = typeof window !== 'undefined' ? window.location.pathname : '/';
  const segments = path.split('/').filter(Boolean);
  return segments[1] ?? null;
};

export const uiStatePart = await appState.getStatePart<IUiState>(
  'ui',
  {
    activeView: getInitialView(),
    activeSubview: getInitialSubview(),
    sidebarCollapsed: false,
    autoRefresh: true,
    refreshInterval: 1000, // 1 second
    theme: 'light',
  },
);

// Toggle Auto Refresh Action
export const toggleAutoRefreshAction = uiStatePart.createAction(async (statePartArg): Promise<IUiState> => {
  const currentState = statePartArg.getState()!;
  return {
    ...currentState,
    autoRefresh: !currentState.autoRefresh,
  };
});

// Set Active View Action
export const setActiveViewAction = uiStatePart.createAction<string>(async (statePartArg, viewName): Promise<IUiState> => {
  const currentState = statePartArg.getState()!;

  // If switching to network view, ensure we fetch network data
  if (viewName === 'network' && currentState.activeView !== 'network') {
    setTimeout(() => {
      networkStatePart.dispatchAction(fetchNetworkStatsAction, null);
    }, 100);
  }

  // If switching to the Domains group, ensure we fetch certificate data
  // (Certificates is a subview of Domains).
  if (viewName === 'domains' && currentState.activeView !== 'domains') {
    setTimeout(() => {
      certificateStatePart.dispatchAction(fetchCertificateOverviewAction, null);
    }, 100);
  }

  return {
    ...currentState,
    activeView: viewName,
  };
});

