import type {
  AsukaInlineLayoutModuleDefinition,
  LayoutConfig,
  LayoutItemConfig,
  LayoutZoneId,
} from '../types/layout';
import { registerModule, type AsukaModuleDefinition } from './modules';

const LAYOUT_ZONES: LayoutZoneId[] = ['top', 'bottom', 'left', 'right'];

function nonEmptyString(value: unknown): string | undefined {
  return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}

/**
 * Register custom modules declared inside init-time layout items and return a
 * layout copy containing presentation data only.
 */
export function registerInlineLayoutModules(config: LayoutConfig): LayoutConfig {
  if (!config || typeof config !== 'object') return config;

  const next: LayoutConfig = { ...config };

  for (const zone of LAYOUT_ZONES) {
    const zoneConfig = config[zone];
    if (!zoneConfig || !Array.isArray(zoneConfig.items)) continue;

    next[zone] = {
      ...zoneConfig,
      items: zoneConfig.items.map((rawItem) => {
        if (!rawItem || typeof rawItem !== 'object') return rawItem;

        const item = rawItem as LayoutItemConfig;
        const { module: inlineModule, ...serializableItem } = item;
        const kind = nonEmptyString(item.kind);

        if (!kind || !inlineModule || typeof inlineModule !== 'object' || Array.isArray(inlineModule)) {
          return serializableItem as LayoutItemConfig;
        }

        const definition = inlineModule as AsukaInlineLayoutModuleDefinition;
        registerModule({
          ...definition,
          id: kind,
          label: definition.label ?? nonEmptyString(item.label) ?? kind,
          icon: definition.icon ?? nonEmptyString(item.icon),
          displayMode: definition.displayMode ?? item.type,
          supportedEngines: definition.supportedEngines ?? item.supportedEngines,
          requiredCapabilities: definition.requiredCapabilities ?? item.requiredCapabilities,
          mountTarget: definition.mountTarget ?? nonEmptyString(item.mountTarget),
        } as AsukaModuleDefinition);

        return serializableItem as LayoutItemConfig;
      }),
    };
  }

  return next;
}
