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;
  showBounds?: boolean;
}

/**
 * 处理 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) => (
        <>
          <article
            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)}
          />
          {props.showBounds && (
            <div
              class="absolute border-2 border-blue-500/50 pointer-events-none select-none"
              style={{
                left: `${(layer.x1 - 1) * props.dimensions.cellWidth}mm`,
                top: `${(layer.y1 - 1) * props.dimensions.cellHeight}mm`,
                width: `${(layer.x2 - layer.x1 + 1) * props.dimensions.cellWidth}mm`,
                height: `${(layer.y2 - layer.y1 + 1) * props.dimensions.cellHeight}mm`
              }}
            />
          )}
        </>
      )}
    </For>
  );
}
