import 'server-only';

import { getWidgetData } from '@akinon/next/data/server';

export interface ThemeCheckoutSettings {
  variant?: string;
  options?: Record<string, unknown>;
}

interface ThemeSettings {
  logo?: string;
  favicon?: string;
  plainHeader?: boolean;
  fontFamily?: string;
  backupFontFamily?: string;
  fontWeight?: string;
  fontSubsets?: string;
  fontSize?: string;
  fontColor?: string;
  fontOpacity?: number;
  mainMenuSticky?: boolean;
  breadcrumbSeparator?: string;
  socialNetworks?: Record<string, { url?: string; icon?: string }>;
  checkout?: ThemeCheckoutSettings;
}

/**
 * Fetches theme configuration from the widget API
 * This is a server-side function that reads theme settings stored in the theme-config widget
 */
export async function getThemeSettings(): Promise<ThemeSettings> {
  try {
    const themeConfigData = await getWidgetData<any>({
      slug: 'theme-config'
    });

    if (!themeConfigData?.attributes?.theme_settings?.value) {
      return {};
    }

    // Parse the theme_settings JSON string from the value property
    const settings: ThemeSettings = JSON.parse(
      themeConfigData.attributes.theme_settings.value
    );

    return settings;
  } catch (error) {
    console.error('Error loading theme settings:', error);
    return {};
  }
}
