import { For } from 'solid-js';
import { marked } from '../../markdown';
import { getLayerStyle } from './hooks/dimensions';
import type { LayerConfig, Dimensions, CardData } from './types';

export interface CardLayerProps {
  layers: LayerConfig[];
  dimensions: Dimensions;
  cardData: CardData;
}

/**
 * 处理 body 内容中的 {{prop}} 语法并解析 markdown
 */
function processBody(body: string, currentRow: CardData): string {
  const processedBody = body.replace(/\{\{(\w+)\}\}/g, (_, key) => currentRow[key] || '');
  return marked.parse(processedBody) as string;
}

/**
 * 渲染 layer 内容
 */
function renderLayerContent(layer: { prop: string }, cardData: CardData): string {
  const content = cardData[layer.prop] || '';
  return processBody(content, cardData);
}

export function CardLayer(props: CardLayerProps) {
  return (
    <For each={props.layers}>
      {(layer) => (
        <div
          class="absolute flex items-center justify-center text-center prose prose-sm"
          style={{
            ...getLayerStyle(layer, props.dimensions),
            'font-size': `${props.dimensions.fontSize}mm`
          }}
          innerHTML={renderLayerContent(layer, props.cardData)}
        />
      )}
    </For>
  );
}
